Completed
Push — wip/steps ( 593c83...eae10b )
by Romain
05:16 queued 01:49
created

AbstractMiddleware::getScopes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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\Item;
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\Definition\Step\Step\Step;
23
use Romm\Formz\Form\Definition\Middleware\MiddlewareScopes;
24
use Romm\Formz\Form\FormObject\FormObject;
25
use Romm\Formz\Middleware\Item\Step\Service\StepMiddlewareService;
26
use Romm\Formz\Middleware\MiddlewareInterface;
27
use Romm\Formz\Middleware\Option\AbstractOptionDefinition;
28
use Romm\Formz\Middleware\Option\OptionInterface;
29
use Romm\Formz\Middleware\Processor\MiddlewareProcessor;
30
use Romm\Formz\Middleware\Request\Forward;
31
use Romm\Formz\Middleware\Request\Redirect;
32
use Romm\Formz\Middleware\Signal\After;
33
use Romm\Formz\Middleware\Signal\Before;
34
use Romm\Formz\Middleware\Signal\MiddlewareSignal;
35
use Romm\Formz\Middleware\Signal\SendsMiddlewareSignal;
36
use Romm\Formz\Middleware\Signal\SignalObject;
37
use TYPO3\CMS\Extbase\Mvc\Controller\Arguments;
38
use TYPO3\CMS\Extbase\Mvc\Web\Request;
39
40
/**
41
 * Abstract class that must be extended by middlewares.
42
 *
43
 * Child middleware must implement their 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
     * child classes to be mapped to another option definition.
55
     *
56
     * @var \Romm\Formz\Middleware\Option\DefaultOptionDefinition
57
     */
58
    protected $options;
59
60
    /**
61
     * @var \Romm\Formz\Form\Definition\Middleware\MiddlewareScopes
62
     */
63
    protected $scopes = [];
64
65
    /**
66
     * Can be overridden in child class with custom priority value.
67
     *
68
     * The higher the priority is, the earlier the middleware is called.
69
     *
70
     * Note that you can also override the method `getPriority()` for advanced
71
     * priority calculation.
72
     *
73
     * @var int
74
     */
75
    protected $priority = 0;
76
77
    /**
78
     * @param OptionInterface  $options
79
     * @param MiddlewareScopes $scopes
80
     */
81
    final public function __construct(OptionInterface $options, MiddlewareScopes $scopes)
82
    {
83
        $this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
$options is of type object<Romm\Formz\Middle...Option\OptionInterface>, 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...
84
        $this->scopes = $scopes;
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\SendsMiddlewareSignal::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\SendsMiddlewareSignal::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 AbstractOptionDefinition
129
     */
130
    public function getOptions()
131
    {
132
        return $this->options;
133
    }
134
135
    /**
136
     * @todo
137
     */
138
    protected function redirectToNextStep()
139
    {
140
        $formObject = $this->getFormObject();
141
142
        if ($formObject->hasForm()
143
            && $formObject->isPersistent()
144
        ) {
145
            $formObject->getFormMetadata()->persist();
146
        }
147
148
        $service = StepMiddlewareService::get();
149
        $nextStep = $service->getNextStep($this->getCurrentStep());
150
151
        if ($nextStep) {
152
            $this->beforeSignal()->dispatch();
153
154
            $service->moveForwardToStep($nextStep, $this->redirect());
155
        }
156
    }
157
158
    /**
159
     * @return MiddlewareScopes
160
     */
161
    public function getScopes()
162
    {
163
        return $this->scopes;
164
    }
165
166
    /**
167
     * Returns a new forward dispatcher, on which you can add options by calling
168
     * its fluent methods.
169
     *
170
     * You must call the method `dispatch()` to actually dispatch the forward
171
     * signal.
172
     *
173
     * @return Forward
174
     */
175
    final protected function forward()
176
    {
177
        return new Forward($this->getRequest(), $this->getFormObject());
178
    }
179
180
    /**
181
     * Returns a new redirect dispatcher, on which you can add options by
182
     * calling its fluent methods.
183
     *
184
     * You must call the method `dispatch()` to actually dispatch the redirect
185
     * signal.
186
     *
187
     * @return Redirect
188
     */
189
    final protected function redirect()
190
    {
191
        return new Redirect($this->getRequest(), $this->getFormObject());
192
    }
193
194
    /**
195
     * @return FormObject
196
     */
197
    final protected function getFormObject()
198
    {
199
        return $this->processor->getFormObject();
200
    }
201
202
    /**
203
     * @return Request
204
     */
205
    final protected function getRequest()
206
    {
207
        return $this->processor->getRequest();
208
    }
209
210
    /**
211
     * @return Arguments
212
     */
213
    final protected function getRequestArguments()
214
    {
215
        return $this->processor->getRequestArguments();
216
    }
217
218
    /**
219
     * @return array
220
     */
221
    final protected function getSettings()
222
    {
223
        return $this->processor->getSettings();
224
    }
225
226
    /**
227
     * @return Step|null
228
     */
229
    final protected function getCurrentStep()
230
    {
231
        return $this->getFormObject()->getCurrentStep();
232
    }
233
234
    /**
235
     * @return int
236
     */
237
    public function getPriority()
238
    {
239
        return (int)$this->priority;
240
    }
241
242
    /**
243
     * @param MiddlewareProcessor $middlewareProcessor
244
     */
245
    final public function bindMiddlewareProcessor(MiddlewareProcessor $middlewareProcessor)
246
    {
247
        $this->processor = $middlewareProcessor;
248
    }
249
250
    /**
251
     * Returns the name of the signal on which this middleware is bound.
252
     *
253
     * @return string
254
     * @throws SignalNotFoundException
255
     */
256
    final public function getBoundSignalName()
257
    {
258
        $interfaces = class_implements($this);
259
260
        foreach ($interfaces as $interface) {
261
            if (in_array(MiddlewareSignal::class, class_implements($interface))) {
262
                return $interface;
263
            }
264
        }
265
266
        throw SignalNotFoundException::signalNotFoundInMiddleware($this);
267
    }
268
269
    /**
270
     * Will inject empty options if no option has been defined at all.
271
     *
272
     * @param DataPreProcessor $processor
273
     */
274
    public static function dataPreProcessor(DataPreProcessor $processor)
275
    {
276
        $data = $processor->getData();
277
278
        if (false === isset($data['options'])) {
279
            $data['options'] = [];
280
        }
281
282
        if (false === isset($data['scopes'])) {
283
            $data['scopes'] = [];
284
        }
285
286
        $processor->setData($data);
287
    }
288
289
    /**
290
     * @param string $signal
291
     * @param string $type
292
     * @return SignalObject
293
     * @throws InvalidArgumentValueException
294
     * @throws InvalidEntryException
295
     * @throws MissingArgumentException
296
     */
297
    private function getSignalObject($signal, $type)
298
    {
299
        if (false === $this instanceof SendsMiddlewareSignal) {
300
            throw InvalidEntryException::middlewareNotSendingSignals($this);
301
        }
302
303
        /** @var SendsMiddlewareSignal $this */
304
        if (null === $signal) {
305
            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\Item\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Item\AbstractMiddleware: Romm\Formz\Middleware\It...our\BehaviourMiddleware, Romm\Formz\Middleware\It...FormInjectionMiddleware, Romm\Formz\Middleware\It...ormValidationMiddleware, Romm\Formz\Middleware\It...tenceFetchingMiddleware, Romm\Formz\Middleware\It...epDispatchingMiddleware. 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...
306
                throw MissingArgumentException::signalNameArgumentMissing($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Romm\Formz\Middlewa...tem\AbstractMiddleware>, but the function expects a object<Romm\Formz\Middle...\SendsMiddlewareSignal>.

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...
307
            }
308
309
            $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\Item\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Item\AbstractMiddleware: Romm\Formz\Middleware\It...our\BehaviourMiddleware, Romm\Formz\Middleware\It...FormInjectionMiddleware, Romm\Formz\Middleware\It...ormValidationMiddleware, Romm\Formz\Middleware\It...tenceFetchingMiddleware, Romm\Formz\Middleware\It...epDispatchingMiddleware. 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...
310
        }
311
312
        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\Item\AbstractMiddleware as the method getAllowedSignals() does only exist in the following sub-classes of Romm\Formz\Middleware\Item\AbstractMiddleware: Romm\Formz\Middleware\It...our\BehaviourMiddleware, Romm\Formz\Middleware\It...FormInjectionMiddleware, Romm\Formz\Middleware\It...ormValidationMiddleware, Romm\Formz\Middleware\It...tenceFetchingMiddleware, Romm\Formz\Middleware\It...epDispatchingMiddleware. 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...
313
            throw InvalidArgumentValueException::signalNotAllowed($this);
0 ignored issues
show
Documentation introduced by
$this is of type this<Romm\Formz\Middlewa...tem\AbstractMiddleware>, but the function expects a object<Romm\Formz\Middle...\SendsMiddlewareSignal>.

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...
314
        }
315
316
        return new SignalObject($this->processor, $signal, $type);
317
    }
318
319
    /**
320
     * @return array
321
     */
322
    public function __sleep()
323
    {
324
        return ['options', 'scopes'];
325
    }
326
}
327