Name::createNode()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
/**
3
 * This program is free software. It comes without any warranty, to
4
 * the extent permitted by applicable law. You can redistribute it
5
 * and/or modify it under the terms of the Do What The Fuck You Want
6
 * To Public License, Version 2, as published by Sam Hocevar. See
7
 * http://www.wtfpl.net/ for more details.
8
 */
9
10
declare(strict_types = 1);
11
12
namespace hanneskod\classtools;
13
14
use PhpParser\Node\Name as PhpParserName;
15
16
/**
17
 * Internal name representation
18
 *
19
 * @author Hannes Forsgård <[email protected]>
20
 */
21
class Name
22
{
23
    /**
24
     * @var string[] Name components
25
     */
26
    private $parts;
27
28
    /**
29
     * Set name at construct
30
     */
31
    public function __construct(string $name)
32
    {
33
        $this->parts = explode('\\', $name);
34
    }
35
36
    /**
37
     * Get as string
38
     */
39
    public function __tostring(): string
40
    {
41
        return implode('\\', $this->parts);
42
    }
43
44
    /**
45
     * Get PhpParser node for this name
46
     */
47
    public function createNode(): PhpParserName
48
    {
49
        return new PhpParserName($this->parts);
50
    }
51
52
    /**
53
     * Checks if a class, interface, trait or function has been defined
54
     */
55
    public function isDefined(bool $autoload = true): bool
56
    {
57
        return class_exists((string)$this, $autoload)
58
            || interface_exists((string)$this, $autoload)
59
            || trait_exists((string)$this, $autoload)
60
            || function_exists((string)$this);
61
    }
62
63
    /**
64
     * Remove leading backslashes
65
     */
66
    public function normalize(): string
67
    {
68
        return preg_replace('/^\\\*/', '', (string)$this);
69
    }
70
71
    /**
72
     * Remove leading backslashes and convert case
73
     */
74
    public function keyize(): string
75
    {
76
        return strtolower($this->normalize());
77
    }
78
79
    /**
80
     * Get trailing name component
81
     */
82
    public function getBasename(): Name
83
    {
84
        return new Name((string)end($this->parts));
85
    }
86
87
    /**
88
     * Get parent namespace name component
89
     */
90
    public function getNamespace(): Name
91
    {
92
        $parts = $this->parts;
93
        array_pop($parts);
94
        return new Name(implode('\\', $parts));
95
    }
96
97
    /**
98
     * Check if name is in namespace
99
     */
100
    public function inNamespace(Name $namespace): bool
101
    {
102
        return !!preg_match(
103
            '/^'.preg_quote($namespace->keyize()).'/',
104
            $this->getNamespace()->keyize()
105
        );
106
    }
107
}
108