From 35389b5d90336af7e7445007d5f929dc9a635d7a Mon Sep 17 00:00:00 2001 From: Iman Ghafoori Date: Tue, 5 Dec 2023 00:00:42 +0330 Subject: [PATCH] refactor --- src/ErrorReporters/ErrorPrinter.php | 48 ++++++++++++++----- .../CheckEvents}/CheckEvents.php | 3 +- src/Features/CheckEvents/Installer.php | 21 ++++++++ .../CheckEvents}/SpyDispatcher.php | 2 +- .../CheckImports/CheckImportReporter.php | 32 ++++++------- .../CheckImports/ExistenceChecker.php | 14 ++++-- .../Handlers/ExtraCorrectImports.php | 25 +++++----- .../Handlers/ExtraWrongImports.php | 25 +++++----- .../Handlers/FixWrongClassRefs.php | 6 +-- .../Handlers/PrintWrongClassRefs.php | 16 +++---- src/Features/CheckRoutes/Installer.php | 17 +++++++ .../SpyRouteCollection.php | 3 +- .../SpyRouter.php | 4 +- src/Features/Psr4/CheckPsr4ArtisanCommand.php | 7 +-- .../CheckCodeGeneration.php | 7 ++- .../GenerateCode.php | 17 ++++--- .../ServiceProviderStub.php | 2 +- .../microscopeServiceProvider.stub | 0 src/LaravelMicroscopeServiceProvider.php | 44 +++++------------ src/Traits/LogsErrors.php | 4 +- 20 files changed, 165 insertions(+), 132 deletions(-) rename src/{Commands => Features/CheckEvents}/CheckEvents.php (88%) create mode 100644 src/Features/CheckEvents/Installer.php rename src/{SpyClasses => Features/CheckEvents}/SpyDispatcher.php (98%) create mode 100644 src/Features/CheckRoutes/Installer.php rename src/Features/{RouteOverride => CheckRoutes}/SpyRouteCollection.php (90%) rename src/Features/{RouteOverride => CheckRoutes}/SpyRouter.php (95%) rename src/{Commands => Features/ServiceProviderGenerator}/CheckCodeGeneration.php (78%) rename src/{ => Features/ServiceProviderGenerator}/GenerateCode.php (86%) rename src/{Stubs => Features/ServiceProviderGenerator}/ServiceProviderStub.php (86%) rename src/{Stubs => Features/ServiceProviderGenerator}/microscopeServiceProvider.stub (100%) diff --git a/src/ErrorReporters/ErrorPrinter.php b/src/ErrorReporters/ErrorPrinter.php index 0e5f75e8..5a62d58a 100644 --- a/src/ErrorReporters/ErrorPrinter.php +++ b/src/ErrorReporters/ErrorPrinter.php @@ -10,20 +10,46 @@ class ErrorPrinter { public static $ignored; - public $errorsList = [ - 'total' => 0, - ]; + /** + * @var array + */ + public $errorsList = []; + + /** + * @var int + */ + public $total = 0; + /** + * The output interface implementation. + * + * @var \Illuminate\Console\OutputStyle + */ public $printer; + /** + * @var bool + */ public $logErrors = true; + /** + * @var string[] + */ public $pended = []; + /** + * @var int + */ public $count = 0; + /** + * @var self + */ public static $instance; + /** + * @var string + */ public static $basePath; /** @@ -70,7 +96,7 @@ public function print($msg, $path = ' ') public function printHeader($msg) { - $number = ++$this->errorsList['total']; + $number = ++$this->total; ($number < 10) && $number = " $number"; $number = ''.$number.' '; @@ -121,16 +147,16 @@ public function hasErrors() public function logErrors() { $errList = $this->errorsList; - unset($errList['total']); foreach ($errList as $list) { foreach ($list as $error) { - if ($error instanceof PendingError) { - $this->printHeader($error->getHeader()); - $this->print($error->getErrorData()); - $this->printLink($error->getLinkPath(), $error->getLinkLineNumber()); - $this->end(); - } + $this->printHeader($error->getHeader()); + $this->print($error->getErrorData()); + $this->printLink( + $error->getLinkPath(), + $error->getLinkLineNumber() + ); + $this->end(); } } diff --git a/src/Commands/CheckEvents.php b/src/Features/CheckEvents/CheckEvents.php similarity index 88% rename from src/Commands/CheckEvents.php rename to src/Features/CheckEvents/CheckEvents.php index 4eef8091..315659b3 100644 --- a/src/Commands/CheckEvents.php +++ b/src/Features/CheckEvents/CheckEvents.php @@ -1,10 +1,9 @@ booting(function () { + app()->singleton('events', function ($app) { + return (new SpyDispatcher($app))->setQueueResolver(function () use ($app) { + return $app->make(QueueFactoryContract::class); + }); + }); + Event::clearResolvedInstance('events'); + }); + } +} diff --git a/src/SpyClasses/SpyDispatcher.php b/src/Features/CheckEvents/SpyDispatcher.php similarity index 98% rename from src/SpyClasses/SpyDispatcher.php rename to src/Features/CheckEvents/SpyDispatcher.php index 2072e3c7..a131ea27 100644 --- a/src/SpyClasses/SpyDispatcher.php +++ b/src/Features/CheckEvents/SpyDispatcher.php @@ -1,6 +1,6 @@ '.ImportsAnalyzer::$checkedRefCount.' refs were checked, '.$totalErrors.' error'.($totalErrors == 1 ? ' ' : 's').' found.'.PHP_EOL; - $output .= ' - '.ImportsAnalyzer::$extraCorrectImportsCount.' unused import'.(ImportsAnalyzer::$extraCorrectImportsCount == 1 ? ' ' : 's').' found.'.PHP_EOL; - $output .= ' - '.ImportsAnalyzer::$wrongImportsCount.' wrong import'.(ImportsAnalyzer::$wrongImportsCount <= 1 ? ' ' : 's').' found.'.PHP_EOL; - $output .= ' - '.ImportsAnalyzer::$wrongClassRefCount.' wrong class'.(ImportsAnalyzer::$wrongClassRefCount <= 1 ? '' : 'es').' ref found.'; + $output = ''.ImportsAnalyzer::$checkedRefCount.' references were checked, '.$totalErrors.' error'.($totalErrors == 1 ? '' : 's').' found.'.PHP_EOL; + $output .= ' - '.ImportsAnalyzer::$extraCorrectImportsCount.' unused import'.(ImportsAnalyzer::$extraCorrectImportsCount == 1 ? '' : 's').' found.'.PHP_EOL; + $output .= ' - '.ImportsAnalyzer::$wrongImportsCount.' wrong import'.(ImportsAnalyzer::$wrongImportsCount <= 1 ? '' : 's').' found.'.PHP_EOL; + $output .= ' - '.ImportsAnalyzer::$wrongClassRefCount.' wrong class reference'.(ImportsAnalyzer::$wrongClassRefCount <= 1 ? '' : 's').' found.'; return $output; } @@ -112,9 +112,9 @@ public static function totalImportsMsg() return ''.ImportsAnalyzer::$checkedRefCount.' imports were checked under:'; } - private static function getBladeStats($stats, $checkedFilesCount): string + private static function getBladeStats($stats, $filesCount): string { - $output = self::blue($checkedFilesCount).'blade'.($checkedFilesCount <= 1 ? '' : 's'); + $output = self::blue($filesCount).'blade'.($filesCount <= 1 ? '' : 's'); $numPaths = count($stats); $output .= self::hyphen(); $i = 0; @@ -127,24 +127,24 @@ private static function getBladeStats($stats, $checkedFilesCount): string return $output; } - private static function getRouteStats($routeFilesCount) + private static function getRouteStats($count) { - return ' - '.$routeFilesCount.' route'.($routeFilesCount <= 1 ? '' : 's').PHP_EOL; + return ' - '.$count.' route'.($count <= 1 ? '' : 's').PHP_EOL; } - private static function getFilesStats($checkedFilesCount) + private static function getFilesStats($count) { - return ' - '.$checkedFilesCount.' class'.($checkedFilesCount <= 1 ? '' : 'es').PHP_EOL; + return ' - '.$count.' class'.($count <= 1 ? '' : 'es').PHP_EOL; } - private static function normalize($dir) + private static function normalize($dirPath) { - return FilePath::normalize(str_replace(base_path(), '.', $dir)); + return FilePath::normalize(str_replace(base_path(), '.', $dirPath)); } - private static function green(string $path) + private static function green(string $string) { - return ''.$path.''; + return ''.$string.''; } private static function hyphen() @@ -159,9 +159,7 @@ private static function files($count) private static function addLine($path, $count, $i, $numPaths) { - $output = ''; - $path = self::normalize($path); - $output .= self::green($path); + $output = self::green(self::normalize($path)); $output .= self::files($count); if ($i !== $numPaths) { $output .= self::hyphen(); diff --git a/src/Features/CheckImports/ExistenceChecker.php b/src/Features/CheckImports/ExistenceChecker.php index e717ec58..73a82a1d 100644 --- a/src/Features/CheckImports/ExistenceChecker.php +++ b/src/Features/CheckImports/ExistenceChecker.php @@ -6,9 +6,9 @@ class ExistenceChecker { - public static function check($class, $absFilePath): bool + public static function check($import, $absFilePath): bool { - if (! self::isAbsent($class) || \function_exists($class)) { + if (self::entityExists($import)) { return true; } @@ -18,15 +18,19 @@ public static function check($class, $absFilePath): bool return false; } - if (! self::isAbsent($class) || \function_exists($class)) { + if (self::entityExists($import)) { return true; } return false; } - private static function isAbsent($class) + private static function entityExists($import) { - return ! class_exists($class) && ! interface_exists($class) && ! trait_exists($class) && ! (function_exists('enum_exists') && enum_exists($class)); + return class_exists($import) || + interface_exists($import) || + trait_exists($import) || + function_exists($import) || + (function_exists('enum_exists') && enum_exists($import)); } } diff --git a/src/Features/CheckImports/Handlers/ExtraCorrectImports.php b/src/Features/CheckImports/Handlers/ExtraCorrectImports.php index bab051f3..808fb4a9 100644 --- a/src/Features/CheckImports/Handlers/ExtraCorrectImports.php +++ b/src/Features/CheckImports/Handlers/ExtraCorrectImports.php @@ -6,21 +6,18 @@ class ExtraCorrectImports { - public static function handle($unusedCorrectImports, $absFilePath) + public static function handle($extraCorrectImports, $absFilePath) { - foreach ($unusedCorrectImports as $class) { - self::extraImport($absFilePath, $class[0], $class[1]); - } - } + $printer = ErrorPrinter::singleton(); - public static function extraImport($absPath, $class, $lineNumber) - { - ErrorPrinter::singleton()->simplePendError( - $class, - $absPath, - $lineNumber, - 'extraImport', - 'Extra Import:' - ); + foreach ($extraCorrectImports as [$class, $lineNumber]) { + $printer->simplePendError( + $class, + $absFilePath, + $lineNumber, + 'extraCorrectImport', + 'Extra Import:' + ); + } } } diff --git a/src/Features/CheckImports/Handlers/ExtraWrongImports.php b/src/Features/CheckImports/Handlers/ExtraWrongImports.php index ff410a84..5e148b2e 100644 --- a/src/Features/CheckImports/Handlers/ExtraWrongImports.php +++ b/src/Features/CheckImports/Handlers/ExtraWrongImports.php @@ -6,21 +6,18 @@ class ExtraWrongImports { - public static function handle($unusedWrongImports, $absPath) + public static function handle($extraWrongImports, $absPath) { - foreach ($unusedWrongImports as $class) { - self::wrongImport($absPath, $class[0], $class[1]); - } - } + $printer = ErrorPrinter::singleton(); - public static function wrongImport($absPath, $class, $lineNumber) - { - ErrorPrinter::singleton()->simplePendError( - "use $class;", - $absPath, - $lineNumber, - 'wrongImport', - 'Unused & wrong import:' - ); + foreach ($extraWrongImports as [$class, $lineNumber]) { + $printer->simplePendError( + "use $class;", + $absPath, + $lineNumber, + 'extraWrongImport', + 'Unused & wrong import:' + ); + } } } diff --git a/src/Features/CheckImports/Handlers/FixWrongClassRefs.php b/src/Features/CheckImports/Handlers/FixWrongClassRefs.php index e2c6b841..cff442ff 100644 --- a/src/Features/CheckImports/Handlers/FixWrongClassRefs.php +++ b/src/Features/CheckImports/Handlers/FixWrongClassRefs.php @@ -74,13 +74,13 @@ private static function printFixation($absPath, $wrongClass, $lineNumber, $corre ); } - private static function wrongUsedClassError($absPath, $class, $lineNumber) + private static function wrongUsedClassError($absPath, $class, $line) { ErrorPrinter::singleton()->simplePendError( $class, $absPath, - $lineNumber, - 'wrongUsedClassError', + $line, + 'wrongClassRef', 'Class does not exist:' ); } diff --git a/src/Features/CheckImports/Handlers/PrintWrongClassRefs.php b/src/Features/CheckImports/Handlers/PrintWrongClassRefs.php index 2b389c6f..95db5dbc 100644 --- a/src/Features/CheckImports/Handlers/PrintWrongClassRefs.php +++ b/src/Features/CheckImports/Handlers/PrintWrongClassRefs.php @@ -11,15 +11,13 @@ public static function handle(array $wrongClassRefs, $absFilePath) $printer = ErrorPrinter::singleton(); foreach ($wrongClassRefs as $classReference) { - $wrongClassRef = $classReference['class']; - $line = $classReference['line']; - - self::wrongRef($printer, $wrongClassRef, $absFilePath, $line); + $printer->simplePendError( + $classReference['class'], + $absFilePath, + $classReference['line'], + 'wrongClassReference', + 'Class Reference does not exist:' + ); } } - - private static function wrongRef($printer, $wrongClassRef, $absFilePath, $line): void - { - $printer->simplePendError($wrongClassRef, $absFilePath, $line, 'wrongReference', 'Inline class Ref does not exist:'); - } } diff --git a/src/Features/CheckRoutes/Installer.php b/src/Features/CheckRoutes/Installer.php new file mode 100644 index 00000000..a9bdf324 --- /dev/null +++ b/src/Features/CheckRoutes/Installer.php @@ -0,0 +1,17 @@ +singleton('router', function ($app) use ($router) { + return $router; + }); + Route::swap($router); + } +} \ No newline at end of file diff --git a/src/Features/RouteOverride/SpyRouteCollection.php b/src/Features/CheckRoutes/SpyRouteCollection.php similarity index 90% rename from src/Features/RouteOverride/SpyRouteCollection.php rename to src/Features/CheckRoutes/SpyRouteCollection.php index 48d09b29..628136f1 100644 --- a/src/Features/RouteOverride/SpyRouteCollection.php +++ b/src/Features/CheckRoutes/SpyRouteCollection.php @@ -1,8 +1,9 @@ option('watch')) { sleep(8); - $errorPrinter->errorsList = ['total' => 0]; + $errorPrinter->errorsList = []; + $errorPrinter->total = 0; goto start; } else { - return $errorPrinter->errorsList['total'] > 0 ? 1 : 0; + return $errorPrinter->total > 0 ? 1 : 0; } } @@ -68,7 +69,7 @@ private function printReport(ErrorPrinter $errorPrinter, $time, $autoload, $clas if (! $this->option('watch') && Str::startsWith(request()->server('argv')[1] ?? '', 'check:psr4')) { $this->getOutput()->writeln(CheckPsr4Printer::reportResult($autoload, $stats, $time, $typesStats)); - $this->printMessages(CheckPsr4Printer::getErrorsCount($errorPrinter->errorsList['total'], $time)); + $this->printMessages(CheckPsr4Printer::getErrorsCount($errorPrinter->total, $time)); } else { $this->getOutput()->writeln(' - '.array_sum($stats).' namespaces were checked.'); } diff --git a/src/Commands/CheckCodeGeneration.php b/src/Features/ServiceProviderGenerator/CheckCodeGeneration.php similarity index 78% rename from src/Commands/CheckCodeGeneration.php rename to src/Features/ServiceProviderGenerator/CheckCodeGeneration.php index 4a6b5101..c54c6048 100644 --- a/src/Commands/CheckCodeGeneration.php +++ b/src/Features/ServiceProviderGenerator/CheckCodeGeneration.php @@ -1,12 +1,11 @@ info('Scanning for Empty Provider Files'); - $errorPrinter->printer = $this->output; + ErrorPrinter::singleton($this->output); foreach (ComposerJson::readAutoload() as $psr4) { foreach ($psr4 as $psr4Namespace => $psr4Path) { diff --git a/src/GenerateCode.php b/src/Features/ServiceProviderGenerator/GenerateCode.php similarity index 86% rename from src/GenerateCode.php rename to src/Features/ServiceProviderGenerator/GenerateCode.php index d7c14eae..acf9fe6f 100644 --- a/src/GenerateCode.php +++ b/src/Features/ServiceProviderGenerator/GenerateCode.php @@ -1,18 +1,17 @@ getPath().DIRECTORY_SEPARATOR; - file_put_contents($_basePath.$prefix.'_routes.php', self::routeContent($namespace)); - self::makeDirectory($_basePath.'Database'.DIRECTORY_SEPARATOR.'migrations'); - self::makeDirectory($_basePath.'views'); - self::makeDirectory($_basePath.'Http'); - self::makeDirectory($_basePath.'Database'.DIRECTORY_SEPARATOR.'Models'); + $basePath = $classFilePath->getPath().DIRECTORY_SEPARATOR; + file_put_contents($basePath.$prefix.'_routes.php', self::routeContent($namespace)); + self::makeDirectory($basePath.'Database'.DIRECTORY_SEPARATOR.'migrations'); + self::makeDirectory($basePath.'views'); + self::makeDirectory($basePath.'Http'); + self::makeDirectory($basePath.'Database'.DIRECTORY_SEPARATOR.'Models'); } protected static function routeContent($namespace) diff --git a/src/Stubs/ServiceProviderStub.php b/src/Features/ServiceProviderGenerator/ServiceProviderStub.php similarity index 86% rename from src/Stubs/ServiceProviderStub.php rename to src/Features/ServiceProviderGenerator/ServiceProviderStub.php index 3df76942..456ccc8c 100644 --- a/src/Stubs/ServiceProviderStub.php +++ b/src/Features/ServiceProviderGenerator/ServiceProviderStub.php @@ -1,6 +1,6 @@ version()); - if ((int) $major >= 8) { - $color = 'gray'; - } else { - $color = 'blue'; - } + $color = (int) $major >= 8 ? 'gray' : 'blue'; + config()->set('microscope.colors.line_separator', $color); $this->registerCompiler(); @@ -124,7 +120,7 @@ public function register() app()->singleton(ErrorPrinter::class, function () { return ErrorPrinter::singleton(); }); - $this->spyRouter(); + \Imanghafoori\LaravelMicroscope\Features\CheckRoutes\Installer::spyRouter(); // also we should spy the factory paths. if (class_exists('Illuminate\Database\Eloquent\Factory')) { $this->spyFactory(); @@ -134,22 +130,13 @@ public function register() $command = $_SERVER['argv'][1] ?? ''; // We spy the router in order to have a list of route files. $checkAll = Str::startsWith('check:all', $command); - ($checkAll || Str::startsWith('check:eve', $command)) && $this->spyEvents(); + ($checkAll || Str::startsWith('check:eve', $command)) && Installer::spyEvents(); ($checkAll || Str::startsWith('check:routes', $command)) && app('router')->spyRouteConflict(); Str::startsWith('check:action_comment', $command) && app('router')->spyRouteConflict(); // ($checkAll || Str::startsWith('check:events', $command)) && $this->spyEvents(); ($checkAll || Str::startsWith('check:gates', $command)) && $this->spyGates(); } - private function spyRouter() - { - $router = new SpyRouter(app('events'), app()); - $this->app->singleton('router', function ($app) use ($router) { - return $router; - }); - Route::swap($router); - } - private function spyFactory() { $this->app->singleton('Illuminate\Database\Eloquent\Factory', function ($app) { @@ -168,18 +155,6 @@ private function spyGates() }); } - private function spyEvents() - { - app()->booting(function () { - $this->app->singleton('events', function ($app) { - return (new SpyDispatcher($app))->setQueueResolver(function () use ($app) { - return $app->make(QueueFactoryContract::class); - }); - }); - Event::clearResolvedInstance('events'); - }); - } - public function spyView() { app()->singleton('microscope.views', ViewsData::class); @@ -241,6 +216,9 @@ private function resetCountersOnFinish() CheckView::$checkedCallsCount = 0; CheckView::$skippedCallsCount = 0; ImportsAnalyzer::$checkedRefCount = 0; + ImportsAnalyzer::$extraCorrectImportsCount = 0; + ImportsAnalyzer::$wrongImportsCount = 0; + ImportsAnalyzer::$wrongClassRefCount = 0; Iterators\ChecksOnPsr4Classes::$checkedFilesCount = 0; }); } diff --git a/src/Traits/LogsErrors.php b/src/Traits/LogsErrors.php index cfa1a1e6..ea8d1ae0 100644 --- a/src/Traits/LogsErrors.php +++ b/src/Traits/LogsErrors.php @@ -22,9 +22,7 @@ protected function finishCommand(ErrorPrinter $errorPrinter) return; } - if (($errorCount = $errorPrinter->hasErrors()) || $errorPrinter->pended) { - $errorCount && $this->warn(PHP_EOL.$errorCount.' errors found for '.$commandType); - + if ($errorPrinter->hasErrors() || $errorPrinter->pended) { $errorPrinter->logErrors(); } elseif (property_exists($this, 'customMsg')) { $this->info(PHP_EOL.$this->customMsg);