Completed
Push — master ( d8f60e...a72876 )
by Changwan
03:40
created

MetadataReader   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
dl 0
loc 50
ccs 26
cts 28
cp 0.9286
rs 10
c 0
b 0
f 0
wmc 8
lcom 1
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C getMetadataFrom() 0 36 7
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
                } elseif ($prop instanceof Cast) {
49 19
                    $casts[$propertyRefl->name] = $prop;
50
                } 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