Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
UseStatementParser
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
5
100.00% covered (success)
100.00%
1 / 1
 parse
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
5
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 * Use-statement parser class
19 *
20 * Scrapes `use Foo\Bar;` / `use Foo\Bar as Baz;` lines out of raw PHP source text. Native reflection has
21 * no API for "which traits/classes does this file `use`," so ClassReflection and TraitReflection both
22 * need this; it previously lived as an identical copy of this regex in each of them.
23 *
24 * @category   Pop
25 * @package    Pop\Code
26 * @author     Nick Sagona, III <dev@noladev.com>
27 * @copyright  Copyright (c) 2009-2027 NOLA Interactive, LLC.
28 * @license    https://www.popphp.org/license     New BSD License
29 * @version    6.0.0
30 */
31class UseStatementParser
32{
33
34    /**
35     * Parse `use` statements out of raw PHP source
36     *
37     * @param  string $sourceCode
38     * @return array
39     */
40    public static function parse(string $sourceCode): array
41    {
42        $result  = [];
43        $matches = [];
44
45        preg_match_all('/[ ]+use(.*);$/m', $sourceCode, $matches);
46
47        foreach ($matches[1] as $u) {
48            $useAry = array_map('trim', explode(',', trim($u)));
49            foreach ($useAry as $useValue) {
50                if (strpos($useValue, ' as ') !== false) {
51                    [$use, $as] = explode(' as ', $useValue);
52                } else {
53                    $use = $useValue;
54                    $as  = null;
55                }
56                $result[trim($use)] = ($as !== null) ? trim($as) : null;
57            }
58        }
59
60        return $result;
61    }
62
63}