top-think / framework

ThinkPHP Framework
http://www.thinkphp.cn
Other
2.72k stars 1.05k forks source link

StyleCi 规则草案讨论 #2994

Closed big-dream closed 1 month ago

big-dream commented 6 months ago

因现在仓库每次的提交的 StyleCi 检查都不通过,且 StyleCi 的默认规则又不符合我们的需求,因此花了些时间整理出了 StyleCi 默认配置的影响。

一、配置文件

目前计划增加该配置文件

risky: false # 禁用风险类配置
version: 8.1 # PHP 版本
preset: recommended # 预设配置:推荐配置
tab-width: 4 # tab 宽度
use-tabs: false # 不使用 tab
disabled: # 禁用配置项
  - binary_operator_exactly_one_space
  - blank_line_after_opening_tag
  - concat_without_spaces
  - phpdoc_align
  - phpdoc_separation
  - phpdoc_summary
  - unalign_equals

二、问题配置项概览

以下为 styleci 推荐配置产生的影响范围概览,列举了推荐配置中,每项配置影响的文件数和行数。禁用列为 Y 的,表示个人认为影响范围较大,可不使用该配置。禁用列为 ? 的,个人拿不定主意,不确定要不要使用。

点击配置名可跳转到概览,点击配置详情可查看配置项说明,点击影响内容可查看完整影响内容。

配置名 文件数 增加行 删除行 配置详情 影响内容 禁用
align_double_arrow 5 32 32 查看 查看
alpha_ordered_imports 3 3 3 查看 查看
binary_operator_exactly_one_space 79 864 864 查看 查看 Y
blank_line_after_opening_tag 148 148 0 查看 查看 Y
blank_line_before_return 44 128 0 查看 查看
blank_line_before_throw 8 8 0 查看 查看
blank_line_before_try 1 1 0 查看 查看
concat_without_spaces 76 351 351 查看 查看 Y
declare_equal_normalize 28 28 28 查看 查看
heredoc_to_nowdoc 2 2 2 查看 查看
method_separation 27 2 28 查看 查看
new_with_parentheses 8 13 13 查看 查看
no_blank_lines_after_class_opening 26 0 26 查看 查看
no_unneeded_control_parentheses 1 1 1 查看 查看
no_unused_lambda_imports 1 1 1 查看 查看
no_useless_return 2 2 2 查看 查看
no_whitespace_in_blank_line 2 2 2 查看 查看
phpdoc_align 100 1510 1510 查看 查看 ?
phpdoc_no_access 87 0 756 查看 查看
phpdoc_no_package 36 0 36 查看 查看
phpdoc_no_useless_inheritdoc 2 3 3 查看 查看
phpdoc_order 18 32 32 查看 查看
phpdoc_scalar 16 28 28 查看 查看
phpdoc_separation 112 2824 1 查看 查看 Y
phpdoc_single_line_var_spacing 3 9 9 查看 查看
phpdoc_summary 122 1157 1157 查看 查看 Y
phpdoc_trim 1 0 1 查看 查看
phpdoc_types 4 5 5 查看 查看
post_increment 4 5 5 查看 查看
return_type_declaration 1 2 2 查看 查看
single_blank_line_before_namespace 13 13 0 查看 查看
single_quote 31 86 86 查看 查看
symfony_braces 65 28 96 查看 查看
unalign_equals 73 344 344 查看 查看 Y
union_type_without_spaces 3 6 6 查看 查看

二、问题详情

align_double_arrow

更改:5 个文件,增加 32 行,删除 32 行

match($a) {
-    1 =>  111,
+    1 =>  111,
-    2 =>   222,
+    2 => 222,
    3 => 333
}

alpha_ordered_imports

更改:3 个文件,增加 3 行,删除 3 行

-use SplFileInfo;
 use Closure;
+use SplFileInfo;
 use think\exception\FileException;

binary_operator_exactly_one_space

更改:79 个文件,增加 864 行,删除 864 行

     protected $catchExceptions = true;
-    protected $autoExit        = true;
+    protected $autoExit = true;
     protected $definition;
-    protected $defaultCommand  = 'list';
+    protected $defaultCommand = 'list';

     protected $defaultCommands = [
-        'help'             => Help::class,
-        'list'             => Lists::class,
-        'clear'            => Clear::class,
-        'make:command'     => MakeCommand::class,
-        'make:controller'  => Controller::class,
-        'make:model'       => Model::class,
-        'make:middleware'  => Middleware::class,
-        'make:validate'    => Validate::class,
-        'make:event'       => Event::class,
-        'make:listener'    => Listener::class,
-        'make:service'     => Service::class,
-        'make:subscribe'   => Subscribe::class,
-        'optimize:route'   => Route::class,
-        'optimize:schema'  => Schema::class,
-        'run'              => RunServer::class,
-        'version'          => Version::class,
-        'route:list'       => RouteList::class,
+        'help' => Help::class,
+        'list' => Lists::class,
+        'clear' => Clear::class,
+        'make:command' => MakeCommand::class,
+        'make:controller' => Controller::class,
+        'make:model' => Model::class,
+        'make:middleware' => Middleware::class,
+        'make:validate' => Validate::class,
+        'make:event' => Event::class,
+        'make:listener' => Listener::class,
+        'make:service' => Service::class,
+        'make:subscribe' => Subscribe::class,
+        'optimize:route' => Route::class,
+        'optimize:schema' => Schema::class,
+        'run' => RunServer::class,
+        'version' => Version::class,
+        'route:list' => RouteList::class,
         'service:discover' => ServiceDiscover::class,
-        'vendor:publish'   => VendorPublish::class,
+        'vendor:publish' => VendorPublish::class,
     ];

     /**

         if (isset($components['path'])) {
             $server = array_merge($server, [
                 'SCRIPT_FILENAME' => $components['path'],
-                'SCRIPT_NAME'     => $components['path'],
-                'REQUEST_URI'     => $components['path'],
+                'SCRIPT_NAME' => $components['path'],
+                'REQUEST_URI' => $components['path'],
             ]);
         }

         if (isset($components['host'])) {
             $server['SERVER_NAME'] = $components['host'];
-            $server['HTTP_HOST']   = $components['host'];
+            $server['HTTP_HOST'] = $components['host'];
         }

         if (isset($components['scheme'])) {
             if ('https' === $components['scheme']) {
-                $server['HTTPS']       = 'on';
+                $server['HTTPS'] = 'on';
                 $server['SERVER_PORT'] = 443;
             } else {
                 unset($server['HTTPS']);

     {
         array_unshift($parameters, $command);

-        $input  = new Input($parameters);
+        $input = new Input($parameters);
         $output = new Output($driver);

         $this->setCatchExceptions(false);

blank_line_after_opening_tag

更改:148 个文件,增加 148 行,删除 0 行

<?php
+
 // +----------------------------------------------------------------------
 // | ThinkPHP [ WE CAN DO IT JUST THINK ]
 // +----------------------------------------------------------------------

blank_line_before_return

更改:44 个文件,增加 128 行,删除 0 行

     public function name(string $name)
     {
         $this->name = $name;
+
         return $this;
     }

blank_line_before_throw

更改:8 个文件,增加 8 行,删除 0 行

         $msg = Lang::get($fileUploadErrors[$error]);
+
         throw new Exception($msg, $error);

blank_line_before_try

更改:1 个文件,增加 1 行,删除 0 行

                 if (is_callable([$instance, $action])) {
                     $vars = $this->request->param();
+
                     try {
                         $reflect = new ReflectionMethod($instance, $action);
                         // 严格获取当前操作方法名

concat_without_spaces

更改:76 个文件,增加 351 行,删除 351 行

-            $output = PHP_EOL . $output . PHP_EOL;
+            $output = PHP_EOL.$output.PHP_EOL;

declare_equal_normalize

更改:28 个文件,增加 28 行,删除 28 行

-declare(strict_types = 1);
+declare(strict_types=1);

heredoc_to_nowdoc

更改:2 个文件,增加 2 行,删除 2 行

-            <<<EOF
+            <<<'EOF'

method_separation

更改:27 个文件,增加 2 行,删除 28 行

     {
         return 'app' . ($app ? '\\' . $app : '');
     }
-
 }
interface SessionHandlerInterface
 {
     public function read(string $sessionId): string;
+
     public function delete(string $sessionId): bool;
+
     public function write(string $sessionId, string $data): bool;
 }

new_with_parentheses

更改:8 个文件,增加 13 行,删除 13 行

         if (is_null(static::$instance)) {
-            static::$instance = new static;
+            static::$instance = new static();
         }

no_blank_lines_after_class_opening

更改:26 个文件,增加 0 行,删除 26 行

class File extends SplFileInfo
 {
-
     /**
      * 文件hash规则
      * @var array

no_unneeded_control_parentheses

更改:1 个文件,增加 1 行,删除 1 行

         }

         // 域名检查
-        if ((isset($option['domain']) && !in_array($option['domain'], [$request->host(true), $request->subDomain()]))) {
+        if (isset($option['domain']) && !in_array($option['domain'], [$request->host(true), $request->subDomain()])) {
             return false;
         }

no_unused_lambda_imports

更改:1 个文件,增加 1 行,删除 1 行

-        $pipeline->send($request)->then(function ($request) use ($e, $response) {
+        $pipeline->send($request)->then(function ($request) use ($e ) {
             throw $e;
         });

no_useless_return

更改:2 个文件,增加 2 行,删除 2 行

             return $info;
         }
-        return;
+        
     }

no_whitespace_in_blank_line

更改:2 个文件,增加 2 行,删除 2 行

     protected function register()
     {
         $this->registered = true;
-        
+
         $this->resource->parseGroupRule($this->resource->getRule());
     }

phpdoc_align

更改:100 个文件,增加 1510 行,删除 1510 行

二次确认

     /**
      * 快速获取容器中的实例 支持依赖注入
      * @template T
-     * @param string|class-string<T> $name        类名或标识 默认获取当前应用实例
-     * @param array                  $args        参数
-     * @param bool                   $newInstance 是否每次创建新的实例
+     * @param  string|class-string<T> $name        类名或标识 默认获取当前应用实例
+     * @param  array                  $args        参数
+     * @param  bool                   $newInstance 是否每次创建新的实例
      * @return T|object|App
      */

phpdoc_no_access

更改:87 个文件,增加 0 行,删除 756 行

     /**
      * 架构方法
-     * @access public
      * @param string $rootPath 应用根目录
      */
     public function __construct(string $rootPath = '')

phpdoc_no_package

更改:36 个文件,增加 0 行,删除 36 行

/**
  * 配置管理类
- * @package think
  */
 class Config
 {

phpdoc_no_useless_inheritdoc

更改:2 个文件,增加 3 行,删除 3 行

     /**
-     * {@inheritdoc}
+     * 
      */
     public function choice(Input $input, $question, array $choices, $default = null)
     {

phpdoc_order

更改:18 个文件,增加 32 行,删除 32 行

     /**
      * 执行当前的指令
      * @access public
-     * @return int
      * @throws \Exception
+     * @return int
      * @api
      */

phpdoc_scalar

更改:16 个文件,增加 28 行,删除 28 行

     /**
      * 抛出HTTP异常
-     * @param integer|Response $code    状态码 或者 Response对象实例
+     * @param int|Response $code    状态码 或者 Response对象实例
      * @param string           $message 错误信息
      * @param array            $header  参数
      */

phpdoc_separation

更改:112 个文件,增加 2824 行,删除 1 行

     /**
      * 快速获取容器中的实例 支持依赖注入
+     *
      * @template T
+     *
      * @param string|class-string<T> $name        类名或标识 默认获取当前应用实例
      * @param array                  $args        参数
      * @param bool                   $newInstance 是否每次创建新的实例
+     *
      * @return T|object|App
      */

phpdoc_single_line_var_spacing

更改:3 个文件,增加 9 行,删除 9 行

-    /** @var  Input */
+    /** @var Input */
     protected $input;

phpdoc_summary

更改:122 个文件,增加 1157 行,删除 1157 行

     /**
-     * 快速获取容器中的实例 支持依赖注入
+     * 快速获取容器中的实例 支持依赖注入.
      * @template T
      * @param string|class-string<T> $name        类名或标识 默认获取当前应用实例
      * @param array                  $args        参数

phpdoc_trim

更改:1 个文件,增加 0 行,删除 1 行

      *
      * @param string $name
      * @return mixed
-     *
      */
     protected function createDriver(string $name)
     {

phpdoc_types

更改:4 个文件,增加 5 行,删除 5 行

      * @access public
      * @param string $rule  路由规则
      * @param string $route 路由地址
-     * @return Resource|ResourceRegister
+     * @return resource|ResourceRegister
      */
     public function resource(string $rule, string $route)
     {

    /**
      * 视图过滤
      * @access public
-     * @param Callable $filter 过滤方法或闭包
+     * @param callable $filter 过滤方法或闭包
      * @return $this
      */

post_increment

更改:4 个文件,增加 5 行,删除 5 行

private function parseShortOptionSet(string $name): void
     {
         $len = strlen($name);
-        for ($i = 0; $i < $len; ++$i) {
+        for ($i = 0; $i < $len; $i++) {
             if (!$this->definition->hasShortcut($name[$i])) {
                 throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $name[$i]));
             }
         }

         if ($argument->isRequired()) {
-            ++$this->requiredCount;
+            $this->requiredCount++;
         } else {
             $this->hasOptional = true;
         }

return_type_declaration

更改:1 个文件,增加 2 行,删除 2 行

     /**
      * 初始化
      */
-    protected function initialize():void
+    protected function initialize(): void
     {
         if (!$this->app->initialized()) {
             $this->app->initialize();

single_blank_line_before_namespace

更改:13 个文件,增加 13 行,删除 0 行

// +----------------------------------------------------------------------
 // | Author: liu21st <liu21st@gmail.com>
 // +----------------------------------------------------------------------
+
 namespace think;

single_quote

更改:31 个文件,增加 86 行,删除 86 行

-        $output->writeln("<info>Clear Successed</info>");
+        $output->writeln('<info>Clear Successed</info>');

symfony_braces

更改:65 个文件,增加 28 行,删除 96 行

class Cache extends Manager implements CacheInterface
 {
-
     protected $namespace = '\\think\\cache\\driver\\';

     /**

     {
         return $this->store()->tag($name);
     }
-
 }
-declare (strict_types = 1);
+declare(strict_types = 1);
-    protected function cacheHasExpired($filename) {
+    protected function cacheHasExpired($filename)
+    {
             try {
                 $this->app->log->record($log, 'error');
-            } catch (Exception $e) {}
+            } catch (Exception $e) {
+            }
-    protected function cacheHasExpired($filename) {
+    protected function cacheHasExpired($filename)
+    {
     public function bar()
     {
-
     }

unalign_equals

更改:73 个文件,增加 344 行,删除 344 行

考虑考虑

-        $this->thinkPath   = realpath(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
-        $this->rootPath    = $rootPath ? rtrim($rootPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $this->getDefaultRootPath();
-        $this->appPath     = $this->rootPath . 'app' . DIRECTORY_SEPARATOR;
+        $this->thinkPath = realpath(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
+        $this->rootPath = $rootPath ? rtrim($rootPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR : $this->getDefaultRootPath();
+        $this->appPath = $this->rootPath . 'app' . DIRECTORY_SEPARATOR;
     protected $catchExceptions = true;
-    protected $autoExit        = true;
+    protected $autoExit = true;
     protected $definition;
-    protected $defaultCommand  = 'list';
+    protected $defaultCommand = 'list';

union_type_without_spaces

更改:3 个文件,增加 6 行,删除 6 行

-                } catch (Throwable | Exception $e) {
+                } catch (Throwable|Exception $e) {
-    public function model(array | string | Closure $var, string | Closure $model = null, bool $exception = true)
+    public function model(array|string|Closure $var, string|Closure $model = null, bool $exception = true)
NHZEX commented 3 months ago

我建议放弃 StyleCi ,转为使用开源工具 php-cs-fixer。 并使用现代化的社区规范:PER-CS1.0

liu21st commented 2 months ago

我暂时设置了 只有pr的时候才会检测 这样基本不影响正式提交或合并 PER-CS1.0好像已经过时了吧 现在2.0了

big-dream commented 2 months ago

https://cs.symfony.com/doc/ruleSets/index.html

PER-CS 1.0 暂时还没标记为过时,但有更新的 PER-CS 2.0

改变为:

--- Original
+++ New
 <?php
 $foo = [
-   'bar' => [
-    'baz' => true,
-  ],
+    'bar' => [
+        'baz' => true,
+    ],
 ];
--- Original
+++ New
 <?php
-$bar = ( string )  $a;
-$foo = (int)$b;
+$bar = (string) $a;
+$foo = (int) $b;
--- Original
+++ New
 <?php
-$foo = 'bar' . 3 . 'baz'.'qux';
+$foo = 'bar'. 3 .'baz'.'qux';
--- Original
+++ New
 <?php

 class Foo
 {
-    public static function  bar   ( $baz , $foo )
+    public static function bar($baz , $foo)
     {
         return false;
     }
 }

-function  foo  ($bar, $baz)
+function foo($bar, $baz)
 {
     return false;
 }

 <?php
-$f = function () {};
+$f = function() {};

 <?php
-$f = fn () => null;
+$f = fn() => null;
--- Original
+++ New
 <?php
-function sample($a=10,$b=20,$c=30) {}
-sample(1,  2);
+function sample($a=10, $b=20, $c=30) {}
+sample(1, 2);

 <?php
-function sample($a=10,
-    $b=20,$c=30) {}
-sample(1,
-    2);
+function sample(
+    $a=10,
+    $b=20,
+    $c=30
+) {}
+sample(
+    1,
+    2
+);

 <?php
 sample(
     <<<EOD
         foo
-        EOD
-    ,
+        EOD,
     'bar'
 );
--- Original
+++ New
 <?php function foo(
     int $x
-)
-{
-}
+) {}
--- Original
+++ New
 <?php
 array(
     1,
-    2
+    2,
 );
big-dream commented 2 months ago

用 StyleCi 的一个好处就是,对于不符合规则的代码,会给出调整示例,且跟 github 比较搭配。

NHZEX commented 2 months ago

用 StyleCi 的一个好处就是,对于不符合规则的代码,会给出调整示例,且跟 github 比较搭配。

能使用更统一的标准就是好的一步(这样无论用哪个工具都能正确适配)。

php-cs-fixer主要是本地可用,ide也有支持,不依赖云端服务。

ps: php-cs-fixer可用使用phar打包版本:php-cs-fixer/shim,不污染项目依赖

liu21st commented 2 months ago

现代化编辑器都有类似插件或功能的 php-cs-fixer phpfmt 不知道StyleCi 现在搞什么幺蛾子