From 764bc02b849617a0efe099a53d5ff5ac2f965841 Mon Sep 17 00:00:00 2001 From: Markus Podar Date: Tue, 1 Sep 2020 11:32:31 +0200 Subject: [PATCH] [CODESTYLE] Replace phpcs with php-cs-fixer (#1030) * composer require --dev friendsofphp/php-cs-fixer:^2 * php-cs-fixer: ignore cache and custom local config file * php-cs-fixer: initial config * php-cs-fixer: replace commands in composer * php-cs-fixer: add PSR12 "as good as it currently gets" * php-cs-fixer: apply PSR12 to codebase * tests: add workaround to keep unused imports for snapshot testing * php-cs-fixer: apply no_unused_imports * php-cs-fixer: apply array_syntax short * php-cs-fixer: apply single_quote * php-cs-fixer: switch ordered_imports sort_algorithm to alpha Let's be opinionated here for consistency * php-cs-fixer: split between non-tests and tests and share config * php-cs-fixer: apply declare_strict_types for tests * php-cs-fixer: apply fully_qualified_strict_types * php-cs-fixer: apply space_after_semicolon * php-cs-fixer: apply trailing_comma_in_multiline_array * php-cs-fixer: apply trim_array_spaces * php-cs-fixer: apply unary_operator_spaces * php-cs-fixer: apply whitespace_after_comma_in_array * php-cs-fixer: apply native_function_invocation * php-cs-fixer: apply concat_space * grumphp: reflect we're using phpcsfixer now * composer remove --dev squizlabs/php_codesniffer * gha: simplify fix-style approach Not really necessary to remove packages and then manually prevent unrelated commits creeping in Co-authored-by: Barry vd. Heuvel --- .github/workflows/fix-code-style.yml | 7 +- .gitignore | 3 + .php_cs.common.php | 65 +++++++++++++ .php_cs.dist | 14 +++ .php_cs.tests.php | 22 +++++ composer.json | 12 ++- config/ide-helper.php | 39 ++++---- grumphp.yml | 2 +- src/Alias.php | 24 ++--- src/Console/GeneratorCommand.php | 36 ++++---- src/Console/MetaCommand.php | 9 +- src/Console/ModelsCommand.php | 92 +++++++++---------- src/Eloquent.php | 4 +- src/Factories.php | 1 - src/Generator.php | 44 ++++----- src/IdeHelperServiceProvider.php | 3 +- src/Macro.php | 2 +- src/Method.php | 20 ++-- tests/Console/EloquentCommandTest.php | 2 + .../Collections/SimpleCollection.php | 3 +- .../ModelsCommand/CustomCollection/Test.php | 3 - .../Console/ModelsCommand/CustomDate/Test.php | 2 - .../DynamicRelations/OtherModels/Account.php | 1 - .../GenerateBasicPhpdoc/Test.php | 2 - .../GenerateBasicPhpdocCamel/Test.php | 2 - .../GenerateBasicPhpdocFinal/Test.php | 2 - .../GeneratePhpdocWithFqn/Casts/CastType.php | 1 - .../GeneratePhpdocWithFqn/Models/Post.php | 20 +++- .../GeneratePhpdocWithFqn/Test.php | 6 -- .../__snapshots__/Test__test__1.php | 20 +++- .../Builders/EMaterialQueryBuilder.php | 1 - .../Test.php | 6 -- tests/Console/ModelsCommand/Getter/Test.php | 2 - .../ModelsCommand/Ignored/Models/Ignored.php | 1 - tests/Console/ModelsCommand/Ignored/Test.php | 4 +- .../Console/ModelsCommand/Interfaces/Test.php | 2 - .../Casts/CastedProperty.php | 3 +- .../Casts/CustomCasterWithDocblockReturn.php | 2 + .../CustomCasterWithDocblockReturnFqn.php | 2 + ...ustomCasterWithNullablePrimitiveReturn.php | 2 + ...ustomCasterWithPrimitiveDocblockReturn.php | 2 + .../Casts/CustomCasterWithPrimitiveReturn.php | 2 + .../Casts/CustomCasterWithReturnType.php | 2 + .../Casts/CustomCasterWithoutReturnType.php | 2 + .../ModelsCommand/LaravelCustomCasts/Test.php | 3 - .../Console/ModelsCommand/MagicWhere/Test.php | 2 - .../PHPStormNoInspection/Test.php | 4 - .../RelationCountProperties/Test.php | 4 - .../Console/ModelsCommand/Relations/Test.php | 2 - .../ModelsCommand/ResetAndSmartReset/Test.php | 2 - .../ModelsCommand/SoftDeletes/Test.php | 2 - .../migrations/____posts_table.php | 2 +- tests/MethodTest.php | 2 + tests/SnapshotPhpDriver.php | 2 + tests/SnapshotTxtDriver.php | 2 + 55 files changed, 308 insertions(+), 215 deletions(-) create mode 100644 .php_cs.common.php create mode 100644 .php_cs.dist create mode 100644 .php_cs.tests.php diff --git a/.github/workflows/fix-code-style.yml b/.github/workflows/fix-code-style.yml index e4088b18d..f898df503 100644 --- a/.github/workflows/fix-code-style.yml +++ b/.github/workflows/fix-code-style.yml @@ -23,16 +23,11 @@ jobs: tools: composer:v2 - name: Install dependencies - run: | - composer remove phpro/grumphp vimeo/psalm --no-update --dev - composer update --prefer-dist --no-progress + run: composer update --prefer-dist --no-progress - run: composer fix-style continue-on-error: true - # Revert manual modifications so they don't get commited 💥 - - run: git checkout -- composer.json - - uses: stefanzweifel/git-auto-commit-action@v4 with: commit_message: composer fix-style diff --git a/.gitignore b/.gitignore index ad4fb616f..1192196b0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,8 @@ .phpunit.result.cache /.idea +/.php_cs +/.php_cs.cache +/.php_cs.tests.cache /composer.lock /vendor diff --git a/.php_cs.common.php b/.php_cs.common.php new file mode 100644 index 000000000..a7aad6375 --- /dev/null +++ b/.php_cs.common.php @@ -0,0 +1,65 @@ + true, + 'blank_line_after_opening_tag' => true, + 'braces' => [ + // Not-yet-implemented + // 'allow_single_line_anonymous_class_with_empty_body' => true, + ], + 'compact_nullable_typehint' => true, + 'declare_equal_normalize' => true, + 'lowercase_cast' => true, + 'lowercase_static_reference' => true, + 'new_with_braces' => true, + 'no_blank_lines_after_class_opening' => true, + 'no_leading_import_slash' => true, + 'no_whitespace_in_blank_line' => true, + 'ordered_class_elements' => [ + 'order' => [ + 'use_trait', + ], + ], + 'ordered_imports' => [ + 'imports_order' => [ + 'class', + 'function', + 'const', + ], + 'sort_algorithm' => 'alpha', + ], + 'return_type_declaration' => true, + 'short_scalar_cast' => true, + 'single_blank_line_before_namespace' => true, + 'single_trait_insert_per_statement' => true, + 'ternary_operator_spaces' => true, + 'visibility_required' => [ + 'elements' => [ + 'const', + 'method', + 'property', + ], + ], + + // Further quality-of-life improvements + 'array_syntax' => [ + 'syntax' => 'short', + ], + 'concat_space' => [ + 'spacing' => 'one', + ], + 'fully_qualified_strict_types' => true, + 'native_function_invocation' => [ + 'include' => [], + 'strict' => true, + ], + 'no_unused_imports' => true, + 'single_quote' => true, + 'space_after_semicolon' => true, + 'trailing_comma_in_multiline_array' => true, + 'trim_array_spaces' => true, + 'unary_operator_spaces' => true, + 'whitespace_after_comma_in_array' => true, +]; diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 000000000..208334516 --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,14 @@ +in(__DIR__) + ->exclude('tests'); + +$config = require __DIR__ . '/.php_cs.common.php'; + +return PhpCsFixer\Config::create() + ->setFinder($finder) + ->setRules($config) + ->setRiskyAllowed(true) + ->setCacheFile(__DIR__ . '/.php_cs.cache'); diff --git a/.php_cs.tests.php b/.php_cs.tests.php new file mode 100644 index 000000000..24c484d1f --- /dev/null +++ b/.php_cs.tests.php @@ -0,0 +1,22 @@ +in(__DIR__ . '/tests') + ->exclude('__snapshots__'); + +$config = require __DIR__ . '/.php_cs.common.php'; + +// Additional rules for tests +$config = array_merge( + $config, + [ + 'declare_strict_types' => true, + ] +); + +return PhpCsFixer\Config::create() + ->setFinder($finder) + ->setRules($config) + ->setRiskyAllowed(true) + ->setCacheFile(__DIR__ . '/.php_cs.tests.cache'); diff --git a/composer.json b/composer.json index 1223b8670..548b938e7 100644 --- a/composer.json +++ b/composer.json @@ -31,13 +31,13 @@ "phpdocumentor/type-resolver": "^1.1.0" }, "require-dev": { + "friendsofphp/php-cs-fixer": "^2", "illuminate/config": "^6 || ^7 || ^8", "illuminate/view": "^6 || ^7 || ^8", "mockery/mockery": "^1.3", "orchestra/testbench": "^4 || ^5 || ^6", "phpro/grumphp": "^0.19.0", "spatie/phpunit-snapshot-assertions": "^1.4 || ^2.2 || ^3", - "squizlabs/php_codesniffer": "^3.5", "vimeo/psalm": "^3.12" }, "config": { @@ -67,8 +67,14 @@ "prefer-stable": true, "scripts": { "analyze": "psalm", - "check-style": "phpcs -p --standard=PSR12 config/ resources/ src/ tests/ '--ignore=*__snapshots_*'", - "fix-style": "phpcbf -p --standard=PSR12 config/ resources/ src/ tests/ '--ignore=*__snapshots_*'", + "check-style": [ + "php-cs-fixer fix --diff --diff-format=udiff --dry-run", + "php-cs-fixer fix --diff --diff-format=udiff --dry-run --config=.php_cs.tests.php" + ], + "fix-style": [ + "php-cs-fixer fix", + "php-cs-fixer fix --config=.php_cs.tests.php" + ], "test": "phpunit", "test-regenerate": "phpunit -d --update-snapshots" } diff --git a/config/ide-helper.php b/config/ide-helper.php index 19c520c38..e287fea52 100644 --- a/config/ide-helper.php +++ b/config/ide-helper.php @@ -1,6 +1,6 @@ false, - 'helper_files' => array( + 'helper_files' => [ base_path() . '/vendor/laravel/framework/src/Illuminate/Support/helpers.php', - ), + ], /* |-------------------------------------------------------------------------- @@ -115,9 +115,9 @@ | */ - 'model_locations' => array( + 'model_locations' => [ 'app', - ), + ], /* |-------------------------------------------------------------------------- @@ -128,9 +128,9 @@ | */ - 'ignored_models' => array( + 'ignored_models' => [ - ), + ], /* |-------------------------------------------------------------------------- @@ -141,12 +141,12 @@ | */ - 'extra' => array( - 'Eloquent' => array('Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'), - 'Session' => array('Illuminate\Session\Store'), - ), + 'extra' => [ + 'Eloquent' => ['Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'], + 'Session' => ['Illuminate\Session\Store'], + ], - 'magic' => array(), + 'magic' => [], /* |-------------------------------------------------------------------------- @@ -158,9 +158,9 @@ | */ - 'interfaces' => array( + 'interfaces' => [ - ), + ], /* |-------------------------------------------------------------------------- @@ -188,9 +188,9 @@ | ), | */ - 'custom_db_types' => array( + 'custom_db_types' => [ - ), + ], /* |-------------------------------------------------------------------------- @@ -226,10 +226,10 @@ | Cast the given "real type" to the given "type". | */ - 'type_overrides' => array( + 'type_overrides' => [ 'integer' => 'int', 'boolean' => 'bool', - ), + ], /* |-------------------------------------------------------------------------- @@ -253,5 +253,4 @@ | */ 'force_fqn' => false, - -); +]; diff --git a/grumphp.yml b/grumphp.yml index 04caf1c59..7dab4b128 100644 --- a/grumphp.yml +++ b/grumphp.yml @@ -5,7 +5,7 @@ grumphp: triggered_by: [php] metadata: task: composer_script - phpcs: + phpcsfixer: script: check-style triggered_by: [php] metadata: diff --git a/src/Alias.php b/src/Alias.php index 5167b5ec0..4ad4e87c8 100644 --- a/src/Alias.php +++ b/src/Alias.php @@ -11,13 +11,13 @@ namespace Barryvdh\LaravelIdeHelper; -use Closure; -use ReflectionClass; use Barryvdh\Reflection\DocBlock; use Barryvdh\Reflection\DocBlock\Context; +use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer; use Barryvdh\Reflection\DocBlock\Tag\MethodTag; +use Closure; use Illuminate\Config\Repository as ConfigRepository; -use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer; +use ReflectionClass; class Alias { @@ -31,12 +31,12 @@ class Alias protected $short; protected $namespace = '__root'; protected $root = null; - protected $classes = array(); - protected $methods = array(); - protected $usedMethods = array(); + protected $classes = []; + protected $methods = []; + protected $usedMethods = []; protected $valid = false; - protected $magicMethods = array(); - protected $interfaces = array(); + protected $magicMethods = []; + protected $interfaces = []; protected $phpdoc = null; /** @var ConfigRepository */ @@ -50,7 +50,7 @@ class Alias * @param array $magicMethods * @param array $interfaces */ - public function __construct($config, $alias, $facade, $magicMethods = array(), $interfaces = array()) + public function __construct($config, $alias, $facade, $magicMethods = [], $interfaces = []) { $this->alias = $alias; $this->magicMethods = $magicMethods; @@ -82,7 +82,7 @@ public function __construct($config, $alias, $facade, $magicMethods = array(), $ if ($facade === '\Illuminate\Database\Eloquent\Model') { - $this->usedMethods = array('decrement', 'increment'); + $this->usedMethods = ['decrement', 'increment']; } } @@ -289,12 +289,12 @@ protected function detectRoot() //When the database connection is not set, some classes will be skipped } catch (\PDOException $e) { $this->error( - "PDOException: " . $e->getMessage() . + 'PDOException: ' . $e->getMessage() . "\nPlease configure your database connection correctly, or use the sqlite memory driver (-M)." . " Skipping $facade." ); } catch (\Exception $e) { - $this->error("Exception: " . $e->getMessage() . "\nSkipping $facade."); + $this->error('Exception: ' . $e->getMessage() . "\nSkipping $facade."); } } diff --git a/src/Console/GeneratorCommand.php b/src/Console/GeneratorCommand.php index 37121b694..c2abf146b 100644 --- a/src/Console/GeneratorCommand.php +++ b/src/Console/GeneratorCommand.php @@ -15,8 +15,8 @@ use Barryvdh\LaravelIdeHelper\Generator; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputOption; /** * A command to generate autocomplete information for your IDE @@ -25,7 +25,6 @@ */ class GeneratorCommand extends Command { - /** * The console command name. * @@ -59,7 +58,8 @@ class GeneratorCommand extends Command * @param \Illuminate\View\Factory $view */ public function __construct( - /*ConfigRepository */ $config, + /*ConfigRepository */ + $config, Filesystem $files, /* Illuminate\View\Factory */ $view @@ -105,9 +105,9 @@ public function handle() $helpers = ''; if ($this->option('helpers') || ($this->config->get('ide-helper.include_helpers'))) { - foreach ($this->config->get('ide-helper.helper_files', array()) as $helper) { + foreach ($this->config->get('ide-helper.helper_files', []) as $helper) { if (file_exists($helper)) { - $helpers .= str_replace(array(''), '', $this->files->get($helper)); + $helpers .= str_replace([''], '', $this->files->get($helper)); } } } else { @@ -134,10 +134,10 @@ protected function useMemoryDriver() //Use a sqlite database in memory, to avoid connection errors on Database facades $this->config->set( 'database.connections.sqlite', - array( + [ 'driver' => 'sqlite', 'database' => ':memory:', - ) + ] ); $this->config->set('database.default', 'sqlite'); } @@ -151,11 +151,11 @@ protected function getArguments() { $filename = $this->config->get('ide-helper.filename'); - return array( - array( - 'filename', InputArgument::OPTIONAL, 'The path to the helper file', $filename - ), - ); + return [ + [ + 'filename', InputArgument::OPTIONAL, 'The path to the helper file', $filename, + ], + ]; } /** @@ -168,11 +168,11 @@ protected function getOptions() $format = $this->config->get('ide-helper.format'); $writeMixins = $this->config->get('ide-helper.write_eloquent_model_mixins'); - return array( - array('format', "F", InputOption::VALUE_OPTIONAL, 'The format for the IDE Helper', $format), - array('write_mixins', "W", InputOption::VALUE_OPTIONAL, 'Write mixins to Laravel Model?', $writeMixins), - array('helpers', "H", InputOption::VALUE_NONE, 'Include the helper files'), - array('memory', "M", InputOption::VALUE_NONE, 'Use sqlite memory driver'), - ); + return [ + ['format', 'F', InputOption::VALUE_OPTIONAL, 'The format for the IDE Helper', $format], + ['write_mixins', 'W', InputOption::VALUE_OPTIONAL, 'Write mixins to Laravel Model?', $writeMixins], + ['helpers', 'H', InputOption::VALUE_NONE, 'Include the helper files'], + ['memory', 'M', InputOption::VALUE_NONE, 'Use sqlite memory driver'], + ]; } } diff --git a/src/Console/MetaCommand.php b/src/Console/MetaCommand.php index 08bfcbe2b..b5cbf7258 100644 --- a/src/Console/MetaCommand.php +++ b/src/Console/MetaCommand.php @@ -23,7 +23,6 @@ */ class MetaCommand extends Command { - /** * The console command name. * @@ -87,7 +86,7 @@ public function handle() $this->registerClassAutoloadExceptions(); - $bindings = array(); + $bindings = []; foreach ($this->getAbstracts() as $abstract) { // Validator and seeder cause problems if (in_array($abstract, ['validator', 'seeder'])) { @@ -161,9 +160,9 @@ protected function getOptions() { $filename = $this->config->get('ide-helper.meta_filename'); - return array( - array('filename', 'F', InputOption::VALUE_OPTIONAL, 'The path to the meta file', $filename), - ); + return [ + ['filename', 'F', InputOption::VALUE_OPTIONAL, 'The path to the meta file', $filename], + ]; } /** diff --git a/src/Console/ModelsCommand.php b/src/Console/ModelsCommand.php index 4a9640fe7..ae1615255 100644 --- a/src/Console/ModelsCommand.php +++ b/src/Console/ModelsCommand.php @@ -58,10 +58,10 @@ class ModelsCommand extends Command protected $write_model_magic_where; protected $write_model_relation_count_properties; - protected $properties = array(); - protected $methods = array(); + protected $properties = []; + protected $methods = []; protected $write = false; - protected $dirs = array(); + protected $dirs = []; protected $reset; protected $keep_text; protected $phpstorm_noinspections; @@ -146,9 +146,9 @@ public function handle() */ protected function getArguments() { - return array( - array('model', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, 'Which models to include', array()), - ); + return [ + ['model', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, 'Which models to include', []], + ]; } /** @@ -158,20 +158,20 @@ protected function getArguments() */ protected function getOptions() { - return array( - array('filename', 'F', InputOption::VALUE_OPTIONAL, 'The path to the helper file', $this->filename), - array('dir', 'D', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, - 'The model dir, supports glob patterns', array()), - array('write', 'W', InputOption::VALUE_NONE, 'Write to Model file'), - array('nowrite', 'N', InputOption::VALUE_NONE, 'Don\'t write to Model file'), - array('reset', 'R', InputOption::VALUE_NONE, 'Remove the original phpdocs instead of appending'), - array('smart-reset', 'r', InputOption::VALUE_NONE, 'Refresh the properties/methods list, but keep the text'), - array('phpstorm-noinspections', 'p', InputOption::VALUE_NONE, + return [ + ['filename', 'F', InputOption::VALUE_OPTIONAL, 'The path to the helper file', $this->filename], + ['dir', 'D', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, + 'The model dir, supports glob patterns', [], ], + ['write', 'W', InputOption::VALUE_NONE, 'Write to Model file'], + ['nowrite', 'N', InputOption::VALUE_NONE, 'Don\'t write to Model file'], + ['reset', 'R', InputOption::VALUE_NONE, 'Remove the original phpdocs instead of appending'], + ['smart-reset', 'r', InputOption::VALUE_NONE, 'Refresh the properties/methods list, but keep the text'], + ['phpstorm-noinspections', 'p', InputOption::VALUE_NONE, 'Add PhpFullyQualifiedNameUsageInspection and PhpUnnecessaryFullyQualifiedNameInspection PHPStorm ' . - 'noinspection tags' - ), - array('ignore', 'I', InputOption::VALUE_OPTIONAL, 'Which models to ignore', ''), - ); + 'noinspection tags', + ], + ['ignore', 'I', InputOption::VALUE_OPTIONAL, 'Which models to ignore', ''], + ]; } protected function generateDocs($loadModels, $ignore = '') @@ -195,7 +195,7 @@ protected function generateDocs($loadModels, $ignore = '') if (empty($loadModels)) { $models = $this->loadModels(); } else { - $models = array(); + $models = []; foreach ($loadModels as $model) { $models = array_merge($models, explode(',', $model)); } @@ -203,7 +203,7 @@ protected function generateDocs($loadModels, $ignore = '') $ignore = array_merge( explode(',', $ignore), - $this->laravel['config']->get('ide-helper.ignored_models', array()) + $this->laravel['config']->get('ide-helper.ignored_models', []) ); foreach ($models as $name) { @@ -213,8 +213,8 @@ protected function generateDocs($loadModels, $ignore = '') } continue; } - $this->properties = array(); - $this->methods = array(); + $this->properties = []; + $this->methods = []; if (class_exists($name)) { try { // handle abstract classes, interfaces, ... @@ -248,7 +248,7 @@ protected function generateDocs($loadModels, $ignore = '') $ignore[] = $name; $this->nullableColumns = []; } catch (\Throwable $e) { - $this->error("Exception: " . $e->getMessage() . + $this->error('Exception: ' . $e->getMessage() . "\nCould not analyze class $name.\n\nTrace:\n" . $e->getTraceAsString()); } @@ -268,7 +268,7 @@ protected function generateDocs($loadModels, $ignore = '') protected function loadModels() { - $models = array(); + $models = []; foreach ($this->dirs as $dir) { if (is_dir(base_path($dir))) { $dir = base_path($dir); @@ -364,7 +364,7 @@ protected function castPropertiesType($model) */ protected function getTypeOverride($type) { - $typeOverrides = $this->laravel['config']->get('ide-helper.type_overrides', array()); + $typeOverrides = $this->laravel['config']->get('ide-helper.type_overrides', []); return $typeOverrides[$type] ?? $type; } @@ -382,7 +382,7 @@ protected function getPropertiesFromTable($model) $databasePlatform->registerDoctrineTypeMapping('enum', 'string'); $platformName = $databasePlatform->getName(); - $customTypes = $this->laravel['config']->get("ide-helper.custom_db_types.{$platformName}", array()); + $customTypes = $this->laravel['config']->get("ide-helper.custom_db_types.{$platformName}", []); foreach ($customTypes as $yourTypeName => $doctrineTypeName) { $databasePlatform->registerDoctrineTypeMapping($yourTypeName, $doctrineTypeName); } @@ -454,11 +454,11 @@ protected function getPropertiesFromTable($model) ); if ($this->write_model_magic_where) { $this->setMethod( - Str::camel("where_" . $name), + Str::camel('where_' . $name), $this->getClassNameInDestinationFile($model, \Illuminate\Database\Eloquent\Builder::class) . '|' . $this->getClassNameInDestinationFile($model, get_class($model)), - array('$value') + ['$value'] ); } } @@ -521,7 +521,7 @@ protected function getPropertiesFromMethods($model) $this->setMethod( $method, - $builder . "|" . $this->getClassNameInDestinationFile($model, get_class($model)) + $builder . '|' . $this->getClassNameInDestinationFile($model, get_class($model)) ); } elseif ( !method_exists('Illuminate\Database\Eloquent\Model', $method) @@ -552,7 +552,7 @@ protected function getPropertiesFromMethods($model) $code = substr($code, $begin, strrpos($code, '}') - $begin + 1); foreach ( - array( + [ 'hasMany' => '\Illuminate\Database\Eloquent\Relations\HasMany', 'hasManyThrough' => '\Illuminate\Database\Eloquent\Relations\HasManyThrough', 'hasOneThrough' => '\Illuminate\Database\Eloquent\Relations\HasOneThrough', @@ -563,8 +563,8 @@ protected function getPropertiesFromMethods($model) 'morphTo' => '\Illuminate\Database\Eloquent\Relations\MorphTo', 'morphMany' => '\Illuminate\Database\Eloquent\Relations\MorphMany', 'morphToMany' => '\Illuminate\Database\Eloquent\Relations\MorphToMany', - 'morphedByMany' => '\Illuminate\Database\Eloquent\Relations\MorphToMany' - ) as $relation => $impl + 'morphedByMany' => '\Illuminate\Database\Eloquent\Relations\MorphToMany', + ] as $relation => $impl ) { $search = '$this->' . $relation . '('; if (stripos($code, $search) || ltrim($impl, '\\') === ltrim((string)$type, '\\')) { @@ -621,7 +621,7 @@ protected function getPropertiesFromMethods($model) false ); } - } elseif ($relation === "morphTo") { + } elseif ($relation === 'morphTo') { // Model isn't specified because relation is polymorphic $this->setProperty( $method, @@ -688,7 +688,7 @@ protected function isRelationNullable(string $relation, Relation $relationObj): protected function setProperty($name, $type = null, $read = null, $write = null, $comment = '', $nullable = false) { if (!isset($this->properties[$name])) { - $this->properties[$name] = array(); + $this->properties[$name] = []; $this->properties[$name]['type'] = 'mixed'; $this->properties[$name]['read'] = false; $this->properties[$name]['write'] = false; @@ -709,12 +709,12 @@ protected function setProperty($name, $type = null, $read = null, $write = null, } } - protected function setMethod($name, $type = '', $arguments = array()) + protected function setMethod($name, $type = '', $arguments = []) { $methods = array_change_key_case($this->methods, CASE_LOWER); if (!isset($methods[strtolower($name)])) { - $this->methods[$name] = array(); + $this->methods[$name] = []; $this->methods[$name]['type'] = $type; $this->methods[$name]['arguments'] = $arguments; } @@ -752,13 +752,13 @@ protected function createPhpDocs($class) $phpdoc->setText($class); } - $properties = array(); - $methods = array(); + $properties = []; + $methods = []; foreach ($phpdoc->getTags() as $tag) { $name = $tag->getName(); - if ($name == "property" || $name == "property-read" || $name == "property-write") { + if ($name == 'property' || $name == 'property-read' || $name == 'property-write') { $properties[] = $tag->getVariableName(); - } elseif ($name == "method") { + } elseif ($name == 'method') { $methods[] = $tag->getMethodName(); } } @@ -797,22 +797,22 @@ protected function createPhpDocs($class) $phpdoc->appendTag($tag); } - if ($this->write && ! $phpdoc->getTagsByName('mixin')) { + if ($this->write && !$phpdoc->getTagsByName('mixin')) { $eloquentClassNameInModel = $this->getClassNameInDestinationFile($reflection, 'Eloquent'); - $phpdoc->appendTag(Tag::createInstance("@mixin " . $eloquentClassNameInModel, $phpdoc)); + $phpdoc->appendTag(Tag::createInstance('@mixin ' . $eloquentClassNameInModel, $phpdoc)); } if ($this->phpstorm_noinspections) { /** * Facades, Eloquent API * @see https://www.jetbrains.com/help/phpstorm/php-fully-qualified-name-usage.html */ - $phpdoc->appendTag(Tag::createInstance("@noinspection PhpFullyQualifiedNameUsageInspection", $phpdoc)); + $phpdoc->appendTag(Tag::createInstance('@noinspection PhpFullyQualifiedNameUsageInspection', $phpdoc)); /** * Relations, other models in the same namespace * @see https://www.jetbrains.com/help/phpstorm/php-unnecessary-fully-qualified-name.html */ $phpdoc->appendTag( - Tag::createInstance("@noinspection PhpUnnecessaryFullyQualifiedNameInspection", $phpdoc) + Tag::createInstance('@noinspection PhpUnnecessaryFullyQualifiedNameInspection', $phpdoc) ); } @@ -857,7 +857,7 @@ protected function createPhpDocs($class) public function getParameters($method) { //Loop through the default values for parameters, and make the correct output string - $paramsWithDefault = array(); + $paramsWithDefault = []; /** @var \ReflectionParameter $param */ foreach ($method->getParameters() as $param) { $paramClass = $param->getClass(); diff --git a/src/Eloquent.php b/src/Eloquent.php index 3a113782f..23f39dd98 100644 --- a/src/Eloquent.php +++ b/src/Eloquent.php @@ -8,12 +8,12 @@ namespace Barryvdh\LaravelIdeHelper; -use Illuminate\Console\Command; -use Illuminate\Filesystem\Filesystem; use Barryvdh\Reflection\DocBlock; use Barryvdh\Reflection\DocBlock\Context; use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer; use Barryvdh\Reflection\DocBlock\Tag; +use Illuminate\Console\Command; +use Illuminate\Filesystem\Filesystem; class Eloquent { diff --git a/src/Factories.php b/src/Factories.php index fffded871..7038edec0 100644 --- a/src/Factories.php +++ b/src/Factories.php @@ -8,7 +8,6 @@ class Factories { - public static function all() { $factories = []; diff --git a/src/Generator.php b/src/Generator.php index 6e1c487e7..d1b451711 100644 --- a/src/Generator.php +++ b/src/Generator.php @@ -11,10 +11,8 @@ namespace Barryvdh\LaravelIdeHelper; -use Illuminate\Foundation\Application; use Illuminate\Foundation\AliasLoader; use Illuminate\Support\Collection; -use ReflectionClass; use Symfony\Component\Console\Output\OutputInterface; class Generator @@ -28,9 +26,9 @@ class Generator /** @var \Symfony\Component\Console\Output\OutputInterface */ protected $output; - protected $extra = array(); - protected $magic = array(); - protected $interfaces = array(); + protected $extra = []; + protected $magic = []; + protected $interfaces = []; protected $helpers; /** @@ -40,8 +38,10 @@ class Generator * @param string $helpers */ public function __construct( - /*ConfigRepository */ $config, - /* Illuminate\View\Factory */ $view, + /*ConfigRepository */ + $config, + /* Illuminate\View\Factory */ + $view, OutputInterface $output = null, $helpers = '' ) { @@ -93,16 +93,16 @@ public function generatePhpHelper() public function generateJsonHelper() { - $classes = array(); + $classes = []; foreach ($this->getValidAliases() as $aliases) { foreach ($aliases as $alias) { - $functions = array(); + $functions = []; foreach ($alias->getMethods() as $method) { $functions[$method->getName()] = '(' . $method->getParamsWithDefault() . ')'; } - $classes[$alias->getAlias()] = array( + $classes[$alias->getAlias()] = [ 'functions' => $functions, - ); + ]; } } @@ -111,11 +111,11 @@ public function generateJsonHelper() $flags |= JSON_PRETTY_PRINT; } - return json_encode(array( - 'php' => array( + return json_encode([ + 'php' => [ 'classes' => $classes, - ), - ), $flags); + ], + ], $flags); } protected function detectDrivers() @@ -129,7 +129,7 @@ class_exists('Auth') && is_a('Auth', '\Illuminate\Support\Facades\Auth', true) && app()->bound('auth') ) { $class = get_class(\Auth::guard()); - $this->extra['Auth'] = array($class); + $this->extra['Auth'] = [$class]; $this->interfaces['\Illuminate\Auth\UserProviderInterface'] = $class; } } catch (\Exception $e) { @@ -138,7 +138,7 @@ class_exists('Auth') && is_a('Auth', '\Illuminate\Support\Facades\Auth', true) try { if (class_exists('DB') && is_a('DB', '\Illuminate\Support\Facades\DB', true)) { $class = get_class(\DB::connection()); - $this->extra['DB'] = array($class); + $this->extra['DB'] = [$class]; $this->interfaces['\Illuminate\Database\ConnectionInterface'] = $class; } } catch (\Exception $e) { @@ -148,7 +148,7 @@ class_exists('Auth') && is_a('Auth', '\Illuminate\Support\Facades\Auth', true) if (class_exists('Cache') && is_a('Cache', '\Illuminate\Support\Facades\Cache', true)) { $driver = get_class(\Cache::driver()); $store = get_class(\Cache::getStore()); - $this->extra['Cache'] = array($driver, $store); + $this->extra['Cache'] = [$driver, $store]; $this->interfaces['\Illuminate\Cache\StoreInterface'] = $store; } } catch (\Exception $e) { @@ -157,7 +157,7 @@ class_exists('Auth') && is_a('Auth', '\Illuminate\Support\Facades\Auth', true) try { if (class_exists('Queue') && is_a('Queue', '\Illuminate\Support\Facades\Queue', true)) { $class = get_class(\Queue::connection()); - $this->extra['Queue'] = array($class); + $this->extra['Queue'] = [$class]; $this->interfaces['\Illuminate\Queue\QueueInterface'] = $class; } } catch (\Exception $e) { @@ -166,7 +166,7 @@ class_exists('Auth') && is_a('Auth', '\Illuminate\Support\Facades\Auth', true) try { if (class_exists('SSH') && is_a('SSH', '\Illuminate\Support\Facades\SSH', true)) { $class = get_class(\SSH::connection()); - $this->extra['SSH'] = array($class); + $this->extra['SSH'] = [$class]; $this->interfaces['\Illuminate\Remote\ConnectionInterface'] = $class; } } catch (\Exception $e) { @@ -175,7 +175,7 @@ class_exists('Auth') && is_a('Auth', '\Illuminate\Support\Facades\Auth', true) try { if (class_exists('Storage') && is_a('Storage', '\Illuminate\Support\Facades\Storage', true)) { $class = get_class(\Storage::disk()); - $this->extra['Storage'] = array($class); + $this->extra['Storage'] = [$class]; $this->interfaces['\Illuminate\Contracts\Filesystem\Filesystem'] = $class; } } catch (\Exception $e) { @@ -198,7 +198,7 @@ protected function getValidAliases() continue; } - $magicMethods = array_key_exists($name, $this->magic) ? $this->magic[$name] : array(); + $magicMethods = array_key_exists($name, $this->magic) ? $this->magic[$name] : []; $alias = new Alias($this->config, $name, $facade, $magicMethods, $this->interfaces); if ($alias->isValid()) { //Add extra methods, from other classes (magic static calls) diff --git a/src/IdeHelperServiceProvider.php b/src/IdeHelperServiceProvider.php index eb7abec54..42b128a88 100644 --- a/src/IdeHelperServiceProvider.php +++ b/src/IdeHelperServiceProvider.php @@ -24,7 +24,6 @@ class IdeHelperServiceProvider extends ServiceProvider { - /** * Indicates if loading of the provider is deferred. * @@ -107,7 +106,7 @@ function ($app) { */ public function provides() { - return array('command.ide-helper.generate', 'command.ide-helper.models'); + return ['command.ide-helper.generate', 'command.ide-helper.models']; } /** diff --git a/src/Macro.php b/src/Macro.php index 7e88b22c2..2dd9e20d0 100644 --- a/src/Macro.php +++ b/src/Macro.php @@ -20,7 +20,7 @@ public function __construct( $alias, $class, $methodName = null, - $interfaces = array() + $interfaces = [] ) { parent::__construct($method, $alias, $class, $methodName, $interfaces); } diff --git a/src/Method.php b/src/Method.php index c66777b0b..ea090c6a2 100644 --- a/src/Method.php +++ b/src/Method.php @@ -13,10 +13,10 @@ use Barryvdh\Reflection\DocBlock; use Barryvdh\Reflection\DocBlock\Context; +use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer; use Barryvdh\Reflection\DocBlock\Tag; -use Barryvdh\Reflection\DocBlock\Tag\ReturnTag; use Barryvdh\Reflection\DocBlock\Tag\ParamTag; -use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer; +use Barryvdh\Reflection\DocBlock\Tag\ReturnTag; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Str; @@ -32,9 +32,9 @@ class Method protected $declaringClassName; protected $name; protected $namespace; - protected $params = array(); - protected $params_with_default = array(); - protected $interfaces = array(); + protected $params = []; + protected $params_with_default = []; + protected $interfaces = []; protected $real_name; protected $return = null; protected $root; @@ -46,7 +46,7 @@ class Method * @param string|null $methodName * @param array $interfaces */ - public function __construct($method, $alias, $class, $methodName = null, $interfaces = array()) + public function __construct($method, $alias, $class, $methodName = null, $interfaces = []) { $this->method = $method; $this->interfaces = $interfaces; @@ -119,7 +119,7 @@ public function getRoot() */ public function isInstanceCall() { - return ! ($this->method->isClosure() || $this->method->isStatic()); + return !($this->method->isClosure() || $this->method->isStatic()); } /** @@ -302,7 +302,7 @@ protected function convertKeywords($string) */ public function shouldReturn() { - if ($this->return !== "void" && $this->method->name !== "__construct") { + if ($this->return !== 'void' && $this->method->name !== '__construct') { return true; } @@ -318,8 +318,8 @@ public function shouldReturn() public function getParameters($method) { //Loop through the default values for parameters, and make the correct output string - $params = array(); - $paramsWithDefault = array(); + $params = []; + $paramsWithDefault = []; foreach ($method->getParameters() as $param) { $paramStr = $param->isVariadic() ? '...$' . $param->getName() : '$' . $param->getName(); $params[] = $paramStr; diff --git a/tests/Console/EloquentCommandTest.php b/tests/Console/EloquentCommandTest.php index 63774dce0..cf32c2725 100644 --- a/tests/Console/EloquentCommandTest.php +++ b/tests/Console/EloquentCommandTest.php @@ -1,5 +1,7 @@ CastType::class, ]; diff --git a/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/Test.php b/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/Test.php index 83532e337..a471b6112 100644 --- a/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/Test.php +++ b/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/Test.php @@ -6,12 +6,6 @@ use Barryvdh\LaravelIdeHelper\Console\ModelsCommand; use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand; -use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithFqn\Models\Post; -use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Eloquent\Relations\HasMany; -use Illuminate\Database\Eloquent\SoftDeletes; -use Illuminate\Filesystem\Filesystem; -use Mockery; class Test extends AbstractModelsCommand { diff --git a/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/__snapshots__/Test__test__1.php b/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/__snapshots__/Test__test__1.php index 736bc0d11..5dc83d073 100644 --- a/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/__snapshots__/Test__test__1.php +++ b/tests/Console/ModelsCommand/GeneratePhpdocWithFqn/__snapshots__/Test__test__1.php @@ -6,13 +6,11 @@ use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithFqn\Casts\CastType; use Eloquent; -use Illuminate\Database\Eloquent\{ - Builder as EloquentBuilder, - Collection, - SoftDeletes -}; +use Illuminate\Database\Eloquent\Builder as EloquentBuilder; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Support\Carbon; @@ -180,6 +178,18 @@ class Post extends Model { use SoftDeletes; + /** + * Special hack to avoid code style fixer removing unused imports + * which play a role when generating the snapshot + */ + private $hack = [ + Carbon::class, + Collection::class, + Eloquent::class, + EloquentBuilder::class, + QueryBuilder::class, + ]; + protected $casts = [ 'char_not_nullable' => CastType::class, ]; diff --git a/tests/Console/ModelsCommand/GeneratePhpdocWithFqnInExternalFile/Builders/EMaterialQueryBuilder.php b/tests/Console/ModelsCommand/GeneratePhpdocWithFqnInExternalFile/Builders/EMaterialQueryBuilder.php index 644d538c2..07d226d25 100644 --- a/tests/Console/ModelsCommand/GeneratePhpdocWithFqnInExternalFile/Builders/EMaterialQueryBuilder.php +++ b/tests/Console/ModelsCommand/GeneratePhpdocWithFqnInExternalFile/Builders/EMaterialQueryBuilder.php @@ -8,5 +8,4 @@ class EMaterialQueryBuilder extends Builder { - } diff --git a/tests/Console/ModelsCommand/GeneratePhpdocWithFqnInExternalFile/Test.php b/tests/Console/ModelsCommand/GeneratePhpdocWithFqnInExternalFile/Test.php index d02e0a4cf..72ac896ab 100644 --- a/tests/Console/ModelsCommand/GeneratePhpdocWithFqnInExternalFile/Test.php +++ b/tests/Console/ModelsCommand/GeneratePhpdocWithFqnInExternalFile/Test.php @@ -6,12 +6,6 @@ use Barryvdh\LaravelIdeHelper\Console\ModelsCommand; use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand; -use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithFqn\Models\Post; -use Illuminate\Database\Eloquent\Model; -use Illuminate\Database\Eloquent\Relations\HasMany; -use Illuminate\Database\Eloquent\SoftDeletes; -use Illuminate\Filesystem\Filesystem; -use Mockery; class Test extends AbstractModelsCommand { diff --git a/tests/Console/ModelsCommand/Getter/Test.php b/tests/Console/ModelsCommand/Getter/Test.php index 224b69cb2..bed8c3aa5 100644 --- a/tests/Console/ModelsCommand/Getter/Test.php +++ b/tests/Console/ModelsCommand/Getter/Test.php @@ -6,8 +6,6 @@ use Barryvdh\LaravelIdeHelper\Console\ModelsCommand; use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand; -use Illuminate\Filesystem\Filesystem; -use Mockery; class Test extends AbstractModelsCommand { diff --git a/tests/Console/ModelsCommand/Ignored/Models/Ignored.php b/tests/Console/ModelsCommand/Ignored/Models/Ignored.php index 73d3ffa44..ea52d7cce 100644 --- a/tests/Console/ModelsCommand/Ignored/Models/Ignored.php +++ b/tests/Console/ModelsCommand/Ignored/Models/Ignored.php @@ -4,7 +4,6 @@ namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Ignored\Models; -use DateTime; use Illuminate\Database\Eloquent\Model; class Ignored extends Model diff --git a/tests/Console/ModelsCommand/Ignored/Test.php b/tests/Console/ModelsCommand/Ignored/Test.php index d5c3c6b8d..58aa6b046 100644 --- a/tests/Console/ModelsCommand/Ignored/Test.php +++ b/tests/Console/ModelsCommand/Ignored/Test.php @@ -7,8 +7,6 @@ use Barryvdh\LaravelIdeHelper\Console\ModelsCommand; use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand; use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\Ignored\Models\Ignored; -use Illuminate\Filesystem\Filesystem; -use Mockery; class Test extends AbstractModelsCommand { @@ -17,7 +15,7 @@ protected function getEnvironmentSetUp($app) parent::getEnvironmentSetUp($app); $app['config']->set('ide-helper.ignored_models', [ - Ignored::class + Ignored::class, ]); } diff --git a/tests/Console/ModelsCommand/Interfaces/Test.php b/tests/Console/ModelsCommand/Interfaces/Test.php index 8ab7df67f..912f366f8 100644 --- a/tests/Console/ModelsCommand/Interfaces/Test.php +++ b/tests/Console/ModelsCommand/Interfaces/Test.php @@ -6,8 +6,6 @@ use Barryvdh\LaravelIdeHelper\Console\ModelsCommand; use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand; -use Illuminate\Filesystem\Filesystem; -use Mockery; final class Test extends AbstractModelsCommand { diff --git a/tests/Console/ModelsCommand/LaravelCustomCasts/Casts/CastedProperty.php b/tests/Console/ModelsCommand/LaravelCustomCasts/Casts/CastedProperty.php index e125157cb..d8b831418 100644 --- a/tests/Console/ModelsCommand/LaravelCustomCasts/Casts/CastedProperty.php +++ b/tests/Console/ModelsCommand/LaravelCustomCasts/Casts/CastedProperty.php @@ -1,8 +1,9 @@ bigIncrements('id'); - + $table->char('char_nullable')->nullable(); $table->char('char_not_nullable'); diff --git a/tests/MethodTest.php b/tests/MethodTest.php index 811ef57db..6285bc886 100644 --- a/tests/MethodTest.php +++ b/tests/MethodTest.php @@ -1,5 +1,7 @@