OutputDebug   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 89
Duplicated Lines 8.99 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 10
lcom 1
cbo 1
dl 8
loc 89
ccs 0
cts 55
cp 0
rs 10
c 1
b 0
f 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
C update() 8 51 8
A formatBytesToString() 0 15 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 *
5
 * This file is part of the Apix Project.
6
 *
7
 * (c) Franck Cassedanne <franck at ouarz.net>
8
 *
9
 * @license     http://opensource.org/licenses/BSD-3-Clause  New BSD License
10
 *
11
 */
12
13
namespace Apix\Plugin;
14
15
use Apix\Response;
16
17
class OutputDebug extends PluginAbstract
18
{
19
20
    public static $hook = array('response', 'early');
21
22
    protected $options = array(
23
        'enable'     => true,               // whether to enable or not
24
        'name'       => 'debug',            // the header name
25
        'prepend'    => false,              // whether to prepend the debugging
26
        'timestamp'  => 'D, d M Y H:i:s T', // stamp format, default to RFC1123
27
        'extras'     => null,               // extras to inject, string or array
28
    );
29
30
    public function update(\SplSubject $response)
0 ignored issues
show
Coding Style introduced by
update 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...
31
    {
32
        if (false === $this->options['enable']) {
33
            return false;
34
        }
35
36
        $request = $response->getRequest();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SplSubject as the method getRequest() does only exist in the following implementations of said interface: Apix\Response.

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...
37
        $route = $response->getRoute();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SplSubject as the method getRoute() does only exist in the following implementations of said interface: Apix\Entity, Apix\Entity\EntityClass, Apix\Entity\EntityClosure, Apix\Main, Apix\Response, Apix\Server.

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...
38
39
        $headers = $response->getHeaders();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SplSubject as the method getHeaders() does only exist in the following implementations of said interface: Apix\Response.

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...
40
41
        if (isset($_SERVER['X_AUTH_USER'])) {
42
            $headers['X_AUTH_USER'] = $_SERVER['X_AUTH_USER'];
43
        }
44
45
        if (isset($_SERVER['X_AUTH_KEY'])) {
46
            $headers['X_AUTH_KEY'] = $_SERVER['X_AUTH_KEY'];
47
        }
48
49
        $data = array(
50
            'timestamp'     => gmdate($this->options['timestamp']),
51
            'request'       => sprintf('%s %s%s',
52
                                    $request->getMethod(),
53
                                    $request->getRequestedUri(),
54
                                    isset($_SERVER['SERVER_PROTOCOL'])
55
                                    ? ' ' . $_SERVER['SERVER_PROTOCOL'] : null
56
                               ),
57
            'headers'       => $headers,
58
            'output_format' => $response->getFormat(),
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SplSubject as the method getFormat() does only exist in the following implementations of said interface: Apix\Response.

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...
59
            'router_params' => $route->getParams(),
60
            'memory'        => self::formatBytesToString(memory_get_usage())
61
                               . '~' .  self::formatBytesToString(
62
                                            memory_get_peak_usage()
63
                                        )
64
        );
65
66
        if (defined('APIX_START_TIME')) {
67
            $data['timing'] = round(microtime(true) - APIX_START_TIME, 3) . ' seconds';
68
        }
69
70 View Code Duplication
        if (null !== $this->options['extras']) {
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...
71
            $data['extras'] = $this->options['extras'];
72
        }
73
74
        $name = $this->options['name'];
75 View Code Duplication
        if (true === $this->options['prepend']) {
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...
76
            $response->results = array($name=>$data)+$response->results;
0 ignored issues
show
Bug introduced by
Accessing results on the interface SplSubject 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...
77
        } else {
78
            $response->results[$name] = $data;
0 ignored issues
show
Bug introduced by
Accessing results on the interface SplSubject 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...
79
        }
80
    }
81
82
    /**
83
     * Formats bytes into a human readable string
84
     *
85
     * @param  int     $bytes
86
     * @param  boolean $long
87
     * @return string
88
     */
89
    public static function formatBytesToString($bytes, $long=false)
90
    {
91
        $bytes = (int) $bytes;
92
93
        $unit = false == $long
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
94
                    ? array('B','kB','MB','GB','TB','PB','EB')
95
                    : array(
96
                        'bytes','kilobytes','megabytes','gigabytes',
97
                        'terabytes','petabytes','exabytes'
98
                    );
99
100
        $i = floor(log($bytes, 1024));
101
102
        return round($bytes/pow(1024, $i), 2) . ' ' . $unit[$i];
103
    }
104
105
}
106