Completed
Push — develop ( 62da87...377dcb )
by
unknown
08:20
created

Module   B

Complexity

Total Complexity 11

Size/Duplication

Total Lines 147
Duplicated Lines 10.2 %

Coupling/Cohesion

Components 0
Dependencies 18

Importance

Changes 0
Metric Value
wmc 11
lcom 0
cbo 18
dl 15
loc 147
rs 7.3333
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getConsoleBanner() 0 12 1
C onBootstrap() 0 90 8
A getConfig() 0 5 1
A getAutoloaderConfig() 15 15 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 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 * @author Carsten Bleek <[email protected]>
9
 * @author Mathias Gelhausen <[email protected]>
10
 * @author Miroslav Fedeleš <[email protected]>
11
 */
12
13
/** Core */
14
namespace Core;
15
16
use Core\Listener\AjaxRouteListener;
17
use Zend\Mvc\MvcEvent;
18
use Core\Listener\LanguageRouteListener;
19
use Core\Listener\AjaxRenderListener;
20
use Core\Listener\XmlRenderListener;
21
use Core\Listener\EnforceJsonResponseListener;
22
use Core\Listener\StringListener;
23
use Core\Listener\TracyListener;
24
use Core\Service\Tracy as TracyService;
25
use Zend\ModuleManager\Feature\ConsoleBannerProviderInterface;
26
use Zend\Console\Adapter\AdapterInterface as Console;
27
use Core\Listener\ErrorHandlerListener;
28
use Core\Repository\DoctrineMongoODM\PersistenceListener;
29
use Core\Listener\NotificationAjaxHandler;
30
use Core\Listener\Events\NotificationEvent;
31
use Doctrine\ODM\MongoDB\Types\Type as DoctrineType;
32
33
/**
34
 * Bootstrap class of the Core module
35
 *
36
 */
37
class Module implements ConsoleBannerProviderInterface
38
{
39
    
40
    public function getConsoleBanner(Console $console)
41
    {
42
        $version = `git describe 2>/dev/null`;
43
        $name = 'YAWIK ' . trim($version);
44
        $width = $console->getWidth();
45
        return sprintf(
46
            "==%1\$s==\n%2\$s%3\$s\n**%1\$s**\n",
47
            str_repeat('-', $width - 4),
48
            str_repeat(' ', floor(($width - strlen($name)) / 2)),
49
            $name
50
        );
51
    }
52
    
53
    /**
54
     * Sets up services on the bootstrap event.
55
     *
56
     * @internal
57
     *     Creates the translation service and a ModuleRouteListener
58
     *
59
     * @param MvcEvent $e
60
     */
61
    public function onBootstrap(MvcEvent $e)
62
    {
63
        // Register the TimezoneAwareDate type with DoctrineMongoODM
64
        // Use it in Annotations ( @Field(type="tz_date") )
65
        if (!DoctrineType::hasType('tz_date')) {
66
            DoctrineType::addType(
67
                'tz_date',
68
                '\Core\Repository\DoctrineMongoODM\Types\TimezoneAwareDate'
69
            );
70
        }
71
        
72
        $sm = $e->getApplication()->getServiceManager();
73
        $translator = $sm->get('translator'); // initialise translator!
74
        \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...
75
        $eventManager        = $e->getApplication()->getEventManager();
76
        $sharedManager       = $eventManager->getSharedManager();
77
        
78
        $tracyConfig = $sm->get('Config')['tracy'];
79
        
80
        if ($tracyConfig['enabled']) {
81
            (new TracyService())->register($tracyConfig);
82
            (new TracyListener())->attach($eventManager);
83
        }
84
        
85
        if (!\Zend\Console\Console::isConsole()) {
86
            $redirectCallback = function () use ($e) {
87
                $routeMatch = $e->getRouteMatch();
88
                $lang = $routeMatch ? $routeMatch->getParam('lang', 'en') : 'en';
89
                $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...
90
                
91
                header('Location: ' . $uri);
92
            };
93
            
94
            if (!$tracyConfig['enabled']) {
95
                $errorHandlerListener = new ErrorHandlerListener($sm->get('ErrorLogger'), $redirectCallback);
0 ignored issues
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...
96
                $errorHandlerListener->attach($eventManager);
97
            }
98
99
            /* @var \Core\Options\ModuleOptions $options */
100
            $languageRouteListener = new LanguageRouteListener($sm->get('Core/Locale'));
0 ignored issues
show
Documentation introduced by
$sm->get('Core/Locale') is of type object|array, but the function expects a object<Core\I18n\Locale>.

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...
101
            $languageRouteListener->attach($eventManager);
102
        
103
        
104
            $ajaxRenderListener = new AjaxRenderListener();
105
            $ajaxRenderListener->attach($eventManager);
106
107
            $ajaxRouteListener = $sm->get(AjaxRouteListener::class);
108
            $ajaxRouteListener->attach($eventManager);
109
110
            $xmlRenderListener = new XmlRenderListener();
111
            $xmlRenderListener->attach($eventManager);
112
        
113
            $enforceJsonResponseListener = new EnforceJsonResponseListener();
114
            $enforceJsonResponseListener->attach($eventManager);
115
        
116
            $stringListener = new StringListener();
117
            $stringListener->attach($eventManager);
118
119
        }
120
121
        $notificationListener = $sm->get('Core/Listener/Notification');
122
        $notificationListener->attachShared($sharedManager);
123
        $notificationAjaxHandler = new NotificationAjaxHandler();
124
        $eventManager->attach(MvcEvent::EVENT_DISPATCH, array($notificationAjaxHandler, 'injectView'), -20);
125
        $notificationListener->attach(NotificationEvent::EVENT_NOTIFICATION_HTML, array($notificationAjaxHandler, 'render'), -20);
126
        
127
128
        $eventManager->attach(
129
            MvcEvent::EVENT_DISPATCH_ERROR,
130
            function ($event) {
131
                $application = $event->getApplication();
132
                if ($application::ERROR_EXCEPTION == $event->getError()) {
133
                    $ex = $event->getParam('exception');
134
                    if (404 == $ex->getCode()) {
135
                        $event->setError($application::ERROR_CONTROLLER_NOT_FOUND);
136
                    }
137
                }
138
            
139
            },
140
            500
141
        );
142
        $eventManager->attach(
143
            MvcEvent::EVENT_DISPATCH,
144
            function ($event) use ($eventManager) {
145
                $eventManager->trigger('postDispatch', $event);
146
            },
147
            -150
148
        );
149
        
150
    }
151
152
    /**
153
     * Loads module specific configuration.
154
     *
155
     * @return array
156
     */
157
    public function getConfig()
158
    {
159
        $config = include __DIR__ . '/config/module.config.php';
160
        return $config;
161
    }
162
163
    /**
164
     * Loads module specific autoloader configuration.
165
     *
166
     * @return array
167
     */
168 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...
169
    {
170
        return array(
171
            'Zend\Loader\ClassMapAutoloader' => [
172
                __DIR__ . '/src/autoload_classmap.php'
173
            ],
174
            'Zend\Loader\StandardAutoloader' => array(
175
                'namespaces' => array(
176
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
177
                    'CoreTest' => __DIR__ . '/test/' . 'CoreTest',
178
                    'CoreTestUtils' => __DIR__ . '/test/CoreTestUtils',
179
                ),
180
            ),
181
        );
182
    }
183
}
184