rector/rules/psr4/src/Composer/PSR4AutoloadPathsProvider.php

64 lines
1.8 KiB
PHP
Raw Normal View History

2019-10-13 07:59:52 +02:00
<?php
declare(strict_types=1);
namespace Rector\PSR4\Composer;
2021-01-31 21:06:14 +01:00
use Symplify\ComposerJsonManipulator\ValueObject\ComposerJsonSection;
use Symplify\SmartFileSystem\Json\JsonFileSystem;
final class PSR4AutoloadPathsProvider
{
/**
* @var array<string, array<string, string>>
*/
private $cachedComposerJsonPSR4AutoloadPaths = [];
/**
* @var JsonFileSystem
*/
private $jsonFileSystem;
public function __construct(JsonFileSystem $jsonFileSystem)
{
$this->jsonFileSystem = $jsonFileSystem;
}
/**
* @return array<string, array<string, string>>
*/
public function provide(): array
{
if ($this->cachedComposerJsonPSR4AutoloadPaths !== []) {
return $this->cachedComposerJsonPSR4AutoloadPaths;
}
$composerJson = $this->jsonFileSystem->loadFilePathToJson($this->getComposerJsonPath());
$psr4Autoloads = array_merge(
2021-01-31 21:06:14 +01:00
$composerJson[ComposerJsonSection::AUTOLOAD]['psr-4'] ?? [],
$composerJson[ComposerJsonSection::AUTOLOAD_DEV]['psr-4'] ?? []
);
$this->cachedComposerJsonPSR4AutoloadPaths = $this->removeEmptyNamespaces($psr4Autoloads);
return $this->cachedComposerJsonPSR4AutoloadPaths;
}
private function getComposerJsonPath(): string
{
// assume the project has "composer.json" in root directory
return getcwd() . '/composer.json';
}
/**
* @param array<string, array<string, string>> $psr4Autoloads
* @return array<string, array<string, string>>
*/
private function removeEmptyNamespaces(array $psr4Autoloads): array
{
2020-04-25 16:45:36 +02:00
return array_filter($psr4Autoloads, function (string $psr4Autoload): bool {
return $psr4Autoload !== '';
}, ARRAY_FILTER_USE_KEY);
}
}