Completed
Push — master ( a5d155...804a55 )
by Fabio
65:23
created

TFirebugLogRoute::renderMessageCallback()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
1
<?php
2
/**
3
 * TLogRouter, TLogRoute, TFileLogRoute, TEmailLogRoute class file
4
 *
5
 * @author Qiang Xue <[email protected]>
6
 * @link https://github.com/pradosoft/prado
7
 * @copyright Copyright &copy; 2005-2016 The PRADO Group
8
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
9
 * @package Prado\Util
10
 */
11
12
namespace Prado\Util;
13
14
use Prado\Web\Javascripts\TJavaScript;
15
use Prado\Web\UI\ActiveControls\TActivePageAdapter;
16
17
/**
18
 * TFirebugLogRoute class.
19
 *
20
 * TFirebugLogRoute prints selected log messages in the firebug log console.
21
 *
22
 * {@link http://www.getfirebug.com/ FireBug Website}
23
 *
24
 * @author Enrico Stahn <[email protected]>, Christophe Boulain <[email protected]>
25
 * @package Prado\Util
26
 * @since 3.1.2
27
 */
28
class TFirebugLogRoute extends TBrowserLogRoute
29
{
30
31
	public function processLogs($logs)
32
	{
33
		$page = $this->getService()->getRequestedPage();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Prado\IService as the method getRequestedPage() does only exist in the following implementations of said interface: Prado\Web\Services\TPageService, Prado\Wsat\TWsatService.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
34
		if (!$page->getIsCallback()) {
35
			return parent::processLogs($logs);
36
		}
37
38
		if (empty($logs) || $this->getApplication()->getMode() === 'Performance') {
39
			return;
40
		}
41
		$first = $logs[0][3];
42
		$even = true;
43
44
		$blocks = [ [ 'info', 'Tot Time', 'Time    ', '[Level] [Category] [Message]' ] ];
45 View Code Duplication
		for ($i = 0, $n = count($logs); $i < $n; ++$i) {
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...
46
			if ($i < $n - 1) {
47
				$timing['delta'] = $logs[$i + 1][3] - $logs[$i][3];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$timing was never initialized. Although not strictly required by PHP, it is generally a good practice to add $timing = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
48
				$timing['total'] = $logs[$i + 1][3] - $first;
0 ignored issues
show
Bug introduced by
The variable $timing does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
49
			} else {
50
				$timing['delta'] = '?';
51
				$timing['total'] = $logs[$i][3] - $first;
52
			}
53
			$timing['even'] = !($even = !$even);
54
			$blocks[] = $this->renderMessageCallback($logs[$i], $timing);
55
		}
56
57
		try {
58
			$blocks = TJavaScript::jsonEncode($blocks);
59
		} catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class Prado\Util\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
60
			// strip everythin not 7bit ascii
61
			$blocks = preg_replace('/[^(\x20-\x7F)]*/', '', serialize($blocks));
62
		}
63
64
		// the response has already been flushed
65
		$response = $this->getApplication()->getResponse();
66
		$content = $response->createHtmlWriter();
67
		$content->getWriter()->setBoundary(TActivePageAdapter::CALLBACK_DEBUG_HEADER);
68
		$content->write($blocks);
69
		$response->write($content);
70
	}
71
72
	protected function renderHeader()
73
	{
74
		$string = <<<EOD
75
76
<script type="text/javascript">
77
/*<![CDATA[*/
78
if (typeof(console) == 'object')
79
{
80
	var groupFunc = blocks.length < 10 ? 'group': 'groupCollapsed';
81
	if(typeof log[groupFunc] === "function")
82
		log[groupFunc]("Callback logs ("+blocks.length+" entries)");
83
84
	console.log ("[Tot Time] [Time    ] [Level] [Category] [Message]");
85
86
EOD;
87
88
		return $string;
89
	}
90
91
	protected function renderMessage($log, $info)
92
	{
93
		$logfunc = 'console.' . $this->getFirebugLoggingFunction($log[1]);
94
		$total = sprintf('%0.6f', $info['total']);
95
		$delta = sprintf('%0.6f', $info['delta']);
96
		$msg = trim($this->formatLogMessage($log[0], $log[1], $log[2], ''));
97
		$msg = preg_replace('/\(line[^\)]+\)$/', '', $msg); //remove line number info
98
		$msg = "[{$total}] [{$delta}] " . $msg; // Add time spent and cumulated time spent
99
		$string = $logfunc . '(\'' . addslashes($msg) . '\');' . "\n";
100
101
		return $string;
102
	}
103
104
	protected function renderMessageCallback($log, $info)
105
	{
106
		$logfunc = $this->getFirebugLoggingFunction($log[1]);
107
		$total = sprintf('%0.6f', $info['total']);
108
		$delta = sprintf('%0.6f', $info['delta']);
109
		$msg = trim($this->formatLogMessage($log[0], $log[1], $log[2], ''));
110
		$msg = preg_replace('/\(line[^\)]+\)$/', '', $msg); //remove line number info
111
112
		return [$logfunc, $total, $delta, $msg];
113
	}
114
115
	protected function renderFooter()
116
	{
117
		$string = <<<EOD
118
119
	if(typeof console.groupEnd === "function")
120
		console.groupEnd();
121
122
}
123
</script>
124
125
EOD;
126
127
		return $string;
128
	}
129
130
	protected function getFirebugLoggingFunction($level)
131
	{
132
		switch ($level) {
133
			case TLogger::DEBUG:
134
			case TLogger::INFO:
135
			case TLogger::NOTICE:
136
				return 'info';
137
			case TLogger::WARNING:
138
				return 'warn';
139
			case TLogger::ERROR:
140
			case TLogger::ALERT:
141
			case TLogger::FATAL:
142
				return 'error';
143
			default:
144
				return 'log';
145
		}
146
	}
147
}
148