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