Completed
Push — develop ( 893c05...38ac6c )
by
unknown
12s
created

Module::onBootstrap()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 89
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 89
rs 5.6482
c 0
b 0
f 0
cc 8
eloc 54
nc 12
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 Zend\Mvc\MvcEvent;
17
use Core\Listener\LanguageRouteListener;
18
use Core\Listener\AjaxRenderListener;
19
use Core\Listener\XmlRenderListener;
20
use Core\Listener\EnforceJsonResponseListener;
21
use Core\Listener\StringListener;
22
use Core\Listener\TracyListener;
23
use Core\Service\Tracy as TracyService;
24
use Zend\ModuleManager\Feature\ConsoleBannerProviderInterface;
25
use Zend\Console\Adapter\AdapterInterface as Console;
26
use Core\Listener\ErrorHandlerListener;
27
use Core\Repository\DoctrineMongoODM\PersistenceListener;
28
use Core\Listener\NotificationAjaxHandler;
29
use Core\Listener\Events\NotificationEvent;
30
use Doctrine\ODM\MongoDB\Types\Type as DoctrineType;
31
32
/**
33
 * Bootstrap class of the Core module
34
 *
35
 */
36
class Module implements ConsoleBannerProviderInterface
37
{
38
    
39
    public function getConsoleBanner(Console $console)
40
    {
41
        $version = `git describe 2>/dev/null`;
42
        $name = 'YAWIK ' . trim($version);
43
        $width = $console->getWidth();
44
        return sprintf(
45
            "==%1\$s==\n%2\$s%3\$s\n**%1\$s**\n",
46
            str_repeat('-', $width - 4),
47
            str_repeat(' ', floor(($width - strlen($name)) / 2)),
48
            $name
49
        );
50
    }
51
    
52
    /**
53
     * Sets up services on the bootstrap event.
54
     *
55
     * @internal
56
     *     Creates the translation service and a ModuleRouteListener
57
     *
58
     * @param MvcEvent $e
59
     */
60
    public function onBootstrap(MvcEvent $e)
61
    {
62
        // Register the TimezoneAwareDate type with DoctrineMongoODM
63
        // Use it in Annotations ( @Field(type="tz_date") )
64
        if (!DoctrineType::hasType('tz_date')) {
65
            DoctrineType::addType(
66
                'tz_date',
67
                '\Core\Repository\DoctrineMongoODM\Types\TimezoneAwareDate'
68
            );
69
        }
70
        
71
        $sm = $e->getApplication()->getServiceManager();
72
        $translator = $sm->get('translator'); // initialise translator!
73
        \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...
74
        $eventManager        = $e->getApplication()->getEventManager();
75
        $sharedManager       = $eventManager->getSharedManager();
76
        
77
        $tracyConfig = $sm->get('Config')['tracy'];
78
        
79
        if ($tracyConfig['enabled']) {
80
            (new TracyService())->register($tracyConfig);
81
            (new TracyListener())->attach($eventManager);
82
        }
83
        
84
        if (!\Zend\Console\Console::isConsole()) {
85
            $redirectCallback = function () use ($e) {
86
                $routeMatch = $e->getRouteMatch();
87
                $lang = $routeMatch ? $routeMatch->getParam('lang', 'en') : 'en';
88
                $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...
89
                
90
                header('Location: ' . $uri);
91
            };
92
            
93
            if (!$tracyConfig['enabled']) {
94
                $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...
95
                $errorHandlerListener->attach($eventManager);
96
            }
97
98
            /* @var \Core\Options\ModuleOptions $options */
99
            $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...
100
            $languageRouteListener->attach($eventManager);
101
        
102
        
103
            $ajaxRenderListener = new AjaxRenderListener();
104
            $ajaxRenderListener->attach($eventManager);
105
106
            $xmlRenderListener = new XmlRenderListener();
107
            $xmlRenderListener->attach($eventManager);
108
        
109
            $enforceJsonResponseListener = new EnforceJsonResponseListener();
110
            $enforceJsonResponseListener->attach($eventManager);
111
        
112
            $stringListener = new StringListener();
113
            $stringListener->attach($eventManager);
114
115
        }
116
117
        $notificationListener = $sm->get('Core/Listener/Notification');
118
        $notificationListener->attachShared($sharedManager);
119
        $notificationAjaxHandler = new NotificationAjaxHandler();
120
        $eventManager->attach(MvcEvent::EVENT_DISPATCH, array($notificationAjaxHandler, 'injectView'), -20);
121
        $notificationListener->attach(NotificationEvent::EVENT_NOTIFICATION_HTML, array($notificationAjaxHandler, 'render'), -20);
122
        
123
        $persistenceListener = new PersistenceListener();
124
        $persistenceListener->attach($eventManager);
125
        
126
        $eventManager->attach(
127
            MvcEvent::EVENT_DISPATCH_ERROR,
128
            function ($event) {
129
                $application = $event->getApplication();
130
                if ($application::ERROR_EXCEPTION == $event->getError()) {
131
                    $ex = $event->getParam('exception');
132
                    if (404 == $ex->getCode()) {
133
                        $event->setError($application::ERROR_CONTROLLER_NOT_FOUND);
134
                    }
135
                }
136
            
137
            },
138
            500
139
        );
140
        $eventManager->attach(
141
            MvcEvent::EVENT_DISPATCH,
142
            function ($event) use ($eventManager) {
143
                $eventManager->trigger('postDispatch', $event);
144
            },
145
            -150
146
        );
147
        
148
    }
149
150
    /**
151
     * Loads module specific configuration.
152
     *
153
     * @return array
154
     */
155
    public function getConfig()
156
    {
157
        $config = include __DIR__ . '/config/module.config.php';
158
        return $config;
159
    }
160
161
    /**
162
     * Loads module specific autoloader configuration.
163
     *
164
     * @return array
165
     */
166 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...
167
    {
168
        return array(
169
            'Zend\Loader\ClassMapAutoloader' => [
170
                __DIR__ . '/src/autoload_classmap.php'
171
            ],
172
            'Zend\Loader\StandardAutoloader' => array(
173
                'namespaces' => array(
174
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
175
                    'CoreTest' => __DIR__ . '/test/' . 'CoreTest',
176
                    'CoreTestUtils' => __DIR__ . '/test/CoreTestUtils',
177
                ),
178
            ),
179
        );
180
    }
181
}
182