{"id":10006432,"date":"2022-09-08T08:13:42","date_gmt":"2022-09-08T00:13:42","guid":{"rendered":"https:\/\/ityet.com\/?p=10006432"},"modified":"2022-09-08T08:13:42","modified_gmt":"2022-09-08T00:13:42","slug":"php-parser-%e5%ba%94%e7%94%a8%e4%b9%8b%e6%89%ab%e6%8f%8f%e5%8f%91%e7%8e%b0%e4%bb%a3%e7%a0%81%e4%b8%ad%e7%9a%84%e6%89%93%e5%8d%b0%e3%80%81%e8%be%93%e5%87%ba%e7%bb%93%e6%9e%84%e8%af%ad%e5%8f%a5","status":"publish","type":"post","link":"https:\/\/itmax.cn\/?p=10006432","title":{"rendered":"PHP-Parser \u5e94\u7528\u4e4b\u626b\u63cf\u53d1\u73b0\u4ee3\u7801\u4e2d\u7684\u6253\u5370\u3001\u8f93\u51fa\u7ed3\u6784\u8bed\u53e5"},"content":{"rendered":"<h2>PHP-Parser \u5e94\u7528\u4e4b\u626b\u63cf\u53d1\u73b0\u4ee3\u7801\u4e2d\u7684\u6253\u5370\u3001\u8f93\u51fa\u7ed3\u6784\u8bed\u53e5<\/h2>\n<blockquote><p><a href=\"https:\/\/link.segmentfault.com\/?enc=DGZsipegboRk%2BFAimZK7IQ%3D%3D.Egl5iOd5pxYzFH7%2F7ki30QX9Ufk5fDIqDdYpXwNOrWDhB7Yn2rr%2Fl7767MuxTv8P\" rel=\"nofollow\">PHP-Parser<\/a> \u662f\u7531 nikic \u5f00\u53d1\u7684\u4e00\u4e2a PHP \u62bd\u8c61\u8bed\u6cd5\u6811(AST)\u89e3\u6790\u5668\uff0c\u53ef\u65b9\u4fbf\u7684\u5c06\u4ee3\u7801\u4e0e\u62bd\u8c61\u8bed\u6cd5\u6811\u4e92\u76f8\u8f6c\u6362\u3002\u5de5\u7a0b\u4e0a\u5e38\u7528\u6765\u751f\u6210\u6a21\u677f\u4ee3\u7801(\u5982 rector)\u3001\u751f\u6210\u62bd\u8c61\u8bed\u6cd5\u6811\u8fdb\u884c\u9759\u6001\u5206\u6790(\u5982 phpstan)\u3002\u6700\u8fd1\u5b66\u4e60\u5e94\u7528(\u9759\u6001\u5206\u6790)\u4e86\u4e00\u4e0b\uff0c\u7f16\u5199\u4e86\u4e00\u4e2a\u7b80\u5355\u7684\u626b\u63cf\u53d1\u73b0\u4ee3\u7801\u4e2d\u7684\u6253\u5370\u3001\u8f93\u51fa\u7ed3\u6784\u8bed\u53e5\u7684\u547d\u4ee4(<a href=\"https:\/\/link.segmentfault.com\/?enc=USYIoCU3q2ima1hqqD6FEg%3D%3D.QdijIPU9L93zNOwyOGJrRUmYw67Ss6gHaxwUsDiVCMx8A4PVog3rbeLYvm4RHA7E0MMyKNXnwoTPlUNXP48UIbHN9yucOnBJdKrcO%2FPPVlKFVrLixIwI3f2BmbQXSnfQPoeWR9N2JXoTMe%2Byf5fSkQ%3D%3D\" rel=\"nofollow\">FindDumpStatementCommand<\/a>)\u3002<\/p><\/blockquote>\n<h3>\u6548\u679c<\/h3>\n<p><img decoding=\"async\" referrerpolicy=\"no-referrer\" src=\"https:\/\/segmentfault.com\/img\/bVc2fUr\" alt=\"\" title=\"\" loading=\"lazy\"><\/p>\n<h3>\u6d41\u7a0b\u6982\u8ff0<\/h3>\n<ol>\n<li>\u626b\u63cf\u62ff\u5230\u6307\u5b9a\u7684 PHP \u6587\u4ef6\u7ed3\u679c\u96c6<\/li>\n<li>\u63d0\u53d6\u6587\u4ef6\u5185\u5bb9\u8f6c\u5316\u4e3a\u62bd\u8c61\u8bed\u6cd5\u6811<\/li>\n<li>\u904d\u5386\u62bd\u8c61\u8bed\u6cd5\u6811\u8282\u70b9\uff0c\u5339\u914d\u7b26\u5408\u8981\u6c42\u7684\u8282\u70b9\uff0c\u6682\u5b58\u7b26\u5408\u8981\u6c42\u7684\u8282\u70b9\u4fe1\u606f<\/li>\n<li>\u8f93\u51fa\u8282\u70b9\u7ed3\u679c\u96c6\u4fe1\u606f<\/li>\n<\/ol>\n<h3><a href=\"https:\/\/link.segmentfault.com\/?enc=3fRkPdXn5WYcLlyvorGeGw%3D%3D.mP4PAmhcEnRzaUMEOWpO%2BHwkfMrUK7mUc7pmXykP5DBWDPPT2L8AQe6XxYWzutSOLrY6rbA3E7N6xLrYP7%2BNMqZ7jRdr%2BEFwS3A7JCflmMwcuFNu%2FfPTULoefFH2zYpLx65ELxvvtQwC5ImgnBv0IQ%3D%3D\" rel=\"nofollow\">FindDumpStatementCommand<\/a><\/h3>\n<pre><code class=\"php\">&lt;?php\n\n\/**\n * This file is part of the guanguans\/laravel-skeleton.\n *\n * (c) guanguans &lt;ityaozm@gmail.com&gt;\n *\n * This source file is subject to the MIT license that is bundled.\n *\n * @see https:\/\/github.com\/guanguans\/laravel-skeleton\n *\/\n\nnamespace App\/Console\/Commands;\n\nuse Composer\/XdebugHandler\/XdebugHandler;\nuse Illuminate\/Console\/Command;\nuse Illuminate\/Support\/Str;\nuse Illuminate\/Support\/Stringable;\nuse PhpParser\/Error;\nuse PhpParser\/Node;\nuse PhpParser\/NodeFinder;\nuse PhpParser\/ParserFactory;\nuse PhpParser\/PrettyPrinter\/Standard;\nuse SebastianBergmann\/Timer\/ResourceUsageFormatter;\nuse SebastianBergmann\/Timer\/Timer;\nuse Symfony\/Component\/Console\/Input\/InputInterface;\nuse Symfony\/Component\/Console\/Output\/OutputInterface;\nuse Symfony\/Component\/Finder\/Finder;\nuse Symfony\/Component\/Finder\/SplFileInfo;\n\nclass FindDumpStatementCommand extends Command\n{\n    \/** @var string *\/\n    protected $signature = '\n        find:dump-statement\n        {--dir=* : The directories to search for files}\n        {--path=* : The paths to search for files}\n        {--name=* : The names to search for files}\n        {--not-path=* : The paths to exclude from the search}\n        {--not-name=* : The names to exclude from the search}\n        {--s|struct=* : The structs to search}\n        {--f|func=* : The functions to search}\n        {--m|parse-mode=1 : The mode(1,2,3,4) to use for the PHP parser}\n        {--M|memory-limit= : The memory limit to use for the PHP parser}';\n    \/** @var string *\/\n    protected $description = 'Find dump statements in PHP files.';\n    \/** @var \/string[][] *\/\n    private $statements = [\n        'struct' =&gt; [\n            'echo',\n            'print',\n            'die',\n            'exit',\n        ],\n        'func' =&gt; [\n            'printf',\n            'vprintf',\n            'var_dump',\n            'dump',\n            'dd',\n            'print_r',\n            'var_export'\n        ]\n    ];\n\n    \/** @var \/Symfony\/Component\/Finder\/Finder *\/\n    private $fileFinder;\n    \/** @var \/PhpParser\/Parser *\/\n    private $parser;\n    \/** @var \/PhpParser\/NodeFinder *\/\n    private $nodeFinder;\n    \/** @var \/PhpParser\/PrettyPrinter\/Standard *\/\n    private $prettyPrinter;\n    \/** @var \/SebastianBergmann\/Timer\/ResourceUsageFormatter *\/\n    private $resourceUsageFormatter;\n\n    protected function initialize(InputInterface $input, OutputInterface $output)\n    {\n        $this-&gt;checkOptions();\n        $this-&gt;initializeEnvs();\n        $this-&gt;initializeProperties();\n    }\n\n    public function handle(Timer $timer)\n    {\n        $timer-&gt;start();\n        $this-&gt;withProgressBar($this-&gt;fileFinder, function (SplFileInfo $fileInfo) use (&amp;$findInfos, &amp;$odd) {\n            try {\n                $nodes = $this-&gt;parser-&gt;parse($fileInfo-&gt;getContents());\n            } catch (Error $e) {\n                $this-&gt;newLine();\n                $this-&gt;error(sprintf(&quot;The file of %s parse error: %s.&quot;, $fileInfo-&gt;getRealPath(), $e-&gt;getMessage()));\n\n                return;\n            }\n\n            $dumpNodes = $this-&gt;nodeFinder-&gt;find($nodes, function (Node $node) {\n                if (\n                    $node instanceof Node\/Stmt\/Expression\n                    &amp;&amp; $node-&gt;expr instanceof Node\/Expr\/FuncCall\n                    &amp;&amp; $node-&gt;expr-&gt;name instanceof Node\/Name\n                    &amp;&amp; in_array($node-&gt;expr-&gt;name-&gt;toString(), $this-&gt;statements['func'])\n                ) {\n                    return true;\n                }\n\n                return Str::of(class_basename(get_class($node)))\n                    -&gt;lower()\n                    -&gt;replaceLast('_', '')\n                    -&gt;is($this-&gt;statements['struct']);\n            });\n            if (empty($dumpNodes)) {\n                return;\n            }\n\n            $findInfos[] = array_map(function (Node $dumpNode) use ($fileInfo, $odd) {\n                if ($dumpNode instanceof Node\/Stmt\/Expression &amp;&amp; $dumpNode-&gt;expr instanceof Node\/Expr\/FuncCall) {\n                    $name = &quot;&lt;fg=cyan&gt;{$dumpNode-&gt;expr-&gt;name-&gt;parts[0]}&lt;\/&gt;&quot;;\n                    $type = '&lt;fg=cyan&gt;func&lt;\/&gt;';\n                } else {\n                    $name = Str::of(class_basename(get_class($dumpNode)))-&gt;lower()-&gt;replaceLast('_', '')-&gt;pipe(function (Stringable $name) {\n                        return &quot;&lt;fg=red&gt;$name&lt;\/&gt;&quot;;\n                    });\n                    $type = '&lt;fg=red&gt;struct&lt;\/&gt;';\n                }\n\n                $file = Str::of($fileInfo-&gt;getRealPath())-&gt;replace(base_path().DIRECTORY_SEPARATOR, '')-&gt;pipe(function (Stringable $file) use ($odd) {\n                    return $odd ? &quot;&lt;fg=green&gt;$file&lt;\/&gt;&quot; : &quot;&lt;fg=blue&gt;$file&lt;\/&gt;&quot;;\n                });\n                $line = Str::of($dumpNode-&gt;getAttribute('startLine'))-&gt;pipe(function (Stringable $line) use ($odd) {\n                    return $odd ? &quot;&lt;fg=green&gt;$line&lt;\/&gt;&quot; : &quot;&lt;fg=blue&gt;$line&lt;\/&gt;&quot;;\n                });\n                $formattedCode = Str::of($this-&gt;prettyPrinter-&gt;prettyPrint([$dumpNode]))-&gt;pipe(function (Stringable $formattedCode) use ($odd) {\n                    return $odd ? &quot;&lt;fg=green&gt;$formattedCode&lt;\/&gt;&quot; : &quot;&lt;fg=blue&gt;$formattedCode&lt;\/&gt;&quot;;\n                });\n\n                return [\n                    'index' =&gt; null,\n                    'name' =&gt; $name,\n                    'type' =&gt; $type,\n                    'file' =&gt; $file,\n                    'line' =&gt; $line,\n                    'formatted_code' =&gt; $formattedCode,\n                ];\n            }, $dumpNodes);\n\n            $odd = ! $odd;\n        });\n\n        $this-&gt;newLine();\n\n        if (empty($findInfos)) {\n            $this-&gt;info('The print statement was not found.');\n            $this-&gt;info($this-&gt;resourceUsageFormatter-&gt;resourceUsage($timer-&gt;stop()));\n\n            return static::INVALID;\n        }\n\n        $findInfos = array_map(function ($info, $index) {\n            $index++;\n            $info['index'] = &quot;&lt;fg=yellow&gt;$index&lt;\/&gt;&quot;;\n\n            return $info;\n        }, $findInfos = array_merge([], ...$findInfos), array_keys($findInfos));\n\n        $this-&gt;table(array_map(function ($name) {\n            return Str::of($name)-&gt;snake()-&gt;replace('_', ' ')-&gt;title();\n        }, array_keys($findInfos[0])), $findInfos);\n\n        $this-&gt;info($this-&gt;resourceUsageFormatter-&gt;resourceUsage($timer-&gt;stop()));\n\n        return self::SUCCESS;\n    }\n\n    protected function checkOptions()\n    {\n        if (! in_array($this-&gt;option('parse-mode'), [\n            ParserFactory::PREFER_PHP7,\n            ParserFactory::PREFER_PHP5,\n            ParserFactory::ONLY_PHP7,\n            ParserFactory::ONLY_PHP5])\n        ) {\n            $this-&gt;error('The parse-mode option is not valid(1,2,3,4).');\n            exit(1);\n        }\n\n        if ($this-&gt;option('struct')) {\n            $this-&gt;statements['struct'] = array_intersect($this-&gt;statements['struct'], $this-&gt;option('struct'));\n        }\n\n        if ($this-&gt;option('func')) {\n            $this-&gt;statements['func'] = array_intersect($this-&gt;statements['func'], $this-&gt;option('func'));\n        }\n    }\n\n    protected function initializeEnvs()\n    {\n        $xdebug = new XdebugHandler(__CLASS__);\n        $xdebug-&gt;check();\n        unset($xdebug);\n\n        extension_loaded('xdebug') and ini_set('xdebug.max_nesting_level', 2048);\n        ini_set('zend.assertions', 0);\n        $this-&gt;option('memory-limit') and ini_set('memory_limit', $this-&gt;option('memory-limit'));\n    }\n\n    protected function initializeProperties()\n    {\n        $this-&gt;fileFinder = tap(Finder::create()-&gt;files()-&gt;ignoreDotFiles(true)-&gt;ignoreVCS(true), function (Finder $finder) {\n            $methods = [\n                'in' =&gt; $this-&gt;option('dir') ?: [base_path()],\n                'path' =&gt; $this-&gt;option('path') ?: [],\n                'notPath' =&gt; $this-&gt;option('not-path') ?: ['vendor', 'storage'],\n                'name' =&gt; $this-&gt;option('name') ?: ['*.php'],\n                'notName' =&gt; $this-&gt;option('not-name') ?: [],\n            ];\n            foreach ($methods as $method =&gt; $parameters) {\n                $finder-&gt;{$method}($parameters);\n            }\n        });\n\n        $this-&gt;parser = (new ParserFactory())-&gt;create((int)$this-&gt;option('parse-mode'));\n        $this-&gt;nodeFinder = new NodeFinder();\n        $this-&gt;prettyPrinter = new Standard();\n        $this-&gt;resourceUsageFormatter = new ResourceUsageFormatter();\n    }\n}<\/code><\/pre>\n<h3>\u539f\u6587\u94fe\u63a5<\/h3>\n<ul>\n<li><a href=\"https:\/\/link.segmentfault.com\/?enc=XFs9sgg2KO%2FMwjfKzDiyGw%3D%3D.oXUpsFJj6lvyDy%2B2d0%2B0dpBhOtZqBQsCilNv%2BmCrmuQZdvmOFtDB6rQIBOxv7N4%2Ff2MpMZkHv5r2HRTFsnF%2FJQ%3D%3D\" rel=\"nofollow\">https:\/\/github.com\/guanguans\/guanguans.github.io\/issues\/49<\/a><\/li>\n<\/ul>\n<p><a href=\"https:\/\/segmentfault.com\/a\/1190000042444476\">https:\/\/segmentfault.com\/a\/1190000042444476<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>PHP-Parser \u5e94\u7528\u4e4b\u626b\u63cf\u53d1\u73b0\u4ee3\u7801\u4e2d\u7684\u6253\u5370\u3001\u8f93\u51fa\u7ed3\u6784\u8bed\u53e5 PHP-Parser \u662f\u7531 nikic \u5f00\u53d1\u7684 [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[],"tags":[],"class_list":["post-10006432","post","type-post","status-publish","format-standard","hentry"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10006432","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/types\/post"}],"replies":[{"embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=10006432"}],"version-history":[{"count":0,"href":"https:\/\/itmax.cn\/index.php?rest_route=\/wp\/v2\/posts\/10006432\/revisions"}],"wp:attachment":[{"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=10006432"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=10006432"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itmax.cn\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=10006432"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}