Passed
Push — dev_2x ( 1e248d...fedccd )
by Adrian
01:40
created

OneToManyObserver::addAggregates()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 16
rs 9.9332
cc 3
nc 3
nop 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Sirius\Orm\CodeGenerator\Observer\Relation;
5
6
use Nette\PhpGenerator\ClassType;
7
use Sirius\Orm\Blueprint\Mapper;
8
use Sirius\Orm\Blueprint\Relation;
9
use Sirius\Orm\Blueprint\Relation\OneToMany;
10
use Sirius\Orm\CodeGenerator\Observer\Base;
11
use Sirius\Orm\Collection\Collection;
12
use Sirius\Orm\Contract\Relation\ToManyInterface;
13
use Sirius\Orm\Helpers\Inflector;
14
use Sirius\Orm\Helpers\Str;
15
16
class OneToManyObserver extends Base implements ToManyInterface
17
{
18
19
    /**
20
     * @var OneToMany
21
     */
22
    protected $relation;
23
24
    public function with(Relation $relation)
25
    {
26
        $clone           = clone($this);
27
        $clone->relation = $relation;
0 ignored issues
show
Documentation Bug introduced by
$relation is of type Sirius\Orm\Blueprint\Relation, but the property $relation was declared to be of type Sirius\Orm\Blueprint\Relation\OneToMany. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
28
29
        return $clone;
30
    }
31
32
    public function observe(string $key, $object)
33
    {
34
        if ($key == $this->relation->getMapper()->getName() . '_base_entity') {
35
            return $this->observeBaseEntity($object);
36
        }
37
38
        return $object;
39
    }
40
41
    public function __toString()
42
    {
43
        return sprintf('Observer for relation %s for mapper %s',
44
            $this->relation->getName(),
45
            $this->relation->getMapper()->getName()
46
        );
47
    }
48
49
    public function observeBaseEntity(ClassType $class)
50
    {
51
        $this->addAttributeToConstructor($class);
52
53
        $mapper        = $this->relation->getMapper();
54
        $name          = $this->relation->getName();
55
        $foreignMapper = $mapper->getOrm()->getMapper($this->relation->getForeignMapper());
56
        $type          = $foreignMapper->getEntityNamespace()
57
                         . '\\' . $foreignMapper->getEntityClass();
58
59
        $class->getNamespace()->addUse(Collection::class);
0 ignored issues
show
Deprecated Code introduced by
The function Nette\PhpGenerator\ClassType::getNamespace() has been deprecated: an object can be in multiple namespaces ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

59
        /** @scrutinizer ignore-deprecated */ $class->getNamespace()->addUse(Collection::class);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
60
        $class->getNamespace()->addUse($type, null, $type);
0 ignored issues
show
Deprecated Code introduced by
The function Nette\PhpGenerator\ClassType::getNamespace() has been deprecated: an object can be in multiple namespaces ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

60
        /** @scrutinizer ignore-deprecated */ $class->getNamespace()->addUse($type, null, $type);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
61
62
        if ($mapper->getEntityStyle() === Mapper::ENTITY_STYLE_PROPERTIES) {
63
            $class->addComment(sprintf('@property %s[]|Collection $%s', $type, $name));
64
        } else {
65
            $setter = $class->addMethod(Str::methodName($name, 'set'));
66
            $setter->setVisibility(ClassType::VISIBILITY_PUBLIC);
67
            $setter->addParameter('value')
68
                   ->setType('Collection');
69
            $setter->setBody('$this->set(\'' . $name . '\', $value);');
70
71
            $getter = $class->addMethod(Str::methodName($name, 'get'));
72
            $getter->setVisibility(ClassType::VISIBILITY_PUBLIC);
73
            $getter->setBody('return $this->get(\'' . $name . '\');');
74
            $getter->setReturnType('Collection');
75
            $getter->setComment(sprintf('@return Collection|%s[]', $type));
76
        }
77
78
        $singular = Inflector::singularize($name);
79
        $adder    = $class->addMethod(Str::methodName($singular, 'add'));
80
        $adder->setVisibility(ClassType::VISIBILITY_PUBLIC);
81
        $adder->addParameter($singular)
82
              ->setType($type);
83
        $adder->setBody(sprintf('$this->get(\'%s\')->add($%s);', $name, $singular));
84
85
        $class = $this->addAggregates($class);
86
87
        return $class;
88
    }
89
90
    private function addAttributeToConstructor(ClassType $class)
91
    {
92
        $name = $this->relation->getName();
93
94
        $constructor = $class->getMethod('__construct');
95
        $constructor->addBody(rtrim('
96
// this is a fail-safe procedure that will be executed
97
// only when you use `new Entity()` instead of `$mapper->newEntity()`
98
// ALWAYS try to use `$mapper->newEntity()`
99
if (!isset($this->attributes[\'' . $name . '\'])) {
100
    $this->attributes[\'' . $name . '\'] = new Collection;
101
}        
102
        '));
103
    }
104
105
    private function addAggregates(ClassType $class)
106
    {
107
        $mapper        = $this->relation->getMapper();
108
        $aggregates = $this->relation->getAggregates();
109
110
        foreach ($aggregates as $name => $aggregate) {
111
            if ($mapper->getEntityStyle() === Mapper::ENTITY_STYLE_PROPERTIES) {
112
                $class->addComment(sprintf('@property mixed $%s', $name));
113
            } else {
114
                $getter = $class->addMethod(Str::methodName($name, 'get'));
115
                $getter->setVisibility(ClassType::VISIBILITY_PUBLIC);
116
                $getter->setBody('return $this->get(\'' . $name . '\');');
117
            }
118
        }
119
120
        return $class;
121
    }
122
123
}
124