Completed
Push — develop ( 168e99...0122be )
by
unknown
18:37 queued 07:11
created

EventManagerAbstractFactory::getConfig()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 16
rs 9.4285
cc 2
eloc 10
nc 2
nop 2
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @license MIT
7
 * @copyright  2013 - 2016 Cross Solution <http://cross-solution.de>
8
 */
9
  
10
/** */
11
namespace Core\Factory\EventManager;
12
13
use Zend\ServiceManager\AbstractFactoryInterface;
14
use Zend\ServiceManager\ServiceLocatorInterface;
15
16
/**
17
 * ${CARET}
18
 * 
19
 * @author Mathias Gelhausen <[email protected]>
20
 * @todo write test 
21
 */
22
class EventManagerAbstractFactory implements AbstractFactoryInterface
23
{
24
    /**
25
     * Determine if we can create a service with name
26
     *
27
     * @param ServiceLocatorInterface $serviceLocator
28
     * @param                         $name
29
     * @param                         $requestedName
30
     *
31
     * @return bool
32
     */
33
    public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
34
    {
35
        return 0 === strpos(strrev($requestedName), 'stnevE/');
36
    }
37
38
    /**
39
     * Create service with name
40
     *
41
     * @param ServiceLocatorInterface $serviceLocator
42
     * @param                         $name
43
     * @param                         $requestedName
44
     *
45
     * @return mixed
46
     */
47
    public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
48
    {
49
        $config = $this->getConfig($serviceLocator, $requestedName);
50
        $events = $serviceLocator->get($config['service']);
0 ignored issues
show
Bug introduced by
It seems like $config['service'] can also be of type array; however, Zend\ServiceManager\ServiceLocatorInterface::get() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
51
52
        $events->setIdentifiers($config['identifiers']);
53
54
        if (method_exists($events, 'setEventPrototype')) {
55
            $event = $serviceLocator->has($config['event']) ? $serviceLocator->get($config['event']) : new $config['event']();
0 ignored issues
show
Bug introduced by
It seems like $config['event'] can also be of type array; however, Zend\ServiceManager\ServiceLocatorInterface::get() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
56
            $events->setEventPrototype($event);
57
        }
58
        else {
59
            $events->setEventClass($config['event']);
60
        }
61
62
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% 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...
63
         * [
64
         *  'listeners' => [
65
         *      'listenerclassorservice' => event,
66
         *      'listenerclassorservice' => [ event, event => priority ],
67
         *      'listeneraggregate',
68
         *      'listeneraggregate' => priority
69
         * ]
70
         * [
71
         *  'listeners' => [
72
         *      'event' => [
73
         *              listener,
74
         *              listener => priority,      (= [ 'priority' => priority ] )
75
         *              listener => 'methodName',  (= [ 'method' => methodName ] )
76
         *              listener => bool,          (= [ 'lazy' => bool ] )
77
         *              listener => [ 'method' => name ],
78
         *              listener => [ 'method' => name, 'priority' => priority, 'lazy' => bool ]
79
         *      ],
80
         *      ...,
81
         *      '*' => [
82
         *              aggragte,
83
         *              aggregate => $priority,
84
         *              aggregate => [ 'priority' => priority ]
85
         *     ],
86
         * ]
87
         */
88
89
        $aggregate = false;
90
91
        foreach ($config['listeners'] as $event => $listeners) {
0 ignored issues
show
Bug introduced by
The expression $config['listeners'] of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
92
            $isAggregate = '*' == $event;
93
94
            foreach ($listeners as $listener => $options) {
95
                /* Normalize options */
96
                if (is_int($listener)) {
97
                    $listener = $options;
98
                    $options = [];
99
100
                } else if (is_int($options)) {
101
                    $options = [ 'priority' => $options ];
102
103
                } else if (is_string($options)) {
104
                    $options = [ 'method' => $options ];
105
106
                } else if (!is_array($options)) {
107
                    $options = [ 'lazy' => (bool) $options ];
108
109
                }
110
111
                $options = array_merge([ 'method' => null, 'priority' => 0, 'lazy' => false ], $options);
112
113
                if ($options['lazy'] && !$isAggregate) {
114
                    $aggregate = $aggregate ?: $serviceLocator->get('Core/Listener/DeferredListenerAggregate');
115
                    $aggregate->setHook($event, $listener, $options['method'], $options['priority']);
116
117
                    continue;
118
                }
119
120 View Code Duplication
                if ($serviceLocator->has($listener)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
121
                    $listener = $serviceLocator->get($listener);
122
123
                } else if (class_exists($listener, true)) {
124
                    $listener = new $listener();
125
126
                } else {
127
                    throw new \UnexpectedValueException(sprintf(
128
                        'Class %s does not exists. Cannot create listener instance.', $listener
129
                    ));
130
                }
131
132
                if ($isAggregate) {
133
                    $listener->attach($events);
134
                } else {
135
                    $callback = $options['method'] ? [ $listener, $options['method'] ] : $listener;
136
                    $events->attach($event, $callback, $options['priority']);
137
                }
138
139
            }
140
        }
141
142
        if ($aggregate) {
143
            $aggregate->attach($events);
144
        }
145
146
        return $events;
147
    }
148
149
    protected function getConfig($services, $name)
150
    {
151
        $defaults = [
152
            'service' => 'EventManager',
153
            'identifiers' => [ $name ],
154
            'event' => '\Zend\EventManager\Event',
155
            'listeners' => [],
156
        ];
157
158
        $config = $services->get('Config');
159
        $config = isset($config['event_manager'][$name]) ? $config['event_manager'][$name] : [];
160
161
        $config = array_replace_recursive($defaults, $config);
162
163
        return $config;
164
    }
165
166
}