Passed
Pull Request — master (#95)
by David
02:49
created

AnnotationParser::parseAnnotation()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 2
nc 1
nop 1
1
<?php
2
declare(strict_types=1);
3
4
namespace TheCodingMachine\TDBM\Utils\Annotation;
5
6
use Doctrine\Common\Annotations\DocParser;
7
8
/**
9
 * Parses annotations in database columns.
10
 */
11
class AnnotationParser
12
{
13
    /**
14
     * @var DocParser
15
     */
16
    private $docParser;
17
18
    /**
19
     * AnnotationParser constructor.
20
     * @param string[] $annotations An array mapping the annotation name to the fully qualified class name
21
     */
22
    public function __construct(array $annotations)
23
    {
24
        $this->docParser = new DocParser();
25
        $this->docParser->setImports(array_change_key_case($annotations, \CASE_LOWER));
26
    }
27
28
    /**
29
     * @param array<string,string> $additionalAnnotations An array associating the name of the annotation in DB comments to the name of a fully qualified Doctrine annotation class
30
     */
31
    public static function buildWithDefaultAnnotations(array $additionalAnnotations): self
32
    {
33
        $defaultAnnotations = [
34
            'UUID' => UUID::class,
35
            'Autoincrement' => Autoincrement::class
36
        ];
37
        $annotations = $defaultAnnotations + $additionalAnnotations;
38
        return new self($annotations);
39
    }
40
41
    /**
42
     * Parses the doc comment and initializes all the values of interest.
43
     *
44
     */
45
    public function parse(string $comment, string $context): Annotations
46
    {
47
        // compatibility with UUID annotation from TDBM 5.0
48
        $comment = \str_replace(['@UUID v1', '@UUID v4'], ['@UUID("v1")', '@UUID("v4")'], $comment);
49
50
        // TODO: add context (table name...)
51
        $annotations = $this->docParser->parse($comment, $context);
52
53
        return new Annotations($annotations);
54
    }
55
}
56