Token::getName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace HansOtt\GraphQL\Shared;
4
5
use ReflectionClass;
6
7
abstract class Token
8
{
9
    public $type;
10
    public $value;
11
    public $location;
12
13 81
    final public function __construct($type, $value, Location $location)
14
    {
15 81
        $this->type = (int) $type;
16 81
        $this->value = (string) $value;
17 81
        $this->location = $location;
18 81
    }
19
20 15
    final private static function getNames()
21
    {
22 15
        static $typeToName;
23
24 15
        if (is_array($typeToName)) {
25 15
            return $typeToName;
26
        }
27
28 6
        $tokenClassName = get_called_class();
29 6
        $reflection = new ReflectionClass($tokenClassName);
30 6
        $constants = $reflection->getConstants();
31 6
        $typeToName = array_flip($constants);
32
33 6
        return $typeToName;
34
    }
35
36 15
    final public static function getNameFor($type)
37
    {
38 15
        $typeToName = static::getNames();
0 ignored issues
show
Bug introduced by
Since getNames() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of getNames() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
39
40 15
        return $typeToName[$type];
41
    }
42
43 15
    final public function getName()
44
    {
45 15
        return static::getNameFor($this->type);
46
    }
47
}
48