Passed
Pull Request — master (#96)
by David
03:16
created

AnnotationParser::getTableAnnotations()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
declare(strict_types=1);
3
4
namespace TheCodingMachine\TDBM\Utils\Annotation;
5
6
use Doctrine\Common\Annotations\DocParser;
7
use Doctrine\DBAL\Schema\Column;
8
use Doctrine\DBAL\Schema\Table;
9
10
/**
11
 * Parses annotations in database columns.
12
 */
13
class AnnotationParser
14
{
15
    /**
16
     * @var DocParser
17
     */
18
    private $docParser;
19
20
    /**
21
     * AnnotationParser constructor.
22
     * @param string[] $annotations An array mapping the annotation name to the fully qualified class name
23
     */
24
    public function __construct(array $annotations)
25
    {
26
        $this->docParser = new DocParser();
27
        $this->docParser->setImports(array_change_key_case($annotations, \CASE_LOWER));
28
    }
29
30
    /**
31
     * @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
32
     */
33
    public static function buildWithDefaultAnnotations(array $additionalAnnotations): self
34
    {
35
        $defaultAnnotations = [
36
            'UUID' => UUID::class,
37
            'Autoincrement' => Autoincrement::class,
38
            'Bean' => Bean::class
39
        ];
40
        $annotations = $defaultAnnotations + $additionalAnnotations;
41
        return new self($annotations);
42
    }
43
44
    /**
45
     * Parses the doc comment and initializes all the annotations.
46
     */
47
    private function parse(string $comment, string $context): Annotations
48
    {
49
        // compatibility with UUID annotation from TDBM 5.0
50
        $comment = \str_replace(['@UUID v1', '@UUID v4'], ['@UUID("v1")', '@UUID("v4")'], $comment);
51
52
        $annotations = $this->docParser->parse($comment, $context);
53
54
        return new Annotations($annotations);
55
    }
56
57
    public function getTableAnnotations(Table $table): Annotations
58
    {
59
        $options = $table->getOptions();
60
        if (isset($options['comment'])) {
61
            return $this->parse($options['comment'], ' comment in table '.$table->getName());
62
        }
63
        return new Annotations([]);
64
    }
65
66
    public function getColumnAnnotations(Column $column, Table $table): Annotations
67
    {
68
        $comment = $column->getComment();
69
        if ($comment === null) {
70
            return new Annotations([]);
71
        }
72
        return $this->parse($comment, sprintf('comment of column %s in table %s', $column->getName(), $table->getName()));
73
    }
74
}
75