Completed
Pull Request — master (#138)
by Paul
03:43 queued 19s
created

App::dispatch()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 36
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 11
Bugs 1 Features 0
Metric Value
c 11
b 1
f 0
dl 0
loc 36
rs 8.439
cc 5
eloc 20
nc 8
nop 2
1
<?php
2
/**
3
 * This file is part of the PPI Framework.
4
 *
5
 * @copyright  Copyright (c) 2011-2015 Paul Dragoonis <[email protected]>
6
 * @license    http://opensource.org/licenses/mit-license.php MIT
7
 *
8
 * @link       http://www.ppi.io
9
 */
10
11
namespace PPI\Framework;
12
13
use PPI\Framework\Config\ConfigManager;
14
use PPI\Framework\Debug\ExceptionHandler;
15
use PPI\Framework\Http\Response;
16
use PPI\Framework\ServiceManager\ServiceManagerBuilder;
17
use Psr\Http\Message\RequestInterface;
18
use Psr\Http\Message\ResponseInterface;
19
use Symfony\Component\ClassLoader\DebugClassLoader;
20
use Symfony\Component\Debug\ErrorHandler;
21
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
22
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
23
use PPI\Framework\Http\Request as HttpRequest;
24
use PPI\Framework\Http\Response as HttpResponse;
25
26
/**
27
 * The PPI App bootstrap class.
28
 *
29
 * This class sets various app settings, and allows you to override classes used in the bootup process.
30
 *
31
 * @author     Paul Dragoonis <[email protected]>
32
 * @author     Vítor Brandão <[email protected]>
33
 */
34
class App implements AppInterface
35
{
36
    /**
37
     * Version string.
38
     *
39
     * @var string
40
     */
41
    const VERSION = '2.1.0-DEV';
42
43
    /**
44
     * @var boolean
45
     */
46
    protected $booted = false;
47
48
    /**
49
     * @var boolean
50
     */
51
    protected $debug;
52
53
    /**
54
     * Application environment: "dev|development" vs "prod|production".
55
     *
56
     * @var string
57
     */
58
    protected $environment;
59
60
    /**
61
     * @var \Psr\Log\LoggerInterface
62
     */
63
    protected $logger;
64
65
    /**
66
     * Unix timestamp with microseconds.
67
     *
68
     * @var float
69
     */
70
    protected $startTime;
71
72
    /**
73
     * Configuration loader.
74
     *
75
     * @var \PPI\Framework\Config\ConfigManager
76
     */
77
    protected $configManager;
78
79
    /**
80
     * The Module Manager.
81
     *
82
     * @var \Zend\ModuleManager\ModuleManager
83
     */
84
    protected $moduleManager;
85
86
    /**
87
     * @param integer $errorReportingLevel The level of error reporting you want
88
     */
89
    protected $errorReportingLevel;
90
91
    /**
92
     * @var null|array
93
     */
94
    protected $matchedRoute;
95
96
    /**
97
     * @var \PPI\Framework\Module\Controller\ControllerResolver
98
     */
99
    protected $resolver;
100
101
    /**
102
     * @var string
103
     */
104
    protected $name;
105
106
    /**
107
     * Path to the application root dir aka the "app" directory.
108
     *
109
     * @var null|string
110
     */
111
    protected $rootDir;
112
113
    /**
114
     * Service Manager.
115
     *
116
     * @var \PPI\Framework\ServiceManager\ServiceManager
117
     */
118
    protected $serviceManager;
119
120
    /**
121
     * App constructor.
122
     *
123
     * @param array $options
124
     */
125
    public function __construct(array $options = array())
126
    {
127
        // Default options
128
        $this->environment = isset($options['environment']) && $options['environment'] ? (string)$options['environment'] : 'prod';
129
        $this->debug = isset($options['debug']) && null !== $options['debug'] ? (boolean)$options['debug'] : false;
130
        $this->rootDir = isset($options['rootDir']) && $options['rootDir'] ? (string)$options['rootDir'] : $this->getRootDir();
131
        $this->name = isset($options['name']) && $options['name'] ? (string)$options['name'] : $this->getName();
132
133
        if ($this->debug) {
134
            $this->startTime = microtime(true);
135
            $this->enableDebug();
136
        } else {
137
            ini_set('display_errors', 0);
138
        }
139
    }
140
141
    /**
142
     * Set an App option.
143
     *
144
     * @param $option
145
     * @param $value
146
     *
147
     * @throws \RuntimeException
148
     *
149
     * @return $this
150
     */
151
    public function setOption($option, $value)
152
    {
153
        if (true === $this->booted) {
154
            throw new \RuntimeException('Setting App options after boot() is now allowed');
155
        }
156
157
        // "root_dir" to "rootDir"
158
        $property = preg_replace('/_(.?)/e', "strtoupper('$1')", $option);
159
        if (!property_exists($this, $property)) {
160
            throw new \RuntimeException(sprintf('App property "%s" (option "%s") does not exist', $property, $option));
161
        }
162
163
        $this->$property = $value;
164
165
        return $this;
166
    }
167
168
    /**
169
     * Get an App option.
170
     *
171
     * @param $option
172
     *
173
     * @throws \RuntimeException
174
     *
175
     * @return string
176
     */
177
    public function getOption($option)
178
    {
179
        // "root_dir" to "rootDir"
180
        $property = preg_replace('/_(.?)/e', "strtoupper('$1')", $option);
181
        if (!property_exists($this, $property)) {
182
            throw new \RuntimeException(sprintf('App property "%s" (option "%s") does not exist', $property, $option));
183
        }
184
185
        return $property;
186
    }
187
188
    public function __clone()
189
    {
190
        if ($this->debug) {
191
            $this->startTime = microtime(true);
192
        }
193
194
        $this->booted = false;
195
        $this->serviceManager = null;
196
    }
197
198
    /**
199
     * Run the boot process, load our modules and their dependencies.
200
     *
201
     * This method is automatically called by dispatch(), but you can use it
202
     * to build all services when not handling a request.
203
     *
204
     * @return $this
205
     */
206
    public function boot()
207
    {
208
        if (true === $this->booted) {
209
            return $this;
210
        }
211
212
        $this->serviceManager = $this->buildServiceManager();
213
        $this->log('debug', sprintf('Booting %s ...', $this->name));
214
215
        // Loading our Modules
216
        $this->getModuleManager()->loadModules();
217
        if ($this->debug) {
218
            $modules = $this->getModuleManager()->getModules();
219
            $this->log('debug', sprintf('All modules online (%d): "%s"', count($modules), implode('", "', $modules)));
220
        }
221
222
        // Lets get all the services our of our modules and start setting them in the ServiceManager
223
        $moduleServices = $this->serviceManager->get('ModuleDefaultListener')->getServices();
224
        foreach ($moduleServices as $key => $service) {
225
            $this->serviceManager->setFactory($key, $service);
226
        }
227
228
        $this->booted = true;
229
        if ($this->debug) {
230
            $this->log('debug', sprintf('%s has booted (in %.3f secs)', $this->name, microtime(true) - $this->startTime));
231
        }
232
233
        return $this;
234
    }
235
236
    /**
237
     * Run the application and send the response.
238
     *
239
     * @param RequestInterface|null $request
240
     * @param ResponseInterface|null $response
241
     * @return Response
242
     * @throws \Exception
243
     */
244
    public function run(RequestInterface $request = null, ResponseInterface $response = null)
245
    {
246
        if (false === $this->booted) {
247
            $this->boot();
248
        }
249
250
        $request = $request ?: HttpRequest::createFromGlobals();
251
        $response = $response ?: new Response();
252
253
        $response = $this->dispatch($request, $response);
0 ignored issues
show
Bug introduced by
It seems like $request defined by $request ?: \PPI\Framewo...st::createFromGlobals() on line 250 can also be of type object<Symfony\Component\HttpFoundation\Request>; however, PPI\Framework\App::dispatch() does only seem to accept object<Psr\Http\Message\RequestInterface>, 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...
254
        $response->send();
255
256
        return $response;
257
    }
258
259
    /**
260
     *
261
     * Decide on a route to use and dispatch our module's controller action.
262
     *
263
     * @param RequestInterface $request
264
     * @param ResponseInterface $response
265
     * @return Response
266
     * @throws \Exception
267
     */
268
    public function dispatch(RequestInterface $request, ResponseInterface $response)
269
    {
270
        if (false === $this->booted) {
271
            $this->boot();
272
        }
273
274
        // Routing
275
        $routeParams = $this->handleRouting($request);
276
        $request->attributes->add($routeParams);
0 ignored issues
show
Bug introduced by
Accessing attributes on the interface Psr\Http\Message\RequestInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
277
278
        // Resolve our Controller
279
        $resolver = $this->serviceManager->get('ControllerResolver');
280
        if (false === $controller = $resolver->getController($request)) {
281
            throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s".', $request->getPathInfo()));
282
        }
283
284
        $controllerArguments = $resolver->getArguments($request, $controller);
285
286
        $result = call_user_func_array(
287
            $controller,
288
            $controllerArguments
289
        );
290
291
292
        if(is_string($result)) {
293
            $response->setContent($result);
294
        } else if ($result instanceof ResponseInterface) {
295
            $response = $result;
296
        } else {
297
            throw new \Exception('Invalid response type returned from controller');
298
        }
299
300
        $this->response = $response;
0 ignored issues
show
Bug introduced by
The property response does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
301
302
        return $response;
303
    }
304
305
    /**
306
     * Gets the name of the application.
307
     *
308
     * @return string The application name
309
     *
310
     * @api
311
     */
312
    public function getName()
313
    {
314
        if (null === $this->name) {
315
            $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
316
        }
317
318
        return $this->name;
319
    }
320
321
    /**
322
     * Gets the version of the application.
323
     *
324
     * @return string The application version
325
     *
326
     * @api
327
     */
328
    public function getVersion()
329
    {
330
        return self::VERSION;
331
    }
332
333
    /**
334
     * Get the environment mode the application is in.
335
     *
336
     * @return string The current environment
337
     *
338
     * @api
339
     */
340
    public function getEnvironment()
341
    {
342
        return $this->environment;
343
    }
344
345
    /**
346
     * @param $env
347
     *
348
     * @return bool
349
     */
350
    public function isEnvironment($env)
351
    {
352
        if ('development' == $env) {
353
            $env = 'dev';
354
        } elseif ('production' == $env) {
355
            $env = 'prod';
356
        }
357
358
        return $this->getEnvironment() == $env;
359
    }
360
361
    /**
362
     * Checks if debug mode is enabled.
363
     *
364
     * @return boolean true if debug mode is enabled, false otherwise
365
     *
366
     * @api
367
     */
368
    public function isDebug()
369
    {
370
        return $this->debug;
371
    }
372
373
    /**
374
     * Gets the application root dir.
375
     *
376
     * @return string The application root dir
377
     *
378
     * @api
379
     */
380
    public function getRootDir()
381
    {
382
        if (null === $this->rootDir) {
383
            $this->rootDir = realpath(getcwd() . '/app');
384
        }
385
386
        return $this->rootDir;
387
    }
388
389
    /**
390
     * Get the service manager.
391
     *
392
     * @return ServiceManager\ServiceManager
393
     */
394
    public function getServiceManager()
395
    {
396
        return $this->serviceManager;
397
    }
398
399
    /**
400
     * @note Added for compatibility with Symfony's HttpKernel\Kernel.
401
     *
402
     * @return null|ServiceManager\ServiceManager
403
     */
404
    public function getContainer()
405
    {
406
        return $this->serviceManager;
407
    }
408
409
    /**
410
     * Returns the Module Manager.
411
     *
412
     * @return \Zend\ModuleManager\ModuleManager
413
     */
414
    public function getModuleManager()
415
    {
416
        if (null === $this->moduleManager) {
417
            $this->moduleManager = $this->serviceManager->get('ModuleManager');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->serviceManager->get('ModuleManager') can also be of type array. However, the property $moduleManager is declared as type object<Zend\ModuleManager\ModuleManager>. Maybe add an additional type 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 mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
418
        }
419
420
        return $this->moduleManager;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->moduleManager; of type object|array adds the type array to the return on line 420 which is incompatible with the return type documented by PPI\Framework\App::getModuleManager of type Zend\ModuleManager\ModuleManager.
Loading history...
421
    }
422
423
    /**
424
     * Get an array of the loaded modules.
425
     *
426
     * @return array An array of Module objects, keyed by module name
427
     */
428
    public function getModules()
429
    {
430
        return $this->getModuleManager()->getLoadedModules(true);
431
    }
432
433
    /**
434
     * @see PPI\Framework\Module\ModuleManager::locateResource()
435
     *
436
     * @param string $name A resource name to locate
437
     * @param string $dir A directory where to look for the resource first
438
     * @param Boolean $first Whether to return the first path or paths for all matching bundles
439
     *
440
     * @throws \InvalidArgumentException if the file cannot be found or the name is not valid
441
     * @throws \RuntimeException         if the name contains invalid/unsafe
442
     * @throws \RuntimeException         if a custom resource is hidden by a resource in a derived bundle
443
     *
444
     * @return string|array The absolute path of the resource or an array if $first is false
445
     */
446
    public function locateResource($name, $dir = null, $first = true)
447
    {
448
        return $this->getModuleManager()->locateResource($name, $dir, $first);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Zend\ModuleManager\ModuleManager as the method locateResource() does only exist in the following sub-classes of Zend\ModuleManager\ModuleManager: PPI\Framework\Module\ModuleManager. 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...
449
    }
450
451
    /**
452
     * Gets the request start time (not available if debug is disabled).
453
     *
454
     * @return integer The request start timestamp
455
     *
456
     * @api
457
     */
458
    public function getStartTime()
459
    {
460
        return $this->debug ? $this->startTime : -INF;
461
    }
462
463
    /**
464
     * Gets the cache directory.
465
     *
466
     * @return string The cache directory
467
     *
468
     * @api
469
     */
470
    public function getCacheDir()
471
    {
472
        return $this->rootDir . '/cache/' . $this->environment;
473
    }
474
475
    /**
476
     * Gets the log directory.
477
     *
478
     * @return string The log directory
479
     *
480
     * @api
481
     */
482
    public function getLogDir()
483
    {
484
        return $this->rootDir . '/logs';
485
    }
486
487
    /**
488
     * Gets the charset of the application.
489
     *
490
     * @return string The charset
491
     *
492
     * @api
493
     */
494
    public function getCharset()
495
    {
496
        return 'UTF-8';
497
    }
498
499
    /**
500
     * Returns a ConfigManager instance.
501
     *
502
     * @return \PPI\Framework\Config\ConfigManager
503
     */
504
    public function getConfigManager()
505
    {
506
        if (null === $this->configManager) {
507
            $cachePath = $this->getCacheDir() . '/application-config-cache.' . $this->getName() . '.php';
508
            $this->configManager = new ConfigManager($cachePath, !$this->debug, $this->rootDir . '/config');
509
        }
510
511
        return $this->configManager;
512
    }
513
514
    /**
515
     * Loads a configuration file or PHP array.
516
     *
517
     * @param  $resource
518
     * @param null $type
519
     *
520
     * @return App The current instance
521
     */
522
    public function loadConfig($resource, $type = null)
523
    {
524
        $this->getConfigManager()->addConfig($resource, $type);
525
526
        return $this;
527
    }
528
529
    /**
530
     * Returns the application configuration.
531
     *
532
     * @throws \RuntimeException
533
     *
534
     * @return array|object
535
     */
536
    public function getConfig()
537
    {
538
        if (!$this->booted) {
539
            throw new \RuntimeException('The "Config" service is only available after the App boot()');
540
        }
541
542
        return $this->serviceManager->get('Config');
543
    }
544
545
    public function serialize()
546
    {
547
        return serialize(array($this->environment, $this->debug));
548
    }
549
550
    public function unserialize($data)
551
    {
552
        list($environment, $debug) = unserialize($data);
553
554
        $this->__construct($environment, $debug);
0 ignored issues
show
Unused Code introduced by
The call to App::__construct() has too many arguments starting with $debug.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
555
    }
556
557
    /**
558
     * Returns the application parameters.
559
     *
560
     * @return array An array of application parameters
561
     */
562
    protected function getAppParameters()
563
    {
564
        return array_merge(
565
            array(
566
                'app.root_dir' => $this->rootDir,
567
                'app.environment' => $this->environment,
568
                'app.debug' => $this->debug,
569
                'app.name' => $this->name,
570
                'app.cache_dir' => $this->getCacheDir(),
571
                'app.logs_dir' => $this->getLogDir(),
572
                'app.charset' => $this->getCharset(),
573
            ),
574
            $this->getEnvParameters()
575
        );
576
    }
577
578
    /**
579
     * Gets the environment parameters.
580
     *
581
     * Only the parameters starting with "PPI__" are considered.
582
     *
583
     * @return array An array of parameters
584
     */
585
    protected function getEnvParameters()
0 ignored issues
show
Coding Style introduced by
getEnvParameters uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
586
    {
587
        $parameters = array();
588
        foreach ($_SERVER as $key => $value) {
589
            if (0 === strpos($key, 'PPI__')) {
590
                $parameters[strtolower(str_replace('__', '.', substr($key, 5)))] = $value;
591
            }
592
        }
593
594
        return $parameters;
595
    }
596
597
    /**
598
     * Creates and initializes a ServiceManager instance.
599
     *
600
     * @return ServiceManager The compiled service manager
601
     */
602
    protected function buildServiceManager()
603
    {
604
        // ServiceManager creation
605
        $serviceManager = new ServiceManagerBuilder($this->getConfigManager()->getMergedConfig());
606
        $serviceManager->build($this->getAppParameters());
607
        $serviceManager->set('app', $this);
608
609
        return $serviceManager;
610
    }
611
612
    /**
613
     *
614
     * Perform the matching of a route and return a set of routing parameters if a valid one is found.
615
     * Otherwise exceptions get thrown
616
     *
617
     * @param RequestInterface $request
618
     * @return array
619
     *
620
     * @throws \Exception
621
     */
622
    protected function handleRouting(RequestInterface $request)
623
    {
624
        $this->router = $this->serviceManager->get('Router');
0 ignored issues
show
Bug introduced by
The property router does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
625
        $this->router->warmUp($this->getCacheDir());
626
627
        try {
628
            // Lets load up our router and match the appropriate route
629
            $parameters = $this->router->matchRequest($request);
630 View Code Duplication
            if (!empty($parameters)) {
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...
631
                if (null !== $this->logger) {
632
                    $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], $this->router->parametersToString($parameters)));
633
                }
634
            }
635
        } catch (ResourceNotFoundException $e) {
636
637
            $routeUri = $this->router->generate('Framework_404');
638
            $parameters = $this->router->matchRequest($request::create($routeUri));
639
640
        } catch (\Exception $e) {
641
            throw $e;
642
        }
643
644
        $parameters['_route_params'] = $parameters;
645
        return $parameters;
646
    }
647
648
    /**
649
     * Logs with an arbitrary level.
650
     *
651
     * @param mixed $level
652
     * @param string $message
653
     * @param array $context
654
     */
655
    protected function log($level, $message, array $context = array())
656
    {
657
        if (null === $this->logger && $this->getServiceManager()->has('logger')) {
658
            $this->logger = $this->getServiceManager()->get('logger');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceManager()->get('logger') can also be of type array. However, the property $logger is declared as type object<Psr\Log\LoggerInterface>. Maybe add an additional type 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 mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
659
        }
660
661
        if ($this->logger) {
662
            $this->logger->log($level, $message, $context);
663
        }
664
    }
665
666
    /**
667
     * Enables the debug tools.
668
     *
669
     * This method registers an error handler and an exception handler.
670
     *
671
     * If the Symfony ClassLoader component is available, a special
672
     * class loader is also registered.
673
     */
674
    protected function enableDebug()
675
    {
676
        error_reporting(-1);
677
678
        ErrorHandler::register($this->errorReportingLevel);
679
        if ('cli' !== php_sapi_name()) {
680
            $handler = ExceptionHandler::register();
681
            $handler->setAppVersion($this->getVersion());
682
        } elseif (!ini_get('log_errors') || ini_get('error_log')) {
683
            ini_set('display_errors', 1);
684
        }
685
686
        if (class_exists('Symfony\Component\ClassLoader\DebugClassLoader')) {
687
            DebugClassLoader::enable();
688
        }
689
    }
690
}
691