Completed
Push — master ( 129dcd...701d92 )
by Craig
06:47
created

DoctrineStorage   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 535
Duplicated Lines 11.59 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
dl 62
loc 535
rs 8.3206
c 0
b 0
f 0
wmc 51
lcom 1
cbo 12

27 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A setTranslator() 0 4 1
B registerSubscriber() 0 25 2
A getSubscriberByEventName() 0 8 1
B unregisterSubscriberByArea() 31 31 2
B registerProvider() 0 27 2
A getProviderByAreaAndType() 0 11 1
B unregisterProviderByArea() 31 31 2
A getSubscribersByOwner() 0 8 1
A getSubscriberAreasByOwner() 0 4 1
A getProviderAreasByOwner() 0 4 1
A getAreasByOwner() 0 18 2
A getOwnerByArea() 0 10 1
A generateRuntimeHandlers() 0 12 2
B addRuntimeHandlers() 0 45 4
A getRuntimeHandlers() 0 10 1
B bindSubscriber() 0 25 2
A unbindSubscriber() 0 18 1
A getBindings() 0 12 1
B getBindingsFor() 0 38 4
B setBindOrder() 0 29 3
A getRuntimeMetaByEventName() 0 13 3
A getBindingBetweenAreas() 0 16 1
B isAllowedBindingBetweenAreas() 0 41 4
A getBindingsBetweenOwners() 0 8 1
B registerArea() 0 24 4
A getAreaId() 0 11 2

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DoctrineStorage often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DoctrineStorage, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 * This file is part of the Zikula package.
5
 *
6
 * Copyright Zikula Foundation - http://zikula.org/
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine;
13
14
use Doctrine\ORM\EntityManager;
15
use Symfony\Component\HttpFoundation\Session\SessionInterface;
16
use Zikula\Bundle\HookBundle\Dispatcher\Exception\InvalidArgumentException;
17
use Zikula\Bundle\HookBundle\Dispatcher\StorageInterface;
18
use Zikula\Common\Translator\TranslatorInterface;
19
use Zikula\Common\Translator\TranslatorTrait;
20
21
/**
22
 * Doctrine class.
23
 */
24
class DoctrineStorage implements StorageInterface
25
{
26
    use TranslatorTrait;
27
28
    const PROVIDER = 'p';
29
    const SUBSCRIBER = 's';
30
31
    private $runtimeHandlers = [];
32
33
    /**
34
     * @var \Doctrine\ORM\EntityManager
35
     */
36
    private $em;
37
38
    /**
39
     * @var SessionInterface
40
     */
41
    private $session;
42
43
    public function __construct(EntityManager $em, SessionInterface $session, TranslatorInterface $translator)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $em. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
44
    {
45
        $this->em = $em;
46
        $this->session = $session;
47
        $this->setTranslator($translator);
48
    }
49
50
    public function setTranslator($translator)
51
    {
52
        $this->translator = $translator;
53
    }
54
55
    public function registerSubscriber($owner, $subOwner, $areaName, $areaType, $category, $eventName)
56
    {
57
        $areaId = $this->registerArea($areaName, self::SUBSCRIBER, $owner, $subOwner, $category);
58
59
        // Now we have an areaId we can register a subscriber, but first test if the subscriber is already registered.
60
        $existingSubscriber = $this->getSubscriberByEventName($eventName);
61
        if (!empty($existingSubscriber)) {
62
            $this->session->getFlashBag()->add('warning', $this->__f('The hook subscriber "%sub" could not be registered for "%own" because it is registered already.', [
63
                '%sub' => $eventName,
64
                '%own' => $owner
65
            ]));
66
67
            return;
68
        }
69
70
        $subscriber = new Entity\HookSubscriberEntity();
71
        $subscriber->setOwner($owner);
72
        $subscriber->setCategory($category);
73
        $subscriber->setEventname($eventName);
74
        $subscriber->setHooktype($areaType);
75
        $subscriber->setSareaid($areaId);
76
        $subscriber->setSubowner($subOwner);
77
        $this->em->persist($subscriber);
78
        $this->em->flush();
79
    }
80
81
    public function getSubscriberByEventName($eventName)
82
    {
83
        return $this->em->createQueryBuilder()->select('t')
84
                 ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookSubscriberEntity', 't')
85
                 ->where('t.eventname = ?1')
86
                 ->getQuery()->setParameter(1, $eventName)
87
                 ->getArrayResult();
88
    }
89
90 View Code Duplication
    public function unregisterSubscriberByArea($areaName)
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...
91
    {
92
        $areaId = $this->getAreaId($areaName);
93
94
        if (!$areaId) {
95
            return;
96
        }
97
98
        // delete subscriber entry
99
        $this->em->createQueryBuilder()
100
                 ->delete('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookSubscriberEntity', 't')
101
                 ->where('t.sareaid = ?1')
102
                 ->getQuery()->setParameter(1, $areaId)
103
                 ->execute();
104
105
        // remove bindings
106
        $this->em->createQueryBuilder()
107
                 ->delete('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookBindingEntity', 't')
108
                 ->where('t.sareaid = ?1')
109
                 ->getQuery()->setParameter(1, $areaId)
110
                 ->execute();
111
112
        // clean areas
113
        $this->em->createQueryBuilder()
114
                 ->delete('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity', 't')
115
                 ->where('t.id = ?1')
116
                 ->getQuery()->setParameter(1, $areaId)
117
                 ->execute();
118
119
        $this->generateRuntimeHandlers();
120
    }
121
122
    public function registerProvider($owner, $subOwner, $areaName, $hookType, $category, $className, $method, $serviceId = null)
123
    {
124
        $pareaId = $this->registerArea($areaName, self::PROVIDER, $owner, $subOwner, $category);
125
126
        $existingProvider = $this->getProviderByAreaAndType($pareaId, $hookType);
127
        if (!empty($existingProvider)) {
128
            $this->session->getFlashBag()->add('warning', $this->__f('The hook provider for area "%parea" of type "%type" could not be registered for "%own" because it already exists.', [
129
                '%parea' => $pareaId,
130
                '%type' => $hookType,
131
                '%own' => $owner
132
            ]));
133
134
            return;
135
        }
136
137
        $provider = new Entity\HookProviderEntity();
138
        $provider->setOwner($owner);
139
        $provider->setSubowner($subOwner);
140
        $provider->setPareaid($pareaId);
141
        $provider->setHooktype($hookType);
142
        $provider->setCategory($category);
143
        $provider->setClassname($className);
144
        $provider->setMethod($method);
145
        $provider->setServiceid($serviceId);
146
        $this->em->persist($provider);
147
        $this->em->flush();
148
    }
149
150
    public function getProviderByAreaAndType($areaId, $type)
151
    {
152
        return $this->em->createQueryBuilder()->select('t')
153
            ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookProviderEntity', 't')
154
            ->where('t.pareaid = ?1')
155
            ->andWhere('t.hooktype = ?2')
156
            ->getQuery()
157
            ->setParameter(1, $areaId)
158
            ->setParameter(2, $type)
159
            ->getArrayResult();
160
    }
161
162 View Code Duplication
    public function unregisterProviderByArea($areaName)
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...
163
    {
164
        $areaId = $this->getAreaId($areaName);
165
166
        if (!$areaId) {
167
            return;
168
        }
169
170
        // delete provider entry
171
        $this->em->createQueryBuilder()
172
                 ->delete('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookProviderEntity', 't')
173
                 ->where('t.pareaid = ?1')
174
                 ->getQuery()->setParameter(1, $areaId)
175
                 ->execute();
176
177
        // remove bindings
178
        $this->em->createQueryBuilder()
179
                 ->delete('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookBindingEntity', 't')
180
                 ->where('t.pareaid = ?1')
181
                 ->getQuery()->setParameter(1, $areaId)
182
                 ->execute();
183
184
        // clean area
185
        $this->em->createQueryBuilder()
186
                 ->delete('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity', 't')
187
                 ->where('t.id = ?1')
188
                 ->getQuery()->setParameter(1, $areaId)
189
                 ->execute();
190
191
        $this->generateRuntimeHandlers();
192
    }
193
194
    public function getSubscribersByOwner($owner)
195
    {
196
        return $this->em->createQueryBuilder()->select('t')
197
                    ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookSubscriberEntity', 't')
198
                    ->where('t.owner = ?1')
199
                    ->getQuery()->setParameter(1, $owner)
200
                    ->getArrayResult();
201
    }
202
203
    public function getSubscriberAreasByOwner($owner)
204
    {
205
        return $this->getAreasByOwner($owner, self::SUBSCRIBER);
206
    }
207
208
    public function getProviderAreasByOwner($owner)
209
    {
210
        return $this->getAreasByOwner($owner, self::PROVIDER);
211
    }
212
213
    private function getAreasByOwner($owner, $type)
214
    {
215
        $dql = "SELECT t.areaname
216
            FROM Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity t
217
            WHERE t.owner = :owner
218
            AND t.areatype = :type";
219
        $query = $this->em->createQuery($dql);
220
        $query->setParameter('owner', $owner);
221
        $query->setParameter('type', $type);
222
        $results = $query->getResult();
223
        // reformat result array to flat array
224
        $resultArray = [];
225
        foreach ($results as $k => $result) {
226
            $resultArray[$k] = $result['areaname'];
227
        }
228
229
        return $resultArray;
230
    }
231
232
    public function getOwnerByArea($areaName)
233
    {
234
        $hookarea = $this->em->createQueryBuilder()->select('t')
235
                    ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity', 't')
236
                    ->where('t.areaname = ?1')
237
                    ->getQuery()->setParameter(1, $areaName)
238
                    ->getSingleResult();
239
240
        return $hookarea->getOwner();
241
    }
242
243
    private function generateRuntimeHandlers()
244
    {
245
        // truncate runtime
246
        $this->em->createQueryBuilder()
247
             ->delete('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookRuntimeEntity')
248
             ->getQuery()
249
             ->execute();
250
251
        foreach ($this->getBindings() as $binding) {
252
            $this->addRuntimeHandlers($binding['sareaid'], $binding['pareaid']);
253
        }
254
    }
255
256
    private function addRuntimeHandlers($subscriberAreaId, $providerAreaId)
257
    {
258
        $sa = $this->em->find('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity',
259
                              $subscriberAreaId);
260
        $pa = $this->em->find('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity',
261
                              $providerAreaId);
262
263
        $subscribers = $this->em->createQueryBuilder()->select('t')
264
                            ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookSubscriberEntity', 't')
265
                            ->where('t.sareaid = ?1')
266
                            ->getQuery()->setParameter(1, $subscriberAreaId)
267
                            ->getArrayResult();
268
269
        if (!$subscribers) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $subscribers of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
270
            return false;
271
        }
272
273
        foreach ($subscribers as $subscriber) {
274
            $provider = $this->em->createQueryBuilder()->select('t')
275
                             ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookProviderEntity', 't')
276
                             ->where('t.pareaid = ?1 AND t.hooktype = ?2')
277
                             ->getQuery()->setParameters([1 => $providerAreaId, 2 => $subscriber['hooktype']])
278
                             ->getArrayResult();
279
280
            if ($provider) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $provider of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
281
                $provider = $provider[0];
282
                $binding = new Entity\HookRuntimeEntity();
283
                $binding->setSowner($sa->getOwner());
284
                $binding->setSubsowner($sa->getSubowner());
285
                $binding->setPowner($pa->getOwner());
286
                $binding->setSubpowner($pa->getSubowner());
287
                $binding->setSareaid($subscriberAreaId);
288
                $binding->setPareaid($providerAreaId);
289
                $binding->setEventname($subscriber['eventname']);
290
                $binding->setClassname($provider['classname']);
291
                $binding->setMethod($provider['method']);
292
                $binding->setServiceid($provider['serviceid']);
293
                $binding->setPriority(10);
294
                $this->em->persist($binding);
295
            }
296
        }
297
        $this->em->flush();
298
299
        return true;
300
    }
301
302
    public function getRuntimeHandlers()
303
    {
304
        $this->runtimeHandlers =
305
            $this->em->createQueryBuilder()->select('t')
306
                 ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookRuntimeEntity', 't')
307
                 ->getQuery()
308
                 ->getArrayResult();
309
310
        return $this->runtimeHandlers;
311
    }
312
313
    public function bindSubscriber($subscriberArea, $providerArea)
314
    {
315
        $sa = $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
316
                   ->findOneBy(['areaname' => $subscriberArea]);
317
        $pa = $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
318
                   ->findOneBy(['areaname' => $providerArea]);
319
320
        if ($sa->getCategory() != $pa->getCategory()) {
321
            throw new \LogicException('Cannot bind areas from different categories.');
322
        }
323
324
        $binding = new Entity\HookBindingEntity();
325
        $binding->setSowner($sa->getOwner());
326
        $binding->setSubsowner($sa->getSubowner());
327
        $binding->setPowner($pa->getOwner());
328
        $binding->setSubpowner($pa->getSubowner());
329
        $binding->setSareaid($sa->getId());
330
        $binding->setPareaid($pa->getId());
331
        $binding->setCategory($sa->getCategory());
332
        $binding->setSortorder(999);
333
        $this->em->persist($binding);
334
        $this->em->flush();
335
336
        $this->generateRuntimeHandlers();
337
    }
338
339
    public function unbindSubscriber($subscriberArea, $providerArea)
340
    {
341
        $sa = $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
342
                   ->findOneBy(['areaname' => $subscriberArea]);
343
        $pa = $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
344
                   ->findOneBy(['areaname' => $providerArea]);
345
346
        $subscriberAreaId = $sa->getId();
347
        $providerAreaId = $pa->getId();
348
349
        $this->em->createQueryBuilder()
350
                 ->delete('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookBindingEntity', 't')
351
                 ->where('t.pareaid = ?1 AND t.sareaid = ?2')
352
                 ->getQuery()->setParameters([1 => $providerAreaId, 2 => $subscriberAreaId])
353
                 ->execute();
354
355
        $this->generateRuntimeHandlers();
356
    }
357
358
    private function getBindings()
359
    {
360
        $order = new \Doctrine\ORM\Query\Expr\OrderBy();
361
        $order->add('t.sareaid', 'ASC');
362
        $order->add('t.sortorder', 'ASC');
363
364
        return $this->em->createQueryBuilder()->select('t')
365
                 ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookBindingEntity', 't')
366
                 ->orderBy($order)
367
                 ->getQuery()
368
                 ->getArrayResult();
369
    }
370
371
    public function getBindingsFor($areaName)
372
    {
373
        $area = $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
374
                     ->findOneBy(['areaname' => $areaName]);
375
376
        if (!$area) {
377
            return [];
378
        }
379
380
        if ($area->getAreatype() == self::PROVIDER) {
381
            $areaIdField = 'pareaid';
382
        } else { // $area->getAreatype() == self::SUBSCRIBER
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
383
            $areaIdField = 'sareaid';
384
        }
385
386
        $order = new \Doctrine\ORM\Query\Expr\OrderBy();
387
        $order->add('t.sortorder', 'ASC');
388
        $order->add('t.sareaid', 'ASC');
389
        $results = $this->em->createQueryBuilder()->select('t')
390
                         ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookBindingEntity', 't')
391
                         ->where("t.$areaIdField = ?1")
392
                         ->orderBy($order)
393
                         ->getQuery()->setParameter(1, $area->getId())
394
                         ->getArrayResult();
395
396
        // this could be an area where related entities would help CAH - 23 Oct 2013
397
        $areas = [];
398
        foreach ($results as $result) {
399
            $area = $this->em->find('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity',
400
                                    $result['pareaid']);
401
            $areas[] = [
402
                'areaname' => $area->getAreaname(),
403
                'category' => $area->getCategory()
404
            ];
405
        }
406
407
        return $areas;
408
    }
409
410
    public function setBindOrder($subscriberAreaName, array $providerAreaNames)
411
    {
412
        $sareaId = $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
413
                        ->findOneBy(['areaname' => $subscriberAreaName])
414
                        ->getId();
415
416
        // convert provider areanames to ids
417
        $providerAreaIds = [];
418
        foreach ($providerAreaNames as $name) {
419
            $providerAreaIds[] =
420
                $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
421
                     ->findOneBy(['areaname' => $name])
422
                     ->getId();
423
        }
424
425
        // sort bindings in order of appearance from $providerAreaIds
426
        $counter = 1;
427
        foreach ($providerAreaIds as $id) {
428
            $this->em->createQueryBuilder()
429
                 ->update('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookBindingEntity', 't')
430
                 ->set('t.sortorder', $counter)
431
                 ->where('t.sareaid = ?1 AND t.pareaid = ?2')
432
                 ->getQuery()->setParameters([1 => $sareaId, 2 => $id])
433
                ->execute();
434
            $counter++;
435
        }
436
437
        $this->generateRuntimeHandlers();
438
    }
439
440
    public function getRuntimeMetaByEventName($eventName)
441
    {
442
        foreach ($this->runtimeHandlers as $handler) {
443
            if ($handler['eventname'] == $eventName) {
444
                return [
445
                    'areaid' => $handler['sareaid'],
446
                    'owner' => $handler['sowner']
447
                ];
448
            }
449
        }
450
451
        return false;
452
    }
453
454
    public function getBindingBetweenAreas($subscriberArea, $providerArea)
455
    {
456
        $sareaId = $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
457
                        ->findOneBy(['areaname' => $subscriberArea])
458
                        ->getId();
459
460
        $pareaId = $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
461
                        ->findOneBy(['areaname' => $providerArea])
462
                        ->getId();
463
464
        return $this->em->createQueryBuilder()->select('t')
465
                    ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookBindingEntity', 't')
466
                    ->where('t.sareaid = ?1 AND t.pareaid = ?2')
467
                    ->getQuery()->setParameters([1 => $sareaId, 2 => $pareaId])
468
                    ->getOneOrNullResult();
469
    }
470
471
    public function isAllowedBindingBetweenAreas($subscriberArea, $providerArea)
472
    {
473
        $sareaId = $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
474
                        ->findOneBy(['areaname' => $subscriberArea])
475
                        ->getId();
476
477
        $subscribers =
478
            $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookSubscriberEntity')
479
                 ->findBy(['sareaid' => $sareaId]);
480
481
        if (!$subscribers) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $subscribers of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
482
            return false;
483
        }
484
485
        $allow = false;
486
        /** @var $subscriber \Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookSubscriberEntity */
487
        foreach ($subscribers as $subscriber) {
488
            $pareaId =
489
                $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
490
                     ->findOneBy(['areaname' => $providerArea])
491
                     ->getId();
492
493
            $hookprovider =
494
                $this->em->createQueryBuilder()->select('t')
495
                    ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookProviderEntity', 't')
496
                    ->where('t.pareaid = ?1 AND t.hooktype = ?2 AND t.category = ?3')
497
                    ->getQuery()->setParameters([
498
                        1 => $pareaId,
499
                        2 => $subscriber->getHooktype(),
500
                        3 => $subscriber->getCategory()
501
                    ])
502
                     ->getArrayResult();
503
504
            if ($hookprovider) {
505
                $allow = true;
506
                break;
507
            }
508
        }
509
510
        return $allow;
511
    }
512
513
    public function getBindingsBetweenOwners($subscriberOwner, $providerOwner)
514
    {
515
        return $this->em->createQueryBuilder()->select('t')
516
                    ->from('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookBindingEntity', 't')
517
                    ->where('t.sowner = ?1 AND t.powner = ?2')
518
                    ->getQuery()->setParameters([1 => $subscriberOwner, 2 => $providerOwner])
519
                    ->getArrayResult();
520
    }
521
522
    private function registerArea($areaName, $areaType, $owner, $subOwner, $category)
523
    {
524
        if ($areaType !== self::PROVIDER && $areaType !== self::SUBSCRIBER) {
525
            throw new InvalidArgumentException('$areaType must be "p" or "s"');
526
        }
527
528
        // if there is an area registered, if not, create it.
529
        $areaId = $this->getAreaId($areaName);
530
        if (!$areaId) {
531
            // There is no area id so create one.
532
            $subscriberArea = new Entity\HookAreaEntity();
533
            $subscriberArea->setAreaname($areaName);
534
            $subscriberArea->setOwner($owner);
535
            $subscriberArea->setSubowner($subOwner);
536
            $subscriberArea->setAreatype($areaType);
537
            $subscriberArea->setCategory($category);
538
            $this->em->persist($subscriberArea);
539
            $this->em->flush();
540
541
            $areaId = $subscriberArea->getId();
542
        }
543
544
        return $areaId;
545
    }
546
547
    public function getAreaId($areaName)
548
    {
549
        $hookArea = $this->em->getRepository('Zikula\Bundle\HookBundle\Dispatcher\Storage\Doctrine\Entity\HookAreaEntity')
550
                   ->findOneBy(['areaname' => $areaName]);
551
552
        if (!$hookArea) {
553
            return false;
554
        }
555
556
        return $hookArea->getId();
557
    }
558
}
559