Completed
Pull Request — master (#80)
by David
04:22 queued 01:44
created

Type::setClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
4
namespace TheCodingMachine\GraphQL\Controllers\Annotations;
5
6
use BadMethodCallException;
7
use function class_exists;
8
use TheCodingMachine\GraphQL\Controllers\Annotations\Exceptions\ClassNotFoundException;
9
use TheCodingMachine\GraphQL\Controllers\MissingAnnotationException;
10
11
/**
12
 * The Type annotation must be put in a GraphQL type class docblock and is used to map to the underlying PHP class
13
 * this is exposed via this type.
14
 *
15
 * @Annotation
16
 * @Target({"CLASS"})
17
 * @Attributes({
18
 *   @Attribute("class", type = "string"),
19
 * })
20
 */
21
class Type
22
{
23
    /**
24
     * @var string|null
25
     */
26
    private $class;
27
28
    /**
29
     * Is the class having the annotation a GraphQL type itself?
30
     *
31
     * @var bool
32
     */
33
    private $selfType = false;
34
35
    /**
36
     * @param mixed[] $attributes
37
     */
38
    public function __construct(array $attributes = [])
39
    {
40
        if (isset($attributes['class'])) {
41
            $this->setClass($attributes['class']);
42
            if (!class_exists($this->class)) {
43
                throw ClassNotFoundException::couldNotFindClass($this->class);
44
            }
45
        } else {
46
            $this->selfType = true;
47
        }
48
    }
49
50
    /**
51
     * Returns the fully qualified class name of the targeted class.
52
     *
53
     * @return string
54
     */
55
    public function getClass(): string
56
    {
57
        if ($this->class === null) {
58
            throw new \RuntimeException('Empty class for @Type annotation. You MUST create the Type annotation object using the GraphQL-Controllers AnnotationReader');
59
        }
60
        return $this->class;
61
    }
62
63
    public function setClass(string $class): void
64
    {
65
        $this->class = ltrim($class, '\\');
66
    }
67
68
    public function isSelfType(): bool
69
    {
70
        return $this->selfType;
71
    }
72
}
73