Completed
Push — master ( 699dc6...d8f60e )
by Changwan
05:50
created

MetadataReader   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 96.43%

Importance

Changes 0
Metric Value
dl 0
loc 53
ccs 27
cts 28
cp 0.9643
rs 10
c 0
b 0
f 0
wmc 10
lcom 1
cbo 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
D getMetadataFrom() 0 39 9
1
<?php
2
namespace Wandu\Database\Entity;
3
4
use Doctrine\Common\Annotations\Reader;
5
use ReflectionClass;
6
use Wandu\Database\Annotations\BelongTo;
7
use Wandu\Database\Annotations\Column;
8
use Wandu\Database\Annotations\Table;
9
use Wandu\Database\Contracts\Entity\MetadataReaderInterface;
10
11
class MetadataReader implements MetadataReaderInterface
12
{
13
    /** @var \Doctrine\Common\Annotations\Reader */
14
    protected $reader;
15
    
16 19
    public function __construct(Reader $reader)
17
    {
18 19
        $this->reader = $reader;
19 19
    }
20
21
    /**
22
     * {@inheritdoc}
23
     */
24 17
    public function getMetadataFrom(string $class): Metadata
25
    {
26
        $settings = [
27 17
            'class' => $class,
28
        ];
29 17
        $classRefl = new ReflectionClass($class);
30 17
        $propertiesRefl = $classRefl->getProperties();
31
32
        /* @var \Wandu\Database\Annotations\Table $table */
33 17
        if ($table = $this->reader->getClassAnnotation($classRefl, Table::class)) {
34 17
            $settings['connection'] = $table->connection;
35 17
            $settings['primaryKey'] = $table->primaryKey;
36 17
            $settings['increments'] = $table->increments;
37
        }
38
39 17
        $columns = [];
40 17
        $casts = [];
41 17
        $relations = [];
42 17
        foreach ($propertiesRefl as $propertyRefl) {
43 17
            foreach ($this->reader->getPropertyAnnotations($propertyRefl) as $prop) {
44 17
                if ($prop instanceof Column) {
45 17
                    $columns[$propertyRefl->name] = $prop->name;
46 17
                    $casts[$propertyRefl->name] = $prop->cast;
47
                } elseif ($prop instanceof BelongTo) {
48 17
                    $relations[$propertyRefl->name] = $prop;
49
                }
50
            }
51
        }
52 17
        if (count($columns)) {
53 17
            $settings['columns'] = $columns;
54
        }
55 17
        if (count($casts)) {
56 17
            $settings['casts'] = $casts;
57
        }
58 17
        if (count($relations)) {
59 4
            $settings['relations'] = $relations;
60
        }
61 17
        return new Metadata($table->name, $settings);
62
    }
63
}
64