Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.67% covered (success)
97.67%
42 / 43
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
SourceBodyExtractor
97.67% covered (success)
97.67%
42 / 43
0.00% covered (danger)
0.00%
0 / 1
22
0.00% covered (danger)
0.00%
0 / 1
 extract
97.67% covered (success)
97.67%
42 / 43
0.00% covered (danger)
0.00%
0 / 1
22
1<?php
2declare(strict_types=1);
3/**
4 * Pop PHP Framework (https://www.popphp.org/)
5 *
6 * @link       https://github.com/popphp/popphp-framework
7 * @author     Nick Sagona, III <dev@noladev.com>
8 * @copyright  Copyright (c) 2009-2027 NOLA Interactive, LLC.
9 * @license    https://www.popphp.org/license     New BSD License
10 */
11
12/**
13 * @namespace
14 */
15namespace Pop\Code\Reflection\Support;
16
17/**
18 * Source body extractor class
19 *
20 * Recovers a method/function/closure's body as source text by slicing its declaring file between
21 * getStartLine()/getEndLine(). Both ReflectionMethod and ReflectionFunction extend
22 * ReflectionFunctionAbstract, so one helper serves MethodReflection and FunctionReflection, which
23 * previously each carried a near-identical, independently written copy of this logic.
24 *
25 * @category   Pop
26 * @package    Pop\Code
27 * @author     Nick Sagona, III <dev@noladev.com>
28 * @copyright  Copyright (c) 2009-2027 NOLA Interactive, LLC.
29 * @license    https://www.popphp.org/license     New BSD License
30 * @version    6.0.0
31 */
32class SourceBodyExtractor
33{
34
35    /**
36     * Cache of file() results, keyed by file path -- avoids re-reading and re-splitting the
37     * same source file once per method when a class with many methods is reflected.
38     * @var array<string, array<int, string>>
39     */
40    protected static array $fileCache = [];
41
42    /**
43     * Extract a method/function's body as source text
44     *
45     * @param  \ReflectionFunctionAbstract $reflection
46     * @param  bool                        $stripBraces
47     * @return string|null
48     */
49    public static function extract(\ReflectionFunctionAbstract $reflection, bool $stripBraces): string|null
50    {
51        $file = $reflection->getFileName();
52
53        if (empty($file) || !file_exists($file)) {
54            return null;
55        }
56
57        if (!isset(self::$fileCache[$file])) {
58            self::$fileCache[$file] = file($file);
59        }
60        $lines     = self::$fileCache[$file];
61        $startLine = $reflection->getStartLine() - 1;
62        $endLine   = $reflection->getEndLine() - 1;
63
64        if (!isset($lines[$startLine]) || !isset($lines[$endLine])) {
65            return null;
66        }
67
68        // Locate the line containing the function/method body's opening brace by tracking
69        // parenthesis depth. It is not necessarily the line immediately after the declaration:
70        // a parameter list (e.g. constructor property promotion) may span multiple lines.
71        //
72        // This is done with PHP's tokenizer rather than a raw character scan so that stray
73        // '(' / ')' / '{' characters inside a string literal or comment in the parameter list
74        // (e.g. a default value like `string $close = ')'`) are never mistaken for real parens.
75        $snippet = '<?php ' . implode('', array_slice($lines, $startLine, $endLine - $startLine + 1));
76        $tokens  = \PhpToken::tokenize($snippet);
77
78        $parenDepth = 0;
79        $seenParen  = false;
80        $braceLine  = null;
81
82        foreach ($tokens as $token) {
83            if ($token->text === '(') {
84                $parenDepth++;
85                $seenParen = true;
86            } else if ($token->text === ')') {
87                $parenDepth--;
88            } else if (($token->text === '{') && $seenParen && ($parenDepth === 0)) {
89                $braceLine = $startLine + $token->line - 1;
90                break;
91            }
92        }
93
94        $length = ($braceLine !== null) ? ($endLine - $braceLine) : 0;
95
96        if (($braceLine === null) || ($length <= 0)) {
97            return null;
98        }
99
100        if ($stripBraces) {
101            $lines = array_slice($lines, $braceLine + 1, $length);
102
103            if (preg_match('/[ ]+\}/', $lines[count($lines) - 1])) {
104                unset($lines[count($lines) - 1]);
105            }
106
107            $lines = array_values($lines);
108        } else {
109            $lines = array_slice($lines, $braceLine + 1, $length - 1);
110        }
111
112        if (isset($lines[0]) && str_starts_with($lines[0], ' ')) {
113            $spaces = strlen($lines[0]) - strlen(ltrim($lines[0]));
114            if ($spaces > 0) {
115                $lines = array_map(function ($value) use ($spaces) {
116                    if (substr($value, 0, $spaces) === str_repeat(' ', $spaces)) {
117                        $value = substr($value, $spaces);
118                    }
119                    return $value;
120                }, $lines);
121            }
122        }
123
124        $body = implode('', $lines);
125
126        return empty($body) ? null : $body;
127    }
128
129}