Completed
Push — develop ( a6f952...c1b7f1 )
by
unknown
07:45
created

Proxy::plugin()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 3
nop 2
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @license MIT
7
 * @copyright  2013 - 2017 Cross Solution <http://cross-solution.de>
8
 */
9
  
10
/** */
11
namespace Core\View\Helper {
12
13
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
14
use Zend\ServiceManager\Exception\ServiceNotFoundException;
15
use Zend\View\Helper\AbstractHelper;
16
17
/**
18
 * View helper to safely use module specific view helpers in other modules.
19
 *
20
 * In most scenarios, to make something failsafe, it takes a lot of (redundant) code.
21
 * With this proxy helper, this can be simplified by just adding a few characters.
22
 *
23
 * <pre>
24
 *
25
 *      //
26
 *      // ORIGINAL
27
 *      //
28
 *      <?=$this->helper()->someOutput()?>
29
 *
30
 *      //
31
 *      // Failsafe code
32
 *      //
33
 *      <? if ($this->getHelperPluginManager()->has('plugin')):
34
 *              $plugin = $this->getHelperPluginManager()->get('helper');
35
 *
36
 *              // do something with the plugin, i.E. call some method
37
 *              echo $plugin->someOutput();
38
 *         else:
39
 *              // helper does not exist.
40
 *              // do something to hanlde this case.
41
 *              echo '';
42
 *         endif;
43
 *      ?>
44
 *
45
 *      //
46
 *      // Failsafe with Proxy:
47
 *      //
48
 *      <?=$this->proxy('helper')->someOutput()?>
49
 *
50
 *      // If 'helper' does not exist, a ProxyNoopHelper is returned, which
51
 *      // simply returns NULL on any method call and whose string representation is
52
 *      // an empty string.
53
 * <pre>
54
 *
55
 * Advanced usage:
56
 *
57
 * - Load a helper without risking an exception:
58
 *   This will return FALSE, if the helper does not exist.
59
 *   <pre><? $helper = $this->proxy()->plugin('HelperServiceName', [options])?></pre>
60
 *
61
 * - Call an invokable helper and expect an array returned.
62
 *   This will return an empty array, if the helper does not exist.
63
 *   <pre><? $array = $this->proxy('helper', Proxy::EXPECT_ARRAY)?></pre>
64
 *
65
 * - Expect other return types:
66
 *   <pre>
67
 *      // Object (which is default)
68
 *      $helper = $this->proxy('helper', Proxy::EXPECT_OBJECT);
69
 *
70
 *      // Iterator (returns an IteratorAggregate which returns an empty ArrayIterator.
71
 *      $helper = $this->proxy('helper', Proxy::EXPECT_ITERATOR);
72
 *
73
 *      // Skalar values: Simply specify the expected result, which will be returned,
74
 *      // if the helper does not exist.
75
 *      $value = $this->proxy('helper', ''); // return empty string.
76
 *      $value = $this->proxy('helper', false) // return FALSE
77
 *   </pre>
78
 *
79
 * - Directly calls an invokable helper with Arguments
80
 *   <pre>
81
 *      <?=$this->proxy('invokableHelper', ['arg1', 'arg2'], false)?>
82
 *   </pre>
83
 *
84
 * @author Mathias Gelhausen <[email protected]>
85
 * @since 0.29
86
 */
87
class Proxy extends AbstractHelper
88
{
89
    /**#@+
90
     * Special expected result types.
91
     * @var string
92
     */
93
    const EXPECT_ARRAY  = '__ARRAY__';
94
    const EXPECT_ITARATOR = '__ITERATOR__';
95
    const EXPECT_OBJECT = '__OBJECT__';
96
97
    /**#@-*/
98
99
    /**
100
     * Loads and possiblity executes a view helper.
101
     *
102
     * @param null|string   $plugin
103
     * @param array|string  $args
104
     * @param mixed         $expect
105
     *
106
     * @return mixed|self|ProxyNoopHelper|ProxyNoopIterator
107
     */
108
    public function __invoke($plugin = null, $args = array(), $expect = self::EXPECT_OBJECT)
109
    {
110
        if (null === $plugin) {
111
            return $this;
112
        }
113
114
        if (!is_array($args)) {
115
            $expect = $args;
116
            $args = [];
117
        }
118
119
        $plugin = $this->plugin($plugin);
120
121
        if ($plugin) {
122
            return is_callable($plugin)
123
            ? call_user_func_array($plugin, $args)
124
            : $plugin;
125
        }
126
127
        if (self::EXPECT_OBJECT == $expect) {
128
            return new Proxy\NoopHelper();
129
        }
130
131
        if (self::EXPECT_ITARATOR == $expect) {
132
            return new Proxy\NoopIterator();
133
        }
134
135
        if (self::EXPECT_ARRAY == $expect) {
136
            return [];
137
        }
138
139
        return $expect;
140
    }
141
142
    /**
143
     * Loads a plugin from the plugin helper manager.
144
     *
145
     * Returns false, if either the helper plugin manager cannot be
146
     * retrieved from the renderer or the requested plugin does not exist.
147
     *
148
     * @param string $plugin
149
     * @param true|array  $options if true, only return if plugin exists or not.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $options not be true|array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
150
     *
151
     * @return bool|object
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|object|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
152
     */
153
    public function plugin($plugin, $options = null)
154
    {
155
        $renderer = $this->getView();
156
157
        if (!method_exists($renderer, 'getHelperPluginManager')) {
158
            return false;
159
        }
160
161
        /* @var \Zend\View\HelperPluginManager $manager */
162
        $manager   = $renderer->getHelperPluginManager();
163
        $hasPlugin = $manager->has($plugin);
164
165
        if (!$hasPlugin || true === $options) {
166
            return $hasPlugin;
167
        }
168
169
        return $manager->get($plugin, $options);
0 ignored issues
show
Bug introduced by
It seems like $options defined by parameter $options on line 153 can also be of type null; however, Zend\ServiceManager\AbstractPluginManager::get() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
170
    }
171
172
    /**
173
     * Does a plugin exists?
174
     *
175
     * @param string $plugin
176
     *
177
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|object|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
178
     */
179
    public function exists($plugin)
180
    {
181
        return $this->plugin($plugin, true);
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a object<Core\View\Helper\true>|array|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
182
    }
183
}
184
185
} // end namespace
186
187
namespace Core\View\Helper\Proxy {
188
189
/**
190
 * NoopHelper
191
 *
192
 * View helper which does nothing but returns null on any method call, and which
193
 * represents as empty string.
194
 *
195
 * @author Mathias Gelhausen <[email protected]>
196
 * @since 0.29
197
 */
198
class NoopHelper
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
199
{
200
    public function __call($method, $args)
201
    {
202
        return null;
203
    }
204
205
    public function __get($name)
206
    {
207
        return null;
208
    }
209
210
    public function __set($name, $value)
211
    {
212
213
    }
214
215
    public function __isset($name)
0 ignored issues
show
Coding Style introduced by
function __isset() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
216
    {
217
        return false;
218
    }
219
220
    public function __toString()
221
    {
222
        return '';
223
    }
224
}
225
226
/**
227
 * NoopIterator
228
 *
229
 * View helper which returns an empty ArrayIterator when used as Iterator.
230
 *
231
 * @author Mathias Gelhausen <[email protected]>
232
 * @since 0.29
233
 */
234
class NoopIterator extends NoopHelper implements \IteratorAggregate
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
235
{
236
    public function getIterator()
237
    {
238
        return new \ArrayIterator([]);
239
    }
240
}
241
242
} // end namespace