Completed
Push — develop ( 9193e7...62056c )
by Jaap
12:45 queued 02:43
created

StopwatchMiddleware::execute()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 16
nc 2
nop 2
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of phpDocumentor.
4
 *
5
 *  For the full copyright and license information, please view the LICENSE
6
 *  file that was distributed with this source code.
7
 *
8
 *  @copyright 2010-2017 Mike van Riel<[email protected]>
9
 *  @license   http://www.opensource.org/licenses/mit-license.php MIT
10
 *  @link      http://phpdoc.org
11
 */
12
13
namespace phpDocumentor\Parser\Middleware;
14
15
use phpDocumentor\Event\Dispatcher;
16
use phpDocumentor\Event\LogEvent;
17
use Psr\Log\LogLevel;
18
use phpDocumentor\Reflection\Middleware\Middleware;
19
use Symfony\Component\Stopwatch\Stopwatch;
20
21
final class StopwatchMiddleware implements Middleware
22
{
23
    /** @var int $memory amount of memory used */
24
    private $memory = 0;
25
26
    /**
27
     * @var Stopwatch
28
     */
29
    private $stopwatch;
30
31
    /**
32
     * StopwatchMiddleware constructor.
33
     * @param Stopwatch $stopwatch
34
     */
35
    public function __construct(Stopwatch $stopwatch)
36
    {
37
        $this->stopwatch = $stopwatch;
38
    }
39
40
    /**
41
     * Executes this middle ware class.
42
     *
43
     * @param $command
44
     * @param callable $next
45
     *
46
     * @return object
47
     */
48
    public function execute($command, callable $next)
49
    {
50
        $result = $next($command);
51
52
        if ($this->stopwatch) {
53
            $lap = $this->stopwatch->lap('parser.parse');
54
            $oldMemory = $this->memory;
55
            $periods = $lap->getPeriods();
56
            $memory = end($periods)->getMemory();
57
58
            $this->log(
59
                '>> Memory after processing of file: ' . number_format($memory / 1024 / 1024, 2)
60
                . ' megabytes (' . (($memory - $oldMemory >= 0)
61
                    ? '+'
62
                    : '-') . number_format(($memory - $oldMemory) / 1024)
63
                . ' kilobytes)',
64
                LogLevel::DEBUG
65
            );
66
67
            $this->memory = $memory;
0 ignored issues
show
Documentation Bug introduced by
It seems like $memory can also be of type double. However, the property $memory is declared as type integer. 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...
68
        }
69
70
        return $result;
71
    }
72
73
    /**
74
     * Dispatches a logging request.
75
     *
76
     * @param string   $message  The message to log.
77
     * @param string   $priority The logging priority as declared in the LogLevel PSR-3 class.
78
     * @param string[] $parameters
79
     *
80
     * @return void
81
     */
82
    protected function log($message, $priority = LogLevel::INFO, $parameters = array())
83
    {
84
        Dispatcher::getInstance()->dispatch(
85
            'system.log',
86
            LogEvent::createInstance($this)
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class phpDocumentor\Event\DebugEvent as the method setPriority() does only exist in the following sub-classes of phpDocumentor\Event\DebugEvent: phpDocumentor\Event\LogEvent. 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...
87
                ->setContext($parameters)
88
                ->setMessage($message)
89
                ->setPriority($priority)
90
        );
91
    }
92
}
93