Completed
Push — master ( 8155ff...9fff48 )
by Changwan
03:00
created

MetadataReader::getMetadataFrom()   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
nc 12
nop 1
dl 0
loc 36
ccs 25
cts 25
cp 1
crap 7
rs 6.7272
c 0
b 0
f 0
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 21
    public function __construct(Reader $reader)
18
    {
19 21
        $this->reader = $reader;
20 21
    }
21
22
    /**
23
     * {@inheritdoc}
24
     */
25 19
    public function getMetadataFrom(string $class): Metadata
26
    {
27 19
        $class = ltrim($class, '\\');
28 19
        $settings = [];
29
30 19
        $classRefl = new ReflectionClass($class);
31 19
        $propertiesRefl = $classRefl->getProperties();
32
33
        /* @var \Wandu\Database\Annotations\Table $table */
34 19
        if ($table = $this->reader->getClassAnnotation($classRefl, Table::class)) {
35 19
            $settings['table'] = $table->name;
36 19
            $settings['connection'] = $table->connection;
37 19
            $settings['primaryKey'] = $table->primaryKey;
38 19
            $settings['increments'] = $table->increments;
39
        }
40
41 19
        $columns = [];
42 19
        $casts = [];
43 19
        $relations = [];
44 19
        foreach ($propertiesRefl as $propertyRefl) {
45 19
            foreach ($this->reader->getPropertyAnnotations($propertyRefl) as $prop) {
46 19
                if ($prop instanceof Column) {
47 19
                    $columns[$propertyRefl->name] = $prop;
48 19
                } elseif ($prop instanceof Cast) {
49 19
                    $casts[$propertyRefl->name] = $prop;
50 6
                } elseif ($prop instanceof RelationInterface) {
51 19
                    $relations[$propertyRefl->name] = $prop;
52
                }
53
            }
54
        }
55 19
        $settings['columns'] = $columns;
56 19
        $settings['casts'] = $casts;
57 19
        $settings['relations'] = $relations;
58
59 19
        return new Metadata($class, $settings);
60
    }
61
}
62