MissingAnnotationArgumentException::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 26
rs 9.7666
c 0
b 0
f 0
cc 3
nc 4
nop 3
1
<?php
2
3
namespace Neimheadh\SonataAnnotationBundle\Exception;
4
5
use InvalidArgumentException;
6
use Neimheadh\SonataAnnotationBundle\Annotation\AnnotationInterface;
7
use ReflectionClass;
8
9
/**
10
 * A mandatory argument is missing on an annotation.
11
 */
12
class MissingAnnotationArgumentException extends InvalidArgumentException
13
{
14
15
    /**
16
     * @param AnnotationInterface|string  $annotation   Annotation object or
17
     *                                                  class.
18
     * @param string                      $argumentName Argument name.
19
     * @param ReflectionClass|string|null $class        Class using the
20
     *                                                  annotation.
21
     */
22
    public function __construct(
23
        $annotation,
24
        string $argumentName,
25
        $class = null
26
    ) {
27
        if (is_object($annotation)) {
28
            $annotation = get_class($annotation);
29
        }
30
31
        $class = $this->getClassName($class);
32
        if ($class) {
33
            $message = sprintf(
34
                'Argument "%s" is mandatory for annotation %s on %s.',
35
                $argumentName,
36
                $annotation,
37
                $class
38
            );
39
        } else {
40
            $message = sprintf(
41
                'Argument "%s" is mandatory for annotation %s.',
42
                $argumentName,
43
                $annotation,
44
            );
45
        }
46
47
        parent::__construct($message);
48
    }
49
50
    /**
51
     * Get given class name.
52
     *
53
     * @param string|object|null $class Class.
54
     *
55
     * @return string|null
56
     */
57
    private function getClassName($class): ?string
58
    {
59
        if ($class instanceof ReflectionClass) {
60
            $class = $class->getName();
61
        }
62
63
        if ($class !== null && !is_string($class)) {
64
            throw new InvalidArgumentException(
65
                'Invalid class (string|ReflectionClass|null) attribute.',
66
            );
67
        }
68
69
        return $class;
70
    }
71
72
}