Completed
Push — master ( a319ef...d8f31a )
by Vítor
03:19
created

App::getConfig()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

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

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
Bug introduced by
It seems like $response defined by $this->dispatch($request, $response) on line 249 can be null; however, PPI\Framework\App::dispatch() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
250
        $response->send();
251
252
        return $response;
253
    }
254
255
    /**
256
     * Decide on a route to use and dispatch our module's controller action.
257
     *
258
     * @param HttpRequest  $request
259
     * @param HttpResponse $response
260
     *
261
     * @throws \Exception
262
     *
263
     * @return Response
264
     */
265
    public function dispatch(HttpRequest $request, HttpResponse $response)
266
    {
267
        if (false === $this->booted) {
268
            $this->boot();
269
        }
270
271
        // Routing
272
        $routeParams = $this->handleRouting($request);
273
        $request->attributes->add($routeParams);
274
275
        // Resolve our Controller
276
        $resolver = $this->serviceManager->get('ControllerResolver');
277
        if (false === $controller = $resolver->getController($request)) {
278
            throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s".', $request->getPathInfo()));
279
        }
280
281
        $controllerArguments = $resolver->getArguments($request, $controller);
282
283
        $result = call_user_func_array(
284
            $controller,
285
            $controllerArguments
286
        );
287
288
        if ($result === null) {
289
            throw new \Exception('Your action returned null. It must always return something');
290
        } elseif (is_string($result)) {
291
            $response->setContent($result);
292
        } elseif ($result instanceof SymfonyResponse || $response instanceof HttpResponse) {
293
            $response = $result;
294
        } else {
295
            throw new \Exception('Invalid response type returned from controller');
296
        }
297
298
        $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...
299
300
        return $response;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $response; (object|integer|double|null|array|boolean) is incompatible with the return type documented by PPI\Framework\App::dispatch of type PPI\Framework\Response|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
301
    }
302
303
    /**
304
     * Gets the name of the application.
305
     *
306
     * @return string The application name
307
     *
308
     * @api
309
     */
310
    public function getName()
311
    {
312
        if (null === $this->name) {
313
            $this->name = preg_replace('/[^a-zA-Z0-9_]+/', '', basename($this->rootDir));
314
        }
315
316
        return $this->name;
317
    }
318
319
    /**
320
     * Gets the version of the application.
321
     *
322
     * @return string The application version
323
     *
324
     * @api
325
     */
326
    public function getVersion()
327
    {
328
        return self::VERSION;
329
    }
330
331
    /**
332
     * Get the environment mode the application is in.
333
     *
334
     * @return string The current environment
335
     *
336
     * @api
337
     */
338
    public function getEnvironment()
339
    {
340
        return $this->environment;
341
    }
342
343
    /**
344
     * @param $env
345
     *
346
     * @return bool
347
     */
348
    public function isEnvironment($env)
349
    {
350
        if ('development' == $env) {
351
            $env = 'dev';
352
        } elseif ('production' == $env) {
353
            $env = 'prod';
354
        }
355
356
        return $this->getEnvironment() == $env;
357
    }
358
359
    /**
360
     * Checks if debug mode is enabled.
361
     *
362
     * @return bool true if debug mode is enabled, false otherwise
363
     *
364
     * @api
365
     */
366
    public function isDebug()
367
    {
368
        return $this->debug;
369
    }
370
371
    /**
372
     * Gets the application root dir.
373
     *
374
     * @return string The application root dir
375
     *
376
     * @api
377
     */
378
    public function getRootDir()
379
    {
380
        if (null === $this->rootDir) {
381
            $this->rootDir = realpath(getcwd().'/app');
382
        }
383
384
        return $this->rootDir;
385
    }
386
387
    /**
388
     * Get the service manager.
389
     *
390
     * @return ServiceManager\ServiceManager
391
     */
392
    public function getServiceManager()
393
    {
394
        return $this->serviceManager;
395
    }
396
397
    /**
398
     * @note Added for compatibility with Symfony's HttpKernel\Kernel.
399
     *
400
     * @return null|ServiceManager\ServiceManager
401
     */
402
    public function getContainer()
403
    {
404
        return $this->serviceManager;
405
    }
406
407
    /**
408
     * Returns the Module Manager.
409
     *
410
     * @return \Zend\ModuleManager\ModuleManager
411
     */
412
    public function getModuleManager()
413
    {
414
        if (null === $this->moduleManager) {
415
            $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...
416
        }
417
418
        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 418 which is incompatible with the return type documented by PPI\Framework\App::getModuleManager of type Zend\ModuleManager\ModuleManager.
Loading history...
419
    }
420
421
    /**
422
     * Get an array of the loaded modules.
423
     *
424
     * @return array An array of Module objects, keyed by module name
425
     */
426
    public function getModules()
427
    {
428
        return $this->getModuleManager()->getLoadedModules(true);
429
    }
430
431
    /**
432
     * @see PPI\Framework\Module\ModuleManager::locateResource()
433
     *
434
     * @param string $name  A resource name to locate
435
     * @param string $dir   A directory where to look for the resource first
436
     * @param bool   $first Whether to return the first path or paths for all matching bundles
437
     *
438
     * @throws \InvalidArgumentException if the file cannot be found or the name is not valid
439
     * @throws \RuntimeException         if the name contains invalid/unsafe
440
     * @throws \RuntimeException         if a custom resource is hidden by a resource in a derived bundle
441
     *
442
     * @return string|array The absolute path of the resource or an array if $first is false
443
     */
444
    public function locateResource($name, $dir = null, $first = true)
445
    {
446
        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...
447
    }
448
449
    /**
450
     * Gets the request start time (not available if debug is disabled).
451
     *
452
     * @return int The request start timestamp
453
     *
454
     * @api
455
     */
456
    public function getStartTime()
457
    {
458
        return $this->debug ? $this->startTime : -INF;
459
    }
460
461
    /**
462
     * Gets the cache directory.
463
     *
464
     * @return string The cache directory
465
     *
466
     * @api
467
     */
468
    public function getCacheDir()
469
    {
470
        return $this->rootDir.'/cache/'.$this->environment;
471
    }
472
473
    /**
474
     * Gets the log directory.
475
     *
476
     * @return string The log directory
477
     *
478
     * @api
479
     */
480
    public function getLogDir()
481
    {
482
        return $this->rootDir.'/logs';
483
    }
484
485
    /**
486
     * Gets the charset of the application.
487
     *
488
     * @return string The charset
489
     *
490
     * @api
491
     */
492
    public function getCharset()
493
    {
494
        return 'UTF-8';
495
    }
496
497
    /**
498
     * Returns a ConfigManager instance.
499
     *
500
     * @return \PPI\Framework\Config\ConfigManager
501
     */
502
    public function getConfigManager()
503
    {
504
        if (null === $this->configManager) {
505
            $cachePath = $this->getCacheDir().'/application-config-cache.'.$this->getName().'.php';
506
            $this->configManager = new ConfigManager($cachePath, !$this->debug, $this->rootDir.'/config');
507
        }
508
509
        return $this->configManager;
510
    }
511
512
    /**
513
     * Loads a configuration file or PHP array.
514
     *
515
     * @param  $resource
516
     * @param null $type
517
     *
518
     * @return App The current instance
519
     */
520
    public function loadConfig($resource, $type = null)
521
    {
522
        $this->getConfigManager()->addConfig($resource, $type);
523
524
        return $this;
525
    }
526
527
    /**
528
     * Returns the application configuration.
529
     *
530
     * @throws \RuntimeException
531
     *
532
     * @return array|object
533
     */
534
    public function getConfig()
535
    {
536
        if (!$this->booted) {
537
            throw new \RuntimeException('The "Config" service is only available after the App boot()');
538
        }
539
540
        return $this->serviceManager->get('Config');
541
    }
542
543
    public function serialize()
544
    {
545
        return serialize(array($this->environment, $this->debug));
546
    }
547
548
    public function unserialize($data)
549
    {
550
        list($environment, $debug) = unserialize($data);
551
552
        $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...
553
    }
554
555
    /**
556
     * Returns the application parameters.
557
     *
558
     * @return array An array of application parameters
559
     */
560
    protected function getAppParameters()
561
    {
562
        return array_merge(
563
            array(
564
                'app.root_dir' => $this->rootDir,
565
                'app.environment' => $this->environment,
566
                'app.debug' => $this->debug,
567
                'app.name' => $this->name,
568
                'app.cache_dir' => $this->getCacheDir(),
569
                'app.logs_dir' => $this->getLogDir(),
570
                'app.charset' => $this->getCharset(),
571
            ),
572
            $this->getEnvParameters()
573
        );
574
    }
575
576
    /**
577
     * Gets the environment parameters.
578
     *
579
     * Only the parameters starting with "PPI__" are considered.
580
     *
581
     * @return array An array of parameters
582
     */
583
    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...
584
    {
585
        $parameters = array();
586
        foreach ($_SERVER as $key => $value) {
587
            if (0 === strpos($key, 'PPI__')) {
588
                $parameters[strtolower(str_replace('__', '.', substr($key, 5)))] = $value;
589
            }
590
        }
591
592
        return $parameters;
593
    }
594
595
    /**
596
     * Creates and initializes a ServiceManager instance.
597
     *
598
     * @return ServiceManager The compiled service manager
599
     */
600
    protected function buildServiceManager()
601
    {
602
        // ServiceManager creation
603
        $serviceManager = new ServiceManagerBuilder($this->getConfigManager()->getMergedConfig());
604
        $serviceManager->build($this->getAppParameters());
605
        $serviceManager->set('app', $this);
606
607
        return $serviceManager;
608
    }
609
610
    /**
611
     * Perform the matching of a route and return a set of routing parameters if a valid one is found.
612
     * Otherwise exceptions get thrown.
613
     *
614
     * @param HttpRequest $request
615
     *
616
     * @throws \Exception
617
     *
618
     * @return array
619
     */
620
    protected function handleRouting(HttpRequest $request)
621
    {
622
        $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...
623
        $this->router->warmUp($this->getCacheDir());
624
625
        try {
626
            // Lets load up our router and match the appropriate route
627
            $parameters = $this->router->matchRequest($request);
628 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...
629
                if (null !== $this->logger) {
630
                    $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], $this->router->parametersToString($parameters)));
631
                }
632
            }
633
        } catch (ResourceNotFoundException $e) {
634
            $routeUri = $this->router->generate('Framework_404');
635
            $parameters = $this->router->matchRequest($request::create($routeUri));
636
        } catch (\Exception $e) {
637
            throw $e;
638
        }
639
640
        $parameters['_route_params'] = $parameters;
641
642
        return $parameters;
643
    }
644
645
    /**
646
     * Logs with an arbitrary level.
647
     *
648
     * @param mixed  $level
649
     * @param string $message
650
     * @param array  $context
651
     */
652
    protected function log($level, $message, array $context = array())
653
    {
654
        if (null === $this->logger && $this->getServiceManager()->has('logger')) {
655
            $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...
656
        }
657
658
        if ($this->logger) {
659
            $this->logger->log($level, $message, $context);
660
        }
661
    }
662
663
    /**
664
     * Enables the debug tools.
665
     *
666
     * This method registers an error handler and an exception handler.
667
     *
668
     * If the Symfony ClassLoader component is available, a special
669
     * class loader is also registered.
670
     */
671
    protected function enableDebug()
672
    {
673
        error_reporting(-1);
674
675
        ErrorHandler::register($this->errorReportingLevel);
676
        if ('cli' !== php_sapi_name()) {
677
            $handler = ExceptionHandler::register();
678
            $handler->setAppVersion($this->getVersion());
679
        } elseif (!ini_get('log_errors') || ini_get('error_log')) {
680
            ini_set('display_errors', 1);
681
        }
682
683
        if (class_exists('Symfony\Component\ClassLoader\DebugClassLoader')) {
684
            DebugClassLoader::enable();
685
        }
686
    }
687
}
688