Completed
Push — master ( 8eb315...5aaba6 )
by Changwan
04:29
created

MetadataReader::getMetadata()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 36
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 25
c 0
b 0
f 0
nc 12
nop 1
dl 0
loc 36
ccs 25
cts 25
cp 1
crap 7
rs 6.7272
1
<?php
2
namespace Wandu\Database\Entity;
3
4
use Doctrine\Common\Annotations\Reader;
5
use ReflectionClass;
6
use Wandu\Database\Annotations\Cast;
7
use Wandu\Database\Annotations\Column;
8
use Wandu\Database\Annotations\RelationInterface;
9
use Wandu\Database\Annotations\Table;
10
use Wandu\Database\Contracts\Entity\MetadataReaderInterface;
11
12
class MetadataReader implements MetadataReaderInterface
13
{
14
    /** @var \Doctrine\Common\Annotations\Reader */
15
    protected $reader;
16
    
17 19
    public function __construct(Reader $reader)
18
    {
19 19
        $this->reader = $reader;
20 19
    }
21
22
    /**
23
     * {@inheritdoc}
24
     */
25 15
    public function getMetadata(string $class): Metadata
26
    {
27 15
        $class = ltrim($class, '\\');
28 15
        $settings = [];
29
30 15
        $classRefl = new ReflectionClass($class);
31 15
        $propertiesRefl = $classRefl->getProperties();
32
33
        /* @var \Wandu\Database\Annotations\Table $table */
34 15
        if ($table = $this->reader->getClassAnnotation($classRefl, Table::class)) {
35 15
            $settings['table'] = $table->name;
36 15
            $settings['connection'] = $table->connection;
37 15
            $settings['primaryKey'] = $table->primaryKey;
38 15
            $settings['increments'] = $table->increments;
39
        }
40
41 15
        $columns = [];
42 15
        $casts = [];
43 15
        $relations = [];
44 15
        foreach ($propertiesRefl as $propertyRefl) {
45 15
            foreach ($this->reader->getPropertyAnnotations($propertyRefl) as $prop) {
46 15
                if ($prop instanceof Column) {
47 15
                    $columns[$propertyRefl->name] = $prop;
48 15
                } elseif ($prop instanceof Cast) {
49 15
                    $casts[$propertyRefl->name] = $prop;
50 3
                } elseif ($prop instanceof RelationInterface) {
51 15
                    $relations[$propertyRefl->name] = $prop;
52
                }
53
            }
54
        }
55 15
        $settings['columns'] = $columns;
56 15
        $settings['casts'] = $casts;
57 15
        $settings['relations'] = $relations;
58
59 15
        return new Metadata($class, $settings);
60
    }
61
}
62