Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
imanghafoori1 committed Mar 14, 2024
1 parent d41f846 commit 4e6596b
Show file tree
Hide file tree
Showing 9 changed files with 135 additions and 117 deletions.
49 changes: 32 additions & 17 deletions src/Checks/CheckEarlyReturn.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,44 +7,59 @@
use Imanghafoori\LaravelMicroscope\ErrorReporters\ErrorPrinter;
use Imanghafoori\LaravelMicroscope\FileReaders\FilePath;
use Imanghafoori\TokenAnalyzer\Refactor;
use Imanghafoori\TokenAnalyzer\SyntaxNormalizer;

class CheckEarlyReturn implements Check
{
public static function check($tokens, $absFilePath, $isTest)
public static function check(array $tokens, $absFilePath, $params)
{
$nofix = $params['nofix'];
$nofixCallback = $params['nofixCallback'];
$fixCallback = $params['fixCallback'];

if (empty($tokens) || $tokens[0][0] !== T_OPEN_TAG) {
return false;
return;
}

try {
$tokens = SyntaxNormalizer::normalizeSyntax($tokens, true);
[$fixes, $tokens] = self::refactor($tokens);
} catch (Exception $e) {
self::requestIssue($absFilePath);
dump('(O_o) Well, It seems we had some problem parsing the contents of: (O_o)');
dump('Skipping : '.$absFilePath);

return false;
return;
}

if (SyntaxNormalizer::$hasChange && self::getConfirm($absFilePath)) {
Refactor::saveTokens($absFilePath, $tokens, $isTest);
if ($fixes === 0) {
return;
}

return true;
if ($nofix) {
$nofixCallback($absFilePath);
} elseif (self::getConfirm($absFilePath)) {
self::fix($absFilePath, $tokens, $fixes, $fixCallback);
}
}

private static function getConfirm($absFilePath)
{
$relFilePath = FilePath::getRelativePath($absFilePath);

return false;
return ErrorPrinter::singleton()->printer->confirm(' Do you want to flatten: <fg=yellow>'.$relFilePath.'</>');
}

private static function getConfirm($filePath)
private static function refactor($tokens)
{
$filePath = FilePath::getRelativePath($filePath);
$fixes = 0;
do {
[$tokens, $refactored] = Refactor::flatten($tokens);
} while ($refactored > 0 && $fixes++);

return ErrorPrinter::singleton()->printer->confirm('Replacing endif in: '.$filePath);
return [$fixes, $tokens];
}

private static function requestIssue(string $path)
private static function fix($absFilePath, $tokens, $fixes, $fixCallback)
{
dump('(O_o) Well, It seems we had some problem parsing the contents of: (o_O)');
dump('Submit an issue on github: https://github.com/imanghafoori1/microscope');
dump('Send us the contents of: '.$path);
Refactor::saveTokens($absFilePath, $tokens);
$fixCallback($absFilePath, $fixes);
}
}
50 changes: 50 additions & 0 deletions src/Checks/CheckRubySyntax.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace Imanghafoori\LaravelMicroscope\Checks;

use Exception;
use Imanghafoori\LaravelMicroscope\Check;
use Imanghafoori\LaravelMicroscope\ErrorReporters\ErrorPrinter;
use Imanghafoori\LaravelMicroscope\FileReaders\FilePath;
use Imanghafoori\TokenAnalyzer\Refactor;
use Imanghafoori\TokenAnalyzer\SyntaxNormalizer;

class CheckRubySyntax implements Check
{
public static function check($tokens, $absFilePath)
{
if (empty($tokens) || $tokens[0][0] !== T_OPEN_TAG) {
return false;
}

try {
$tokens = SyntaxNormalizer::normalizeSyntax($tokens, true);
} catch (Exception $e) {
self::requestIssue($absFilePath);

return false;
}

if (SyntaxNormalizer::$hasChange && self::getConfirm($absFilePath)) {
Refactor::saveTokens($absFilePath, $tokens);

return true;
}

return false;
}

private static function getConfirm($filePath)
{
$filePath = FilePath::getRelativePath($filePath);

return ErrorPrinter::singleton()->printer->confirm('Replacing endif in: '.$filePath);
}

private static function requestIssue(string $path)
{
dump('(O_o) Well, It seems we had some problem parsing the contents of: (o_O)');
dump('Submit an issue on github: https://github.com/imanghafoori1/microscope');
dump('Send us the contents of: '.$path);
}
}
4 changes: 2 additions & 2 deletions src/Commands/CheckAll.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ public function handle(ErrorPrinter $errorPrinter)
$this->call('check:imports', ['--nofix' => $this->option('nofix')]);
$this->call('check:events');
$this->call('check:gates');
$this->call('check:views', ['--detailed' => $this->option('detailed')]);
$this->call('check:views');
$this->call('check:routes');
$this->call('check:stringy_classes');
$this->call('check:dd');
$this->call('check:dead_controllers');
$this->call('check:early_returns', ['--nofix' => true]);
CheckEarlyReturns::applyCheckEarly('', '', true);
$this->call('check:bad_practices');

// turns on error logging.
Expand Down
114 changes: 31 additions & 83 deletions src/Commands/CheckEarlyReturns.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,118 +2,66 @@

namespace Imanghafoori\LaravelMicroscope\Commands;

use Exception;
use Illuminate\Console\Command;
use Imanghafoori\LaravelMicroscope\Analyzers\ComposerJson;
use Imanghafoori\LaravelMicroscope\Checks\CheckEarlyReturn;
use Imanghafoori\LaravelMicroscope\ErrorReporters\ErrorPrinter;
use Imanghafoori\LaravelMicroscope\Features\CheckImports\Reporters\Psr4Report;
use Imanghafoori\LaravelMicroscope\FileReaders\FilePath;
use Imanghafoori\LaravelMicroscope\FileReaders\PhpFinder;
use Imanghafoori\TokenAnalyzer\Refactor;
use Symfony\Component\Console\Terminal;
use Imanghafoori\LaravelMicroscope\ForPsr4LoadedClasses;

class CheckEarlyReturns extends Command
{
protected $signature = 'check:early_returns {--t|test : backup the changed files} {--s|nofix}';
protected $signature = 'check:early_returns {--s|nofix} {--f|file=} {--d|folder=}';

protected $description = 'Applies the early return on the classes';

public function handle()
{
ErrorPrinter::singleton($this->output);

if ($this->option('nofix')) {
$this->info(PHP_EOL.' Checking for possible code flattenings...'.PHP_EOL);
}

if (! $this->option('nofix') && ! $this->startWarning()) {
return;
return 0;
}

$fixingFilesCount = $totalNumberOfFixes = $fixedFilesCount = 0;
foreach (ComposerJson::readPsr4() as $autoload) {
foreach ($autoload as $psr4Namespace => $psr4Paths) {
foreach ((array) $psr4Paths as $psr4Path) {
$files = PhpFinder::getAllPhpFiles($psr4Path);
foreach ($files as $file) {
$path = $file->getRealPath();
$tokens = token_get_all(file_get_contents($path));
if (empty($tokens) || $tokens[0][0] !== T_OPEN_TAG) {
continue;
}

try {
[$fixes, $tokens] = $this->refactor($tokens);
} catch (Exception $e) {
dump('(O_o) Well, It seems we had some problem parsing the contents of: (O_o)');
dump('Skipping : '.$path);
continue;
}

$fixes !== 0 && $fixingFilesCount++;

if ($this->option('nofix') && $fixes !== 0) {
$this->line('<fg=red> - '.FilePath::getRelativePath($path).'</fg=red>');
continue;
}

if ($fixes == 0 || ! $this->getConfirm($path)) {
continue;
}

$this->fix($path, $tokens, $fixes);
$fixedFilesCount++;
$totalNumberOfFixes += $fixes;
}
}
}
}

$this->printFinalMsg($fixedFilesCount, $fixingFilesCount);

return ErrorPrinter::singleton($this->getOutput())->hasErrors() ? 1 : 0;
}

private function fix($filePath, $tokens, $tries)
{
Refactor::saveTokens($filePath, $tokens, $this->option('test'));

$this->warn(PHP_EOL.$tries.' fixes applied to: '.class_basename($filePath));
}

private function refactor($tokens)
{
$fixes = 0;
do {
[$tokens, $refactored] = Refactor::flatten($tokens);
} while ($refactored > 0 && $fixes++);
$fileName = ltrim($this->option('file'), '=');
$folder = ltrim($this->option('folder'), '=');
$psr4Stats = self::applyCheckEarly($fileName, $folder, $this->option('nofix'));
$this->getOutput()->writeln(implode(PHP_EOL, [
Psr4Report::printAutoload($psr4Stats, []),
]));

return [$fixes, $tokens];
return ErrorPrinter::singleton()->hasErrors() ? 1 : 0;
}

private function printFinalMsg($fixed, $fixingFilesCount)
private function startWarning()
{
if ($fixed > 0) {
$msg = ' Hooraay!!!, '.$fixed.' files were flattened by laravel-microscope!';
} elseif ($fixingFilesCount == 0) {
$msg = ' Congratulations, your code base does not seems to need any flattening. <fg=red> \(^_^)/ </fg=red>';
} elseif ($fixingFilesCount !== 0 && $this->option('nofix')) {
$msg = ' The files above can be flattened by: <fg=cyan>php artisan check:early</fg=cyan>';
}
$this->info(PHP_EOL.' Checking for Early Returns...');
$this->warn(' Warning: This command is going to make "CHANGES" to your files!');

isset($msg) && $this->info(PHP_EOL.$msg);
$this->info(' <fg='.config('microscope.colors.line_separator').'>'.str_repeat('_', (new Terminal)->getWidth() - 2).'</>');
return $this->output->confirm(' Do you have committed everything in git?');
}

private function getConfirm($filePath)
private static function getParams($nofix): array
{
$filePath = FilePath::getRelativePath($filePath);
$params = [
'nofix' => $nofix,
'nofixCallback' => function ($absPath) {
$this->line('<fg=red> - '.FilePath::getRelativePath($absPath).'</fg=red>');
},
'fixCallback' => function ($filePath, $tries) {
$this->warn(PHP_EOL.$tries.' fixes applied to: '.class_basename($filePath));
}
];

return $this->output->confirm(' Do you want to flatten: <fg=yellow>'.$filePath.'</>', true);
return $params;
}

private function startWarning()
public static function applyCheckEarly(string $fileName, string $folder, $nofix): array
{
$this->info(PHP_EOL.' Checking for Early Returns...');
$this->warn(' Warning: This command is going to make "CHANGES" to your files!');

return $this->output->confirm(' Do you have committed everything in git?', false);
return ForPsr4LoadedClasses::check([CheckEarlyReturn::class], self::getParams($nofix), $fileName, $folder);
}
}
14 changes: 7 additions & 7 deletions src/Commands/CheckEndIf.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Imanghafoori\LaravelMicroscope\Commands;

use Illuminate\Console\Command;
use Imanghafoori\LaravelMicroscope\Checks\CheckEarlyReturn;
use Imanghafoori\LaravelMicroscope\Checks\CheckRubySyntax;
use Imanghafoori\LaravelMicroscope\ErrorReporters\ErrorPrinter;
use Imanghafoori\LaravelMicroscope\Features\CheckImports\Reporters\Psr4Report;
use Imanghafoori\LaravelMicroscope\ForPsr4LoadedClasses;
Expand All @@ -25,12 +25,7 @@ public function handle(ErrorPrinter $errorPrinter)

$errorPrinter->printer = $this->output;

$psr4Stats = ForPsr4LoadedClasses::check(
[CheckEarlyReturn::class],
$this->option('test'),
$fileName,
$folder
);
$psr4Stats = self::applyRubySyntaxCheck($fileName, $folder);

$this->getOutput()->writeln(implode(PHP_EOL, [
Psr4Report::printAutoload($psr4Stats, []),
Expand All @@ -46,4 +41,9 @@ private function startWarning()

return $this->output->confirm('Do you have committed everything in git?');
}

public static function applyRubySyntaxCheck(string $fileName, string $folder)
{
return ForPsr4LoadedClasses::check([CheckRubySyntax::class], [], $fileName, $folder);
}
}
12 changes: 10 additions & 2 deletions src/Commands/CheckPsr12.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
use Imanghafoori\LaravelMicroscope\Checks\PSR12\CurlyBraces;
use Imanghafoori\LaravelMicroscope\ErrorReporters\ErrorPrinter;
use Imanghafoori\LaravelMicroscope\Features\ActionComments\ActionsComments;
use Imanghafoori\LaravelMicroscope\Features\CheckImports\Reporters\Psr4Report;
use Imanghafoori\LaravelMicroscope\ForPsr4LoadedClasses;
use Imanghafoori\LaravelMicroscope\Traits\LogsErrors;

class CheckPsr12 extends Command
{
use LogsErrors;

protected $signature = 'check:psr12';
protected $signature = 'check:psr12 {--f|file=} {--d|folder=}';

protected $description = 'Applies psr-12 rules';

Expand All @@ -30,7 +31,14 @@ public function handle(ErrorPrinter $errorPrinter)

ActionsComments::$command = $this;

ForPsr4LoadedClasses::checkNow([CurlyBraces::class]);
$fileName = ltrim($this->option('file'), '=');
$folder = ltrim($this->option('folder'), '=');

$psr4Stats = ForPsr4LoadedClasses::check([CurlyBraces::class], [], $fileName, $folder);

$this->getOutput()->writeln(implode(PHP_EOL, [
Psr4Report::printAutoload($psr4Stats, []),
]));

$this->finishCommand($errorPrinter);

Expand Down
3 changes: 1 addition & 2 deletions src/SearchReplace/FullNamespaceIs.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
namespace Imanghafoori\LaravelMicroscope\SearchReplace;

use Illuminate\Support\Str;
use Imanghafoori\LaravelMicroscope\Check;
use Imanghafoori\TokenAnalyzer\GetClassProperties;
use Imanghafoori\TokenAnalyzer\ParseUseStatement;

class FullNamespaceIs implements Check
class FullNamespaceIs
{
public static function check($placeholderVal, $parameter, $tokens)
{
Expand Down
3 changes: 1 addition & 2 deletions src/SearchReplace/IsSubClassOf.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

namespace Imanghafoori\LaravelMicroscope\SearchReplace;

use Imanghafoori\LaravelMicroscope\Check;
use Imanghafoori\TokenAnalyzer\GetClassProperties;
use Imanghafoori\TokenAnalyzer\ParseUseStatement;

class IsSubClassOf implements Check
class IsSubClassOf
{
public static function check($placeholderVal, $parameter, $tokens)
{
Expand Down
3 changes: 1 addition & 2 deletions src/SearchReplace/NamespaceIs.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
namespace Imanghafoori\LaravelMicroscope\SearchReplace;

use Illuminate\Support\Str;
use Imanghafoori\LaravelMicroscope\Check;
use Imanghafoori\TokenAnalyzer\GetClassProperties;
use Imanghafoori\TokenAnalyzer\ParseUseStatement;

class NamespaceIs implements Check
class NamespaceIs
{
public static function check($placeholderVal, $parameter, $tokens)
{
Expand Down

0 comments on commit 4e6596b

Please sign in to comment.