2019-10-13 07:59:52 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
2019-08-18 12:56:56 +02:00
|
|
|
|
|
|
|
namespace Rector\PSR4\Composer;
|
|
|
|
|
|
|
|
use Nette\Utils\Json;
|
2020-07-24 14:21:34 +02:00
|
|
|
use Symplify\SmartFileSystem\SmartFileSystem;
|
2019-08-18 12:56:56 +02:00
|
|
|
|
|
|
|
final class PSR4AutoloadPathsProvider
|
|
|
|
{
|
|
|
|
/**
|
2020-08-11 12:59:04 +02:00
|
|
|
* @var array<string, string[]>
|
2019-08-18 12:56:56 +02:00
|
|
|
*/
|
|
|
|
private $cachedComposerJsonPSR4AutoloadPaths = [];
|
|
|
|
|
2020-07-24 14:21:34 +02:00
|
|
|
/**
|
|
|
|
* @var SmartFileSystem
|
|
|
|
*/
|
|
|
|
private $smartFileSystem;
|
|
|
|
|
|
|
|
public function __construct(SmartFileSystem $smartFileSystem)
|
|
|
|
{
|
|
|
|
$this->smartFileSystem = $smartFileSystem;
|
|
|
|
}
|
|
|
|
|
2019-08-18 12:56:56 +02:00
|
|
|
/**
|
2020-08-11 12:59:04 +02:00
|
|
|
* @return array<string, string[]>
|
2019-08-18 12:56:56 +02:00
|
|
|
*/
|
|
|
|
public function provide(): array
|
|
|
|
{
|
|
|
|
if ($this->cachedComposerJsonPSR4AutoloadPaths !== []) {
|
|
|
|
return $this->cachedComposerJsonPSR4AutoloadPaths;
|
|
|
|
}
|
|
|
|
|
|
|
|
$composerJson = $this->readFileToJsonArray($this->getComposerJsonPath());
|
|
|
|
$psr4Autoloads = array_merge(
|
|
|
|
$composerJson['autoload']['psr-4'] ?? [],
|
|
|
|
$composerJson['autoload-dev']['psr-4'] ?? []
|
|
|
|
);
|
|
|
|
|
|
|
|
$this->cachedComposerJsonPSR4AutoloadPaths = $this->removeEmptyNamespaces($psr4Autoloads);
|
|
|
|
|
|
|
|
return $this->cachedComposerJsonPSR4AutoloadPaths;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return mixed[]
|
|
|
|
*/
|
|
|
|
private function readFileToJsonArray(string $composerJson): array
|
|
|
|
{
|
2020-07-24 14:21:34 +02:00
|
|
|
$composerJsonContent = $this->smartFileSystem->readFile($composerJson);
|
2019-08-18 12:56:56 +02:00
|
|
|
|
|
|
|
return Json::decode($composerJsonContent, Json::FORCE_ARRAY);
|
|
|
|
}
|
|
|
|
|
2019-10-30 10:49:07 +01:00
|
|
|
private function getComposerJsonPath(): string
|
|
|
|
{
|
|
|
|
// assume the project has "composer.json" in root directory
|
|
|
|
return getcwd() . '/composer.json';
|
|
|
|
}
|
|
|
|
|
2019-08-18 12:56:56 +02:00
|
|
|
/**
|
2020-08-11 12:59:04 +02:00
|
|
|
* @param array<string, string[]> $psr4Autoloads
|
|
|
|
* @return array<string, string[]>
|
2019-08-18 12:56:56 +02:00
|
|
|
*/
|
|
|
|
private function removeEmptyNamespaces(array $psr4Autoloads): array
|
|
|
|
{
|
2020-04-25 16:45:36 +02:00
|
|
|
return array_filter($psr4Autoloads, function (string $psr4Autoload): bool {
|
|
|
|
return $psr4Autoload !== '';
|
2019-08-18 12:56:56 +02:00
|
|
|
}, ARRAY_FILTER_USE_KEY);
|
|
|
|
}
|
|
|
|
}
|