Completed
Branch master (a17b64)
by Rémi
15:50
created

EntityBuilder::getLazyLoadingProxies()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 5
nop 1
dl 0
loc 22
rs 8.9197
c 0
b 0
f 0
1
<?php
2
3
namespace Analogue\ORM\System;
4
5
use Analogue\ORM\System\Wrappers\Factory;
6
use Analogue\ORM\System\Proxies\ProxyFactory;
7
use Analogue\ORM\System\Proxies\CollectionProxy;
8
9
/**
10
 * This class builds an array of Entity object(s) from a result set.
11
 */
12
class EntityBuilder
13
{
14
    /**
15
     * The mapper for the entity to build
16
     * @var \Analogue\ORM\System\Mapper
17
     */
18
    protected $mapper;
19
20
    /**
21
     * The Entity Map for the entity to build.
22
     *
23
     * @var \Analogue\ORM\EntityMap
24
     */
25
    protected $entityMap;
26
27
    /**
28
     * Relations that will be eager loaded on this query
29
     *
30
     * @var array
31
     */
32
    protected $eagerLoads;
33
34
    /**
35
     * Relations that will be lazy loaded on this query
36
     *
37
     * @var array
38
     */
39
    protected $lazyLoads;
40
41
    /**
42
     * @var array
43
     */
44
    protected $casts;
45
46
    /**
47
     * Entity Wrapper Factory
48
     * @var \Analogue\ORM\System\Wrappers\Factory
49
     */
50
    protected $factory;
51
52
    /**
53
     * EntityBuilder constructor.
54
     * @param Mapper $mapper
55
     * @param array  $eagerLoads
56
     */
57
    public function __construct(Mapper $mapper, array $eagerLoads)
58
    {
59
        $this->mapper = $mapper;
60
61
        $this->entityMap = $mapper->getEntityMap();
62
63
        $this->eagerLoads = $eagerLoads;
64
65
        $this->lazyLoads = $this->getRelationshipsToProxy();
66
67
        $this->factory = new Factory;
68
    }
69
70
    /**
71
     * Convert an array of values into an entity.
72
     *
73
     * @param  array $result
74
     * @return array
75
     */
76
    public function build(array $result)
77
    {
78
        $keyName = $this->entityMap->getKeyName();
79
80
        $tmpCache = [];
81
82
        $instance = $this->getWrapperInstance();
83
        
84
        $tmpCache[$result[$keyName]] = $result;
85
86
        // Hydrate any embedded Value Object
87
        $this->hydrateValueObjects($result);
88
89
        $instance->setEntityAttributes($result);
90
91
        // Hydrate relationship attributes with lazyloading proxies
92
        if (count($this->lazyLoads) > 0) {
93
            $instance->setProxies($this->lazyLoads);
94
        }
95
96
        // Directly Unwrap the entity now that it has been hydrated
97
        $entity = $instance->getObject();
98
99
        $this->mapper->getEntityCache()->add($tmpCache);
100
101
        return $entity;
102
    }
103
104
    /**
105
     * Get the correct wrapper prototype corresponding to the object type
106
     *
107
     * @throws \Analogue\ORM\Exceptions\MappingException
108
     * @return InternallyMappable
109
     */
110
    protected function getWrapperInstance()
111
    {
112
        return $this->factory->make($this->mapper->newInstance());
113
    }
114
115
    /**
116
     * Hydrate value object embedded in this entity
117
     *
118
     * @param  array $attributes
119
     * @throws \Analogue\ORM\Exceptions\MappingException
120
     * @return void
121
     */
122
    protected function hydrateValueObjects(& $attributes)
123
    {
124
        foreach ($this->entityMap->getEmbeddables() as $localKey => $valueClass) {
125
            $this->hydrateValueObject($attributes, $localKey, $valueClass);
126
        }
127
    }
128
129
    /**
130
     * Hydrate a single value object
131
     *
132
     * @param  array  $attributes
133
     * @param  string $localKey
134
     * @param  string $valueClass
135
     * @throws \Analogue\ORM\Exceptions\MappingException
136
     * @return void
137
     */
138
    protected function hydrateValueObject(& $attributes, $localKey, $valueClass)
139
    {
140
        $map = $this->mapper->getManager()->getValueMap($valueClass);
141
142
        $embeddedAttributes = $map->getAttributes();
143
144
        $valueObject = $this->mapper->getManager()->getValueObjectInstance($valueClass);
145
146
        foreach ($embeddedAttributes as $key) {
147
            $prefix = snake_case(class_basename($valueClass)) . '_';
148
149
            $voWrapper = $this->factory->make($valueObject);
150
151
            $voWrapper->setEntityAttribute($key, $attributes[$prefix . $key]);
152
153
            unset($attributes[$prefix . $key]);
154
        }
155
156
        $attributes[$localKey] = $valueObject;
157
    }
158
159
    /**
160
     * Deduce the relationships for which we will build lazy loading proxies
161
     *
162
     * @return array
163
     */
164
    protected function getRelationshipsToProxy()
165
    {
166
        $relations = $this->entityMap->getRelationships();
167
168
        return array_diff($relations, $this->eagerLoads);
169
    }
170
171
    /**
172
     * Build lazy loading proxies for the current entity
173
     *
174
     * @param InternallyMappable $entity
175
     *
176
     * @return array
177
     */
178
    protected function getLazyLoadingProxies(InternallyMappable $entity)
179
    {
180
        $proxies = [];
181
182
        $singleRelations = $this->entityMap->getSingleRelationships();
183
        $manyRelations = $this->entityMap->getManyRelationships();
184
185
        $proxyFactory = new ProxyFactory;
186
187
        foreach ($this->lazyLoads as $relation) {
188
            if (in_array($relation, $singleRelations)) {
189
                //$proxies[$relation] = new EntityProxy($entity->getObject(), $relation);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
190
                $targetClass = $this->entityMap->getTargetClass($relation);
0 ignored issues
show
Bug introduced by
The method getTargetClass() does not exist on Analogue\ORM\EntityMap. Did you maybe mean getClass()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
191
                $proxies[$relation] = $proxyFactory->make($entity->getObject(), $relation, $targetClass);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Analogue\ORM\System\InternallyMappable as the method getObject() does only exist in the following implementations of said interface: Analogue\ORM\System\Wrappers\EntityWrapper, Analogue\ORM\System\Wrappers\PlainObjectWrapper, Analogue\ORM\System\Wrappers\Wrapper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
192
            }
193
            if (in_array($relation, $manyRelations)) {
194
                $proxies[$relation] = new CollectionProxy($entity->getObject(), $relation);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Analogue\ORM\System\InternallyMappable as the method getObject() does only exist in the following implementations of said interface: Analogue\ORM\System\Wrappers\EntityWrapper, Analogue\ORM\System\Wrappers\PlainObjectWrapper, Analogue\ORM\System\Wrappers\Wrapper.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
195
            }
196
        }
197
198
        return $proxies;
199
    }
200
}