Completed
Push — develop ( 1aadc7...f2612d )
by
unknown
25:44 queued 16:02
created

Module   B

Complexity

Total Complexity 10

Size/Duplication

Total Lines 139
Duplicated Lines 7.91 %

Coupling/Cohesion

Components 0
Dependencies 16

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 10
c 2
b 0
f 0
lcom 0
cbo 16
dl 11
loc 139
rs 8.4614

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getConsoleBanner() 0 13 1
B onBootstrap() 0 79 6
A getConfig() 0 11 2
A getAutoloaderConfig() 11 11 1

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
 * YAWIK
4
 * Core Module Bootstrap
5
 *
6
 * @copyright (c) 2013-2015 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 */
9
10
/** Core */
11
namespace Core;
12
13
use Zend\Mvc\MvcEvent;
14
use Core\Listener\LanguageRouteListener;
15
use Core\Listener\AjaxRenderListener;
16
use Core\Listener\LogListener;
17
use Core\Listener\EnforceJsonResponseListener;
18
use Core\Listener\StringListener;
19
use Zend\ModuleManager\Feature\ConsoleBannerProviderInterface;
20
use Zend\Console\Adapter\AdapterInterface as Console;
21
use Core\Listener\ErrorLoggerListener;
22
use Core\Listener\ErrorHandlerListener;
23
use Zend\Log\Formatter\ErrorHandler;
24
use Core\Repository\DoctrineMongoODM\PersistenceListener;
25
use Core\Listener\NotificationAjaxHandler;
26
use Core\Listener\Events\NotificationEvent;
27
use Doctrine\ODM\MongoDB\Types\Type as DoctrineType;
28
29
/**
30
 * Bootstrap class of the Core module
31
 *
32
 */
33
class Module implements ConsoleBannerProviderInterface
34
{
35
    
36
    public function getConsoleBanner(Console $console)
37
    {
38
        
39
        $version = `git describe`;
40
        $name = 'YAWIK ' . trim($version);
41
        $width = $console->getWidth();
42
        return sprintf(
43
            "==%1\$s==\n%2\$s%3\$s\n**%1\$s**\n",
44
            str_repeat('-', $width - 4),
45
            str_repeat(' ', floor(($width - strlen($name)) / 2)),
46
            $name
47
        );
48
    }
49
    
50
    /**
51
     * Sets up services on the bootstrap event.
52
     *
53
     * @internal
54
     *     Creates the translation service and a ModuleRouteListener
55
     *
56
     * @param MvcEvent $e
57
     */
58
    public function onBootstrap(MvcEvent $e)
59
    {
60
        // Register the TimezoneAwareDate type with DoctrineMongoODM
61
        // Use it in Annotions ( @Field(type="tz_date") )
62
        if (!DoctrineType::hasType('tz_date')) {
63
            DoctrineType::addType(
64
                'tz_date',
65
                '\Core\Repository\DoctrineMongoODM\Types\TimezoneAwareDate'
66
            );
67
        }
68
        
69
        $sm = $e->getApplication()->getServiceManager();
70
        $translator = $sm->get('translator'); // initialise translator!
71
        \Zend\Validator\AbstractValidator::setDefaultTranslator($translator);
0 ignored issues
show
Documentation introduced by
$translator is of type object|array, but the function expects a null|object<Zend\Validat...or\TranslatorInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
72
        $eventManager        = $e->getApplication()->getEventManager();
73
        $sharedManager       = $eventManager->getSharedManager();
74
        
75
 #       $LogListener = new LogListener();
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
76
 #       $LogListener->attach($eventManager);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
77
        
78
        if (!\Zend\Console\Console::isConsole()) {
79
            $redirectCallback = function () use ($e) {
80
                $routeMatch = $e->getRouteMatch();
81
                $lang = $routeMatch ? $routeMatch->getParam('lang', 'en') : 'en';
82
                $uri    = $e->getRouter()->getBaseUrl() . '/' . $lang . '/error';
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Mvc\Router\RouteStackInterface as the method getBaseUrl() does only exist in the following implementations of said interface: Zend\Mvc\Router\Http\Chain, Zend\Mvc\Router\Http\Part, Zend\Mvc\Router\Http\TranslatorAwareTreeRouteStack, Zend\Mvc\Router\Http\TreeRouteStack.

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...
83
                
84
                header('Location: ' . $uri);
85
            };
86
            
87
            $errorHandlerListener = new ErrorHandlerListener($sm->get('ErrorLogger'), $redirectCallback);
1 ignored issue
show
Documentation introduced by
$sm->get('ErrorLogger') is of type object|array, but the function expects a object<Zend\Log\LoggerInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$redirectCallback is of type object<Closure>, but the function expects a null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
88
            $errorHandlerListener->attach($eventManager);
89
            
90
            $languageRouteListener = new LanguageRouteListener();
91
            $languageRouteListener->attach($eventManager);
92
        
93
        
94
            $ajaxRenderListener = new AjaxRenderListener();
95
            $ajaxRenderListener->attach($eventManager);
96
        
97
            $enforceJsonResponseListener = new EnforceJsonResponseListener();
98
            $enforceJsonResponseListener->attach($eventManager);
99
        
100
            $stringListener = new StringListener();
101
            $stringListener->attach($eventManager);
102
103
        }
104
105
        $notificationListener = $sm->get('Core/Listener/Notification');
106
        $notificationListener->attachShared($sharedManager);
107
        $notificationAjaxHandler = new NotificationAjaxHandler();
108
        $eventManager->attach(MvcEvent::EVENT_DISPATCH, array($notificationAjaxHandler, 'injectView'), -20);
109
        $notificationListener->attach(NotificationEvent::EVENT_NOTIFICATION_HTML, array($notificationAjaxHandler, 'render'), -20);
110
        
111
        $persistenceListener = new PersistenceListener();
112
        $persistenceListener->attach($eventManager);
113
        
114
        $eventManager->attach(
115
            MvcEvent::EVENT_DISPATCH_ERROR,
116
            function ($event) {
117
                $application = $event->getApplication();
118
                if ($application::ERROR_EXCEPTION == $event->getError()) {
119
                    $ex = $event->getParam('exception');
120
                    if (404 == $ex->getCode()) {
121
                        $event->setError($application::ERROR_CONTROLLER_NOT_FOUND);
122
                    }
123
                }
124
            
125
            },
126
            500
127
        );
128
        $eventManager->attach(
129
            MvcEvent::EVENT_DISPATCH,
130
            function ($event) use ($eventManager) {
131
                $eventManager->trigger('postDispatch', $event);
132
            },
133
            -150
134
        );
135
        
136
    }
137
138
    /**
139
     * Loads module specific configuration.
140
     *
141
     * @return array
142
     */
143
    public function getConfig()
144
    {
145
        $config = include __DIR__ . '/config/module.config.php';
146
        return $config;
147
        if (\Zend\Console\Console::isConsole()) {
0 ignored issues
show
Unused Code introduced by
if (\Zend\Console\Consol..._hydrators'] = false; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
148
            $config['doctrine']['configuration']['odm_default']['generate_proxies'] = false;
149
            $config['doctrine']['configuration']['odm_default']['generate_hydrators'] = false;
150
            
151
        }
152
        return $config;
153
    }
154
155
    /**
156
     * Loads module specific autoloader configuration.
157
     *
158
     * @return array
159
     */
160 View Code Duplication
    public function getAutoloaderConfig()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
161
    {
162
        return array(
163
            'Zend\Loader\StandardAutoloader' => array(
164
                'namespaces' => array(
165
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
166
                    'CoreTest' => __DIR__ . '/test/' . 'CoreTest'
167
                ),
168
            ),
169
        );
170
    }
171
}
172