Completed
Push — feature/middleware ( bf156f...5ee07f )
by Romain
02:27
created

AbstractMiddleware::getSignalObject()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 24
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
cc 5
eloc 11
nc 6
nop 2
1
<?php
2
/*
3
 * 2017 Romain CANON <[email protected]>
4
 *
5
 * This file is part of the TYPO3 FormZ project.
6
 * It is free software; you can redistribute it and/or modify it
7
 * under the terms of the GNU General Public License, either
8
 * version 3 of the License, or any later version.
9
 *
10
 * For the full copyright and license information, see:
11
 * http://www.gnu.org/licenses/gpl-3.0.html
12
 */
13
14
namespace Romm\Formz\Middleware\Application;
15
16
use Romm\ConfigurationObject\Service\Items\DataPreProcessor\DataPreProcessor;
17
use Romm\ConfigurationObject\Service\Items\DataPreProcessor\DataPreProcessorInterface;
18
use Romm\Formz\Exceptions\InvalidArgumentValueException;
19
use Romm\Formz\Exceptions\InvalidEntryException;
20
use Romm\Formz\Exceptions\MissingArgumentException;
21
use Romm\Formz\Exceptions\SignalNotFoundException;
22
use Romm\Formz\Form\FormObject\FormObject;
23
use Romm\Formz\Middleware\MiddlewareInterface;
24
use Romm\Formz\Middleware\MiddlewareFactory;
25
use Romm\Formz\Middleware\Option\OptionDefinitionInterface;
26
use Romm\Formz\Middleware\Processor\MiddlewareProcessor;
27
use Romm\Formz\Middleware\Request\Forward;
28
use Romm\Formz\Middleware\Request\Redirect;
29
use Romm\Formz\Middleware\Signal\After;
30
use Romm\Formz\Middleware\Signal\Before;
31
use Romm\Formz\Middleware\Signal\Element\MiddlewareSignalInterface;
32
use Romm\Formz\Middleware\Signal\SendsSignal;
33
use Romm\Formz\Middleware\Signal\Element\SignalObject;
34
use TYPO3\CMS\Core\Utility\GeneralUtility;
35
use TYPO3\CMS\Extbase\Mvc\Controller\Arguments;
36
use TYPO3\CMS\Extbase\Mvc\Web\Request;
37
use TYPO3\CMS\Extbase\Reflection\ReflectionService;
38
39
/**
40
 * Default abstraction layout that can be extended by middlewares. It contains
41
 * basic implementation needed by a middleware to work properly.
42
 *
43
 * The middleware class must still implement its own signals.
44
 */
45
abstract class AbstractMiddleware implements MiddlewareInterface, DataPreProcessorInterface
46
{
47
    /**
48
     * @var MiddlewareProcessor
49
     */
50
    private $processor;
51
52
    /**
53
     * This is the default option class, this property can be overridden in
54
     * children classes to be mapped to another option definition.
55
     *
56
     * Please note that the full class name of the option must be written.
57
     *
58
     * @var \Romm\Formz\Middleware\Option\DefaultOptionDefinition
59
     */
60
    protected $options;
61
62
    /**
63
     * Can be overridden in child class with custom priority value.
64
     *
65
     * The higher the priority is, the earlier the middleware is called.
66
     *
67
     * Note that you can also override the method `getPriority()` for advanced
68
     * priority calculation.
69
     *
70
     * @var int
71
     */
72
    protected $priority = 0;
73
74
    /**
75
     * @var ReflectionService
76
     */
77
    protected $reflectionService;
78
79
    /**
80
     * @param OptionDefinitionInterface $options
81
     */
82
    final public function __construct(OptionDefinitionInterface $options)
83
    {
84
        $this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
$options is of type object<Romm\Formz\Middle...ionDefinitionInterface>, but the property $options was declared to be of type object<Romm\Formz\Middle...efaultOptionDefinition>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
85
    }
86
87
    /**
88
     * Abstraction for processing the middleware initialization.
89
     *
90
     * For own initialization, @see initializeMiddleware()
91
     */
92
    final public function initialize()
93
    {
94
        $this->initializeMiddleware();
95
    }
96
97
    /**
98
     * You can override this method in your child class to initialize your
99
     * middleware correctly.
100
     */
101
    protected function initializeMiddleware()
102
    {
103
    }
104
105
    /**
106
     * @see \Romm\Formz\Middleware\Signal\SendsSignal::beforeSignal()
107
     *
108
     * @param string $signal
109
     * @return SignalObject
110
     */
111
    final public function beforeSignal($signal = null)
112
    {
113
        return $this->getSignalObject($signal, Before::class);
114
    }
115
116
    /**
117
     * @see \Romm\Formz\Middleware\Signal\SendsSignal::afterSignal()
118
     *
119
     * @param string $signal
120
     * @return SignalObject
121
     */
122
    final public function afterSignal($signal = null)
123
    {
124
        return $this->getSignalObject($signal, After::class);
125
    }
126
127
    /**
128
     * @return OptionDefinitionInterface
129
     */
130
    public function getOptions()
131
    {
132
        return $this->options;
133
    }
134
135
    /**
136
     * @return string
137
     */
138
    public static function getOptionsClassName()
139
    {
140
        return MiddlewareFactory::get()->getOptionsClassNameFromProperty(self::class);
0 ignored issues
show
Bug introduced by
It seems like getOptionsClassNameFromProperty() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
141
    }
142
143
    /**
144
     * Returns a new forward dispatcher, on which you can add options by calling
145
     * its fluent methods.
146
     *
147
     * You must call the method `dispatch()` to actually dispatch the forward
148
     * signal.
149
     *
150
     * @return Forward
151
     */
152
    final protected function forward()
153
    {
154
        return new Forward($this->getRequest());
155
    }
156
157
    /**
158
     * Returns a new redirect dispatcher, on which you can add options by
159
     * calling its fluent methods.
160
     *
161
     * You must call the method `dispatch()` to actually dispatch the redirect
162
     * signal.
163
     *
164
     * @return Redirect
165
     */
166
    final protected function redirect()
167
    {
168
        return new Redirect($this->getRequest());
169
    }
170
171
    /**
172
     * @return FormObject
173
     */
174
    final protected function getFormObject()
175
    {
176
        return $this->processor->getFormObject();
177
    }
178
179
    /**
180
     * @return Request
181
     */
182
    final protected function getRequest()
183
    {
184
        return $this->processor->getRequest();
185
    }
186
187
    /**
188
     * @return Arguments
189
     */
190
    final protected function getRequestArguments()
191
    {
192
        return $this->processor->getRequestArguments();
193
    }
194
195
    /**
196
     * @return int
197
     */
198
    public function getPriority()
199
    {
200
        return (int)$this->priority;
201
    }
202
203
    /**
204
     * @param MiddlewareProcessor $middlewareProcessor
205
     */
206
    final public function bindMiddlewareProcessor(MiddlewareProcessor $middlewareProcessor)
207
    {
208
        $this->processor = $middlewareProcessor;
209
    }
210
211
    /**
212
     * Returns the name of the signal on which this middleware is bound.
213
     *
214
     * @return string
215
     * @throws SignalNotFoundException
216
     */
217
    final public function getBoundSignalName()
218
    {
219
        $interfaces = class_implements($this);
220
221
        foreach ($interfaces as $interface) {
222
            if (in_array(MiddlewareSignalInterface::class, class_implements($interface))) {
223
                return $interface;
224
            }
225
        }
226
227
        throw SignalNotFoundException::signalNotFoundInMiddleware($this);
228
    }
229
230
    /**
231
     * Will inject empty options if no option has been defined at all.
232
     *
233
     * @param DataPreProcessor $processor
234
     */
235
    public static function dataPreProcessor(DataPreProcessor $processor)
236
    {
237
        $data = $processor->getData();
238
239
        if (false === isset($data['options'])) {
240
            $data['options'] = [];
241
        }
242
243
        $processor->setData($data);
244
    }
245
246
    /**
247
     * Returns a signal object, that will be used to dispatch a signal coming
248
     * from this middleware.
249
     *
250
     * @param string $signal
251
     * @param string $type
252
     * @return SignalObject
253
     * @throws InvalidArgumentValueException
254
     * @throws InvalidEntryException
255
     * @throws MissingArgumentException
256
     */
257
    private function getSignalObject($signal, $type)
258
    {
259
        if (false === $this instanceof SendsSignal) {
260
            throw InvalidEntryException::middlewareNotSendingSignals($this);
261
        }
262
263
        /** @var SendsSignal $this */
264
        if (null === $signal) {
265
            if (count($this->getAllowedSignals()) > 1) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Romm\Formz\Middleware\Ap...tion\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Ap...tion\AbstractMiddleware: Romm\Formz\Domain\Middle...FormInjectionMiddleware, Romm\Formz\Domain\Middle...ormValidationMiddleware. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
266
                throw MissingArgumentException::signalNameArgumentMissing($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Romm\Formz\Middlewa...ion\AbstractMiddleware>, but the function expects a object<Romm\Formz\Middleware\Signal\SendsSignal>.

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...
267
            }
268
269
            $signal = reset($this->getAllowedSignals());
0 ignored issues
show
Bug introduced by
$this->getAllowedSignals() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Romm\Formz\Middleware\Ap...tion\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Ap...tion\AbstractMiddleware: Romm\Formz\Domain\Middle...FormInjectionMiddleware, Romm\Formz\Domain\Middle...ormValidationMiddleware. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
270
        }
271
272
        if (false === in_array($signal, $this->getAllowedSignals())) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Romm\Formz\Middleware\Ap...tion\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Ap...tion\AbstractMiddleware: Romm\Formz\Domain\Middle...FormInjectionMiddleware, Romm\Formz\Domain\Middle...ormValidationMiddleware. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
273
            throw InvalidArgumentValueException::signalNotAllowed($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Romm\Formz\Middlewa...ion\AbstractMiddleware>, but the function expects a object<Romm\Formz\Middleware\Signal\SendsSignal>.

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...
274
        }
275
276
        /** @var SignalObject $signalObject */
277
        $signalObject = GeneralUtility::makeInstance(SignalObject::class, $this->processor, $signal, $type);
278
279
        return $signalObject;
280
    }
281
282
    /**
283
     * @return array
284
     */
285
    public function __sleep()
286
    {
287
        return ['options'];
288
    }
289
290
    /**
291
     * @param ReflectionService $reflectionService
292
     */
293
    public function injectReflectionService(ReflectionService $reflectionService)
294
    {
295
        $this->reflectionService = $reflectionService;
296
    }
297
}
298