From d43890541b5a3dd23d79c3cfe6eb207b5dfd0f10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Bar=C3=A1=C5=A1ek?= Date: Sun, 12 Jan 2020 22:24:00 +0100 Subject: [PATCH] Code simplyfi + better code style + better performance + mark business logic as final. --- src/Console.php | 2 +- src/Exceptions/PackageDescriptorException.php | 12 ++ src/Generator.php | 57 +++------ src/Helpers.php | 36 +++--- .../InteractiveComposer.php | 2 +- src/PackageManagerExtension.php | 11 +- src/PackageRegistrator.php | 120 +++++++----------- src/Storage.php | 2 +- 8 files changed, 98 insertions(+), 144 deletions(-) diff --git a/src/Console.php b/src/Console.php index 6eb03da..f0d1a59 100644 --- a/src/Console.php +++ b/src/Console.php @@ -12,7 +12,7 @@ use Nette\DI\Container; use Tracy\Debugger; -class Console +final class Console { /** diff --git a/src/Exceptions/PackageDescriptorException.php b/src/Exceptions/PackageDescriptorException.php index 21f13a8..e260e63 100644 --- a/src/Exceptions/PackageDescriptorException.php +++ b/src/Exceptions/PackageDescriptorException.php @@ -38,4 +38,16 @@ public static function tempFileGeneratingError(string $path): void ); } + /** + * @param string $path + * @throws PackageDescriptorException + */ + public static function canNotRewritePackageNeon(string $path): void + { + throw new self( + 'Can not rewrite package.neon. Path: "' . $path . '"' + . "\n" . error_get_last()['message'] + ); + } + } \ No newline at end of file diff --git a/src/Generator.php b/src/Generator.php index cd9b925..649500f 100644 --- a/src/Generator.php +++ b/src/Generator.php @@ -9,9 +9,8 @@ use Baraja\PackageManager\Exception\PackageDescriptorException; use Composer\Autoload\ClassLoader; use Nette\Neon\Neon; -use Nette\Utils\Strings; -class Generator +final class Generator { /** @@ -46,19 +45,16 @@ public function __construct(string $projectRoot, array $customPackagesNamePatter * @return PackageDescriptorEntity * @throws PackageDescriptorException */ - public function generate(): PackageDescriptorEntity + public function run(): PackageDescriptorEntity { $packageDescriptor = new PackageDescriptorEntity($this->customPackagesNamePatterns); $composerJson = $this->storage->haystackToArray( - json_decode( - (string) file_get_contents($this->projectRoot . '/composer.json') - ) + json_decode((string) file_get_contents($this->projectRoot . '/composer.json')) ); - $packages = $this->getPackages($composerJson); $packageDescriptor->setComposer($composerJson); - $packageDescriptor->setPackages($packages); + $packageDescriptor->setPackages($packages = $this->getPackages($composerJson)); $customRouters = []; $afterInstallScripts = []; @@ -85,7 +81,7 @@ public function generate(): PackageDescriptorEntity /** * @param string[][] $composer - * @return string[][] + * @return string[][]|string[][][]|string[][][][] * @throws PackageDescriptorException */ private function getPackages(array $composer): array @@ -98,16 +94,8 @@ private function getPackages(array $composer): array $packagesVersions = []; } - $allPackages = array_merge( - $composer['require'], - $packagesVersions - ); - - foreach ($allPackages as $packageName => $dependency) { - $packageName = Strings::lower($packageName); - $path = $this->projectRoot . '/vendor/' . $packageName; - - if (!is_dir($path)) { + foreach (array_merge($composer['require'], $packagesVersions) as $name => $dependency) { + if (is_dir($path = $this->projectRoot . '/vendor/' . ($name = mb_strtolower($name, 'UTF-8'))) === false) { continue; } @@ -118,26 +106,19 @@ private function getPackages(array $composer): array $configPath = $path . '/config.neon'; } - $composerPath = $path . '/composer.json'; - - if (is_file($composerPath) && json_decode(file_get_contents($composerPath)) === null) { - PackageDescriptorCompileException::composerJsonIsBroken($packageName); + if (is_file($composerPath = $path . '/composer.json') && json_decode(file_get_contents($composerPath)) === null) { + PackageDescriptorCompileException::composerJsonIsBroken($name); } - $item = [ - 'name' => $packageName, - 'version' => $packagesVersions[$packageName] ?? null, + $packages[] = [ + 'name' => $name, + 'version' => $packagesVersions[$name] ?? null, 'dependency' => $dependency, 'config' => $configPath !== null ? $this->formatConfigSections($configPath) : null, 'composer' => is_file($composerPath) - ? $this->storage->haystackToArray( - json_decode( - file_get_contents($composerPath) - ) - ) : null, + ? $this->storage->haystackToArray(json_decode(file_get_contents($composerPath))) + : null, ]; - - $packages[] = $item; } return $packages; @@ -150,15 +131,13 @@ private function getPackages(array $composer): array private function formatConfigSections(string $path): array { $return = []; - $neon = Neon::decode(file_get_contents($path)); - foreach (\is_array($neon) ? $neon : [] as $part => $haystack) { + foreach (\is_array($neon = Neon::decode(file_get_contents($path))) ? $neon : [] as $part => $haystack) { if ($part === 'services') { $servicesList = ''; - foreach ($haystack as $serviceKey => $serviceClass) { - $servicesList .= (\is_int($serviceKey) ? '- ' : $serviceKey . ': ') - . Neon::encode($serviceClass) . "\n"; + foreach ($haystack as $key => $serviceClass) { + $servicesList .= (\is_int($key) ? '- ' : $key . ': ') . Neon::encode($serviceClass) . "\n"; } $return[$part] = [ @@ -192,7 +171,7 @@ private function getPackagesVersions(): array $lockFile = null; } - if (!is_file($lockFile)) { + if (is_file($lockFile) === false) { PackageDescriptorCompileException::canNotLoadComposerLock($lockFile); } diff --git a/src/Helpers.php b/src/Helpers.php index 99767fd..bfd8f71 100644 --- a/src/Helpers.php +++ b/src/Helpers.php @@ -6,19 +6,24 @@ use Baraja\PackageManager\Exception\PackageDescriptorException; -use Nette\StaticClass; -class Helpers +final class Helpers { - use StaticClass; + /** + * @throws \Error + */ + public function __construct() + { + throw new \Error('Class ' . get_class($this) . ' is static and cannot be instantiated.'); + } /** * @param mixed[] $array1 * @param mixed[] $array2 - * @return mixed + * @return mixed[] */ - public static function recursiveMerge(array &$array1, array &$array2) + public static function recursiveMerge(array &$array1, array &$array2): array { $merged = $array1; @@ -44,12 +49,8 @@ public static function functionIsAvailable(string $functionName): bool static $disabled; if (\function_exists($functionName)) { - if ($disabled === null) { - $disableFunctions = ini_get('disable_functions'); - - if (\is_string($disableFunctions)) { - $disabled = explode(',', $disableFunctions) ? : []; - } + if ($disabled === null && \is_string($disableFunctions = ini_get('disable_functions'))) { + $disabled = explode(',', $disableFunctions) ? : []; } return \in_array($functionName, $disabled, true) === false; @@ -67,14 +68,12 @@ public static function functionIsAvailable(string $functionName): bool public static function terminalRenderCode(string $path, int $line = null): void { echo "\n" . $path . ($line === null ? '' : ' [on line ' . $line . ']') . "\n\n"; - if (\is_file($path)) { + if (\is_file($path) === true) { echo '----- file -----' . "\n"; - $file = str_replace(["\r\n", "\r"], "\n", (string) file_get_contents($path)); - $fileParser = explode("\n", $file); - $start = $line > 8 ? $line - 8 : 0; + $fileParser = explode("\n", str_replace(["\r\n", "\r"], "\n", (string) file_get_contents($path))); - for ($i = $start; $i <= $start + 15; $i++) { - if (!isset($fileParser[$i])) { + for ($i = ($start = $line > 8 ? $line - 8 : 0); $i <= $start + 15; $i++) { + if (isset($fileParser[$i]) === false) { break; } @@ -135,10 +134,9 @@ public static function terminalInteractiveAsk(string $question, ?array $possibil throw new PackageDescriptorException('Problem with opening "php://stdin".'); } - $input = trim((string) fgets($fOpen)); echo "\n"; - $input = $input === '' ? null : $input; + $input = ($input = trim((string) fgets($fOpen))) === '' ? null : $input; if ($possibilities !== [] && $possibilities !== null) { if (\in_array($input, $possibilities, true)) { diff --git a/src/InteractiveComposer/InteractiveComposer.php b/src/InteractiveComposer/InteractiveComposer.php index 3c9f769..5a31681 100644 --- a/src/InteractiveComposer/InteractiveComposer.php +++ b/src/InteractiveComposer/InteractiveComposer.php @@ -12,7 +12,7 @@ use Baraja\PackageManager\Composer\ITask; use Baraja\PackageManager\Exception\TaskException; -class InteractiveComposer +final class InteractiveComposer { /** diff --git a/src/PackageManagerExtension.php b/src/PackageManagerExtension.php index 3d33016..ba06863 100644 --- a/src/PackageManagerExtension.php +++ b/src/PackageManagerExtension.php @@ -17,13 +17,10 @@ class PackageManagerExtension extends CompilerExtension */ public function afterCompile(ClassType $class): void { - $initialize = $class->getMethod('initialize'); - - if (PHP_SAPI === 'cli' && class_exists(Application::class)) { - $initialize->setBody( - $initialize->getBody() . "\n" - . Console::class . '::setContainer($this);' . "\n" - . 'register_shutdown_function([' . Console::class . '::class, \'run\']);' + if (PHP_SAPI === 'cli' && class_exists(Application::class) === true) { + $class->getMethod('initialize')->addBody( + Console::class . '::setContainer($this);' + . "\n" . 'register_shutdown_function([' . Console::class . '::class, \'run\']);' ); } } diff --git a/src/PackageRegistrator.php b/src/PackageRegistrator.php index 554d319..4a1cd46 100644 --- a/src/PackageRegistrator.php +++ b/src/PackageRegistrator.php @@ -20,7 +20,7 @@ class PackageRegistrator /** * @var bool */ - private static $singleton = false; + private static $created = false; /** * @var string @@ -57,25 +57,35 @@ class PackageRegistrator */ private static $runAfterScripts = false; + /** + * @var string[] + */ + private static $neonNoUseParams = [ + 'includes' => true, + 'application' => true, + 'menu' => true, + 'routers' => true, + 'afterInstall' => true, + ]; + /** * @param string|null $projectRoot * @param string|null $tempPath */ - public function __construct(string $projectRoot = null, string $tempPath = null) + public function __construct(?string $projectRoot = null, ?string $tempPath = null) { - if (self::$singleton === true) { + if (self::$created === true || $projectRoot === null || $tempPath === null) { return; } - self::$singleton = true; + self::$created = true; self::$projectRoot = rtrim($projectRoot, '/'); self::$configPath = self::$projectRoot . '/app/config/common.neon'; self::$configPackagePath = self::$projectRoot . '/app/config/package.neon'; self::$configLocalPath = self::$projectRoot . '/app/config/local.neon'; - $storage = new Storage($tempPath); - try { + $storage = new Storage($tempPath); try { self::$packageDescriptorEntity = $storage->load(); @@ -84,9 +94,7 @@ public function __construct(string $projectRoot = null, string $tempPath = null) } } catch (PackageEntityDoesNotExistsException $e) { $storage->save( - self::$packageDescriptorEntity = ( - new Generator($projectRoot, $this->getCustomPackageNamePatters(), $storage) - )->generate(), + self::$packageDescriptorEntity = (new Generator($projectRoot, $this->getPackageNamePatterns(), $storage))->run(), $this->getComposerHash() ); $this->createPackageConfig(self::$packageDescriptorEntity); @@ -101,11 +109,7 @@ public function __construct(string $projectRoot = null, string $tempPath = null) public static function composerPostAutoloadDump(): void { try { - $interactiveComposer = new InteractiveComposer( - new self(__DIR__ . '/../../../../', __DIR__ . '/../../../../temp/') - ); - - $interactiveComposer->run(); + (new InteractiveComposer(new self(__DIR__ . '/../../../../', __DIR__ . '/../../../../temp/')))->run(); } catch (\Exception $e) { Helpers::terminalRenderError($e->getMessage()); Helpers::terminalRenderCode($e->getFile(), $e->getLine()); @@ -127,12 +131,8 @@ public static function getPackageDescriptorEntityStatic(): PackageDescriptorEnti */ public function getParameters(): array { - if (self::$parameters === null) { - $configNeon = Neon::decode(file_get_contents(self::$configPath)); - - if (isset($configNeon['parameters'])) { - self::$parameters = $configNeon['parameters']; - } + if (self::$parameters === null && isset(($configNeon = Neon::decode(file_get_contents(self::$configPath)))['parameters'])) { + self::$parameters = $configNeon['parameters']; } return self::$parameters ?? []; @@ -141,14 +141,13 @@ public function getParameters(): array /** * @return string[] */ - public function getCustomPackageNamePatters(): array + public function getPackageNamePatterns(): array { $return = ['^baraja-']; $packageRegistrator = $this->getParameters()['packageRegistrator'] ?? null; - $cuPaNaPa = 'customPackagesNamePatterns'; - if (isset($packageRegistrator[$cuPaNaPa]) && \is_array($packageRegistrator[$cuPaNaPa])) { - return \array_merge($return, $packageRegistrator[$cuPaNaPa]); + if (isset($packageRegistrator[$key = 'customPackagesNamePatterns']) && \is_array($packageRegistrator[$key])) { + return \array_merge($return, $packageRegistrator[$key]); } return $return; @@ -204,38 +203,23 @@ public function isPackageInstalled(string $packageName): bool */ public function runAfterActions(Configurator $configurator): void { - static $singleton = false; - - if ($singleton === true) { - return; - } - - $singleton = true; - - if (self::$runAfterScripts === true) { - $containerClass = $configurator->loadContainer(); - /** @var Container $container */ - $container = new $containerClass; - - $someChanged = false; - - foreach (self::$packageDescriptorEntity->getAfterInstallScripts() as $script) { - if (\class_exists($script)) { - /** @var IAfterInstall $instance */ - $instance = new $script($container, $this); - if ($instance->run() === true) { - $someChanged = true; + static $created = false; + + if ($created === false) { + $created = true; + if (self::$runAfterScripts === true) { + $containerClass = $configurator->loadContainer(); + /** @var Container $container */ + $container = new $containerClass; + + foreach (self::$packageDescriptorEntity->getAfterInstallScripts() as $script) { + if (\class_exists($script) === true) { + /** @var IAfterInstall $instance */ + $instance = new $script($container, $this); + $instance->run(); } } } - - if ($someChanged === true) { - echo "\n\n"; - echo '----------------------------------------------------' . "\n"; - echo '---------------- PLEASE RELOAD PAGE ----------------' . "\n"; - echo '----------------------------------------------------' . "\n\n"; - die; - } } } @@ -247,17 +231,9 @@ private function createPackageConfig(PackageDescriptorEntity $packageDescriptorE { $neon = []; - $neonNoUseParam = [ - 'includes', - 'application', - 'menu', - 'routers', - 'afterInstall', - ]; - foreach ($packageDescriptorEntity->getPackagest(true) as $package) { foreach ($package->getConfig() as $param => $value) { - if (!\in_array($param, $neonNoUseParam, true)) { + if (isset(self::$neonNoUseParams[$param]) === false) { $neon[$param][] = [ 'name' => $package->getName(), 'version' => $package->getVersion(), @@ -276,9 +252,7 @@ private function createPackageConfig(PackageDescriptorEntity $packageDescriptorE if ($param === 'services') { foreach (\is_array($values) ? $values : [] as $value) { - $neonData = Neon::decode($value['data']['data']); - - foreach ($neonData as $treeKey => $treeValue) { + foreach ($neonData = Neon::decode($value['data']['data']) as $treeKey => $treeValue) { if (is_int($treeKey) || (is_string($treeKey) && preg_match('/^-?\d+\z/', $treeKey))) { unset($neonData[$treeKey]); $neonData['helperKey_' . $anonymousServiceCounter] = $treeValue; @@ -325,10 +299,7 @@ private function createPackageConfig(PackageDescriptorEntity $packageDescriptorE return $score; }; - $a = $score($left); - $b = $score($right); - - if ($a > $b) { + if (($a = $score($left)) > ($b = $score($right))) { return -1; } @@ -361,10 +332,7 @@ private function createPackageConfig(PackageDescriptorEntity $packageDescriptorE $return = (string) preg_replace('/(\s)\[\]\-(\s)/', '$1-$2', $return); if (!@file_put_contents(self::$configPackagePath, trim($return) . "\n")) { - throw new PackageDescriptorException( - 'Can not rewrite package.neon. Path: [' . self::$configPackagePath . ']' - . "\n" . error_get_last()['message'] - ); + PackageDescriptorException::canNotRewritePackageNeon(self::$configPackagePath); } } @@ -394,11 +362,11 @@ private function getComposerHash(): string { static $cache; - if ($cache !== null) { - return $cache; + if ($cache === null) { + $cache = (@md5_file(self::$projectRoot . '/vendor/composer/installed.json')) ? : md5((string) time()); } - return $cache = (@md5_file(self::$projectRoot . '/vendor/composer/installed.json')) ? : md5((string) time()); + return $cache; } } \ No newline at end of file diff --git a/src/Storage.php b/src/Storage.php index e384860..03c0300 100644 --- a/src/Storage.php +++ b/src/Storage.php @@ -10,7 +10,7 @@ use Nette\PhpGenerator\ClassType; use Nette\Utils\Finder; -class Storage +final class Storage { /**