LdapObjectSubscriber   B
last analyzed

Complexity

Total Complexity 36

Size/Duplication

Total Lines 257
Duplicated Lines 17.12 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 36
c 1
b 0
f 0
lcom 1
cbo 11
dl 44
loc 257
rs 8.8

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getSubscribedEvents() 0 8 1
A preUpdate() 0 4 1
A prePersist() 0 4 1
A postLoad() 12 12 3
A transformValueForDb() 12 12 3
A getLdapObjectAnnotationProperties() 0 14 3
B setLdapObjectForProperty() 0 18 5
A setLdapValueForProperty() 0 20 4
A getLdapAttributesToSelect() 0 18 3
A getObjectFromLifeCycleArgs() 10 10 2
A getOmFromLifeCycleArgs() 10 10 2
C queryLdapForObjects() 0 28 7

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * This file is part of the LdapToolsBundle package.
4
 *
5
 * (c) Chad Sikorra <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LdapTools\Bundle\LdapToolsBundle\Doctrine\Subscriber;
12
13
use Doctrine\Common\Annotations\Reader;
14
use Doctrine\Common\EventSubscriber;
15
use Doctrine\Common\Persistence\ObjectManager;
16
use LdapTools\Bundle\LdapToolsBundle\Annotation\LdapObject as LdapObjectAnnotation;
17
use Doctrine\ORM\Event\LifecycleEventArgs;
18
use LdapTools\LdapManager;
19
use LdapTools\Object\LdapObject;
20
use LdapTools\Object\LdapObjectCollection;
21
22
/**
23
 * Doctrine Lifecycle Events to load/save LDAP objects to an entity property.
24
 *
25
 * @author Chad Sikorra <[email protected]>
26
 */
27
class LdapObjectSubscriber implements EventSubscriber
28
{
29
    /**
30
     * The annotation class to check for.
31
     */
32
    const ANNOTATION = 'LdapTools\Bundle\LdapToolsBundle\Annotation\LdapObject';
33
34
    /**
35
     * @var Reader
36
     */
37
    protected $reader;
38
39
    /**
40
     * @var LdapManager
41
     */
42
    protected $ldap;
43
44
    /**
45
     * @param Reader $reader
46
     * @param LdapManager $ldap
47
     */
48
    public function __construct(Reader $reader, LdapManager $ldap)
49
    {
50
        $this->reader = $reader;
51
        $this->ldap = $ldap;
52
    }
53
54
    /**
55
     * @return array
56
     */
57
    public function getSubscribedEvents()
58
    {
59
        return [
60
            'prePersist',
61
            'preUpdate',
62
            'postLoad',
63
        ];
64
    }
65
66
    /**
67
     * @param LifecycleEventArgs $args
68
     */
69
    public function preUpdate(LifecycleEventArgs $args)
70
    {
71
        $this->transformValueForDb($args);
72
    }
73
74
    /**
75
     * @param LifecycleEventArgs $args
76
     */
77
    public function prePersist(LifecycleEventArgs $args)
78
    {
79
        $this->transformValueForDb($args);
80
    }
81
82
    /**
83
     * @param LifecycleEventArgs $args
84
     */
85 View Code Duplication
    public function postLoad(LifecycleEventArgs $args)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86
    {
87
        $entity = $this->getObjectFromLifeCycleArgs($args);
88
        $om = $this->getOmFromLifeCycleArgs($args);
89
90
        $properties = $this->getLdapObjectAnnotationProperties($entity, $om);
91
        foreach ($properties as $info) {
92
            if ($info['property']->getValue($entity)) {
93
                $this->setLdapObjectForProperty($info['property'], $info['annotation'], $entity);
94
            }
95
        }
96
    }
97
98
    /**
99
     * Handles transforming the value as it currently is to the value the DB expects.
100
     *
101
     * @param LifecycleEventArgs $args
102
     */
103 View Code Duplication
    protected function transformValueForDb(LifecycleEventArgs $args)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
    {
105
        $entity = $this->getObjectFromLifeCycleArgs($args);
106
        $om = $this->getOmFromLifeCycleArgs($args);
107
108
        $properties = $this->getLdapObjectAnnotationProperties($entity, $om);
109
        foreach ($properties as $info) {
110
            if ($info['property']->getValue($entity)) {
111
                $this->setLdapValueForProperty($info['property'], $info['annotation'], $entity);
112
            }
113
        }
114
    }
115
116
    /**
117
     * Get all the properties from the entity that have a LdapObject annotation defined.
118
     *
119
     * @param object $entity
120
     * @param ObjectManager $om
121
     * @return array
122
     */
123
    protected function getLdapObjectAnnotationProperties($entity, $om)
124
    {
125
        $properties = $om->getClassMetadata(get_class($entity))->getReflectionProperties();
126
127
        $ldapObjectProps = [];
128
        foreach ($properties as $prop) {
129
            $annotation = $this->reader->getPropertyAnnotation($prop, self::ANNOTATION);
130
            if (!empty($annotation)) {
131
                $ldapObjectProps[] = ['annotation' => $annotation, 'property' => $prop];
132
            }
133
        }
134
135
        return $ldapObjectProps;
136
    }
137
138
    /**
139
     * Based on an array of IDs for LDAP objects, set the property to either a LdapObject for LdapObjectCollection.
140
     *
141
     * @param \ReflectionProperty $property
142
     * @param LdapObjectAnnotation $annotation
143
     * @param $entity
144
     */
145
    protected function setLdapObjectForProperty(\ReflectionProperty $property, LdapObjectAnnotation $annotation, $entity)
146
    {
147
        if (empty($property->getValue($entity))) {
148
            return;
149
        }
150
        $domain = $this->ldap->getDomainContext();
151
        $switchDomain = $annotation->domain ?: null;
152
        if ($switchDomain) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $switchDomain of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
153
            $this->ldap->switchDomain($annotation->domain);
154
        }
155
156
        $results = $this->queryLdapForObjects($property, $annotation, $entity);
157
        $property->setValue($entity, $results);
158
159
        if ($switchDomain) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $switchDomain of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
160
            $this->ldap->switchDomain($domain);
161
        }
162
    }
163
164
    /**
165
     * Get the specified ID for each LDAP object and save it to an array.
166
     *
167
     * @param \ReflectionProperty $property
168
     * @param LdapObjectAnnotation $annotation
169
     * @param $entity
170
     */
171
    protected function setLdapValueForProperty(\ReflectionProperty $property, LdapObjectAnnotation $annotation, $entity)
172
    {
173
        $value = $property->getValue($entity);
174
175
        if ($value instanceof LdapObject) {
176
            $ldapValues = $value->get($annotation->id);
177
        } elseif ($value instanceof LdapObjectCollection) {
178
            $ldapValues = [];
179
            foreach ($value->toArray() as $ldapObject) {
180
                $ldapValues[] = $ldapObject->get($annotation->id);
181
            }
182
        } else {
183
            throw new \InvalidArgumentException(sprintf(
184
                'Class "%s" is not valid. Expected a LdapObject or LdapObjectCollection',
185
                get_class($value)
186
            ));
187
        }
188
189
        $property->setValue($entity, $ldapValues);
190
    }
191
192
    /**
193
     * @param LdapObjectAnnotation $annotation
194
     * @return array
195
     */
196
    protected function getLdapAttributesToSelect(LdapObjectAnnotation $annotation)
197
    {
198
        $attributes = $annotation->attributes;
199
        if (empty($attributes)) {
200
            $schemaFactory = $this->ldap->getSchemaFactory();
201
            $schema = $schemaFactory->get(
202
                $this->ldap->getConnection()->getConfig()->getSchemaName(),
203
                $annotation->type
204
            );
205
            $attributes = $schema->getAttributesToSelect();
206
        }
207
208
        if (!in_array($annotation->id, $attributes)) {
209
            $attributes[] = $annotation->id;
210
        }
211
212
        return $attributes;
213
    }
214
215
    /**
216
     * @param \ReflectionProperty $property
217
     * @param LdapObjectAnnotation $annotation
218
     * @param $entity
219
     * @return LdapObject|LdapObjectCollection|null
220
     */
221
    protected function queryLdapForObjects(\ReflectionProperty $property, LdapObjectAnnotation $annotation, $entity)
222
    {
223
        $query = $this->ldap->buildLdapQuery()
224
            ->select($this->getLdapAttributesToSelect($annotation))
225
            ->from($annotation->type);
226
        $values = $property->getValue($entity);
227
228
        // A single LdapObject type...
229
        if (is_string($values) && !empty($values)) {
230
            $query->where([$annotation->id => $values]);
231
        // A LdapObjectCollection type...
232
        } elseif (is_array($values) && !empty($values)) {
233
            foreach ($values as $value) {
234
                $query->orWhere([$annotation->id => $value]);
235
            }
236
        // A currently null/empty value?
237
        } else {
238
            return null;
239
        }
240
241
        if ($annotation->collection) {
242
            $results = $query->getLdapQuery()->getResult();
243
        } else {
244
            $results = $query->getLdapQuery()->getOneOrNullResult();
245
        }
246
247
        return $results;
248
    }
249
250
    /**
251
     * Avoid calling deprecated methods if possible.
252
     *
253
     * @param LifecycleEventArgs $args
254
     * @return object
255
     */
256 View Code Duplication
    protected function getObjectFromLifeCycleArgs(LifecycleEventArgs $args)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
257
    {
258
        $rc = new \ReflectionClass('Doctrine\Common\Persistence\Event\LifecycleEventArgs');
259
260
        if ($rc->hasMethod('getObject')) {
261
            return $args->getObject();
262
        } else {
263
            return $args->getEntity();
264
        }
265
    }
266
267
    /**
268
     * Avoid calling deprecated methods if possible.
269
     *
270
     * @param LifecycleEventArgs $args
271
     * @return \Doctrine\Common\Persistence\ObjectManager|\Doctrine\ORM\EntityManager
272
     */
273 View Code Duplication
    protected function getOmFromLifeCycleArgs(LifecycleEventArgs $args)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
274
    {
275
        $rc = new \ReflectionClass('Doctrine\Common\Persistence\Event\LifecycleEventArgs');
276
277
        if ($rc->hasMethod('getObjectManager')) {
278
            return $args->getObjectManager();
279
        } else {
280
            return $args->getEntityManager();
281
        }
282
    }
283
}
284