Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
NamespaceReflection
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
7
100.00% covered (success)
100.00%
1 / 1
 parse
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
7
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;
16
17use Pop\Code\Generator\NamespaceGenerator;
18
19/**
20 * Namespace reflection code class
21 *
22 * @category   Pop
23 * @package    Pop\Code
24 * @author     Nick Sagona, III <dev@noladev.com>
25 * @copyright  Copyright (c) 2009-2027 NOLA Interactive, LLC.
26 * @license    https://www.popphp.org/license     New BSD License
27 * @version    6.0.0
28 */
29class NamespaceReflection extends AbstractReflection
30{
31
32    /**
33     * Method to parse a namespace
34     *
35     * @param  mixed   $code
36     * @param  ?string $name
37     * @throws Exception
38     * @return NamespaceGenerator
39     */
40    public static function parse(mixed $code, ?string $name = null): NamespaceGenerator
41    {
42        if ($name === null) {
43            $matches = [];
44            preg_match_all('/^namespace(.*);$/m', $code, $matches);
45            if (isset($matches[1][0])) {
46                $name = $matches[1][0];
47            }
48        }
49
50        if (empty($name)) {
51            throw new Exception('Error: The namespace name has not been set.');
52        }
53
54        $namespace = new NamespaceGenerator($name);
55        $matches   = [];
56
57        preg_match_all('/^use(.*);$/m', $code, $matches);
58
59        if (isset($matches[1][0])) {
60            foreach ($matches[1] as $match) {
61                $match = trim($match);
62                if (str_contains($match, ' as ')) {
63                    [$use, $as] = explode(' as ', $match);
64                    $use = trim($use);
65                    $as  = trim($as);
66                } else {
67                    $use = $match;
68                    $as  = null;
69                }
70                $namespace->addUse($use, $as);
71            }
72        }
73
74        return $namespace;
75    }
76
77}