Completed
Pull Request — develop (#307)
by
unknown
09:17
created

Module::init()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 6
nc 1
nop 1
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\EnforceJsonResponseListener;
20
use Core\Listener\StringListener;
21
use Zend\ModuleManager\Feature\ConsoleBannerProviderInterface;
22
use Zend\Console\Adapter\AdapterInterface as Console;
23
use Core\Listener\ErrorHandlerListener;
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
use Zend\ModuleManager\Feature\InitProviderInterface;
29
use Zend\ModuleManager\ModuleManagerInterface;
30
use Zend\ModuleManager\ModuleEvent;
31
32
/**
33
 * Bootstrap class of the Core module
34
 *
35
 */
36
class Module implements ConsoleBannerProviderInterface, InitProviderInterface
37
{
38
    
39
    /**
40
     * {@inheritDoc}
41
     * @see \Zend\ModuleManager\Feature\InitProviderInterface::init()
42
     */
43
    public function init(ModuleManagerInterface $moduleManager)
44
    {
45
        $moduleManager->getEventManager()->attach(ModuleEvent::EVENT_MERGE_CONFIG, function (ModuleEvent $event) {
46
            $config = $event->getConfigListener()
47
                ->getMergedConfig(false);
48
            
49
            if (isset($config['date_default_timezone'])) {
50
                date_default_timezone_set($config['date_default_timezone']);
51
            }
52
        });
53
    }
54
    
55
    public function getConsoleBanner(Console $console)
56
    {
57
        $version = `git describe 2>/dev/null`;
58
        $name = 'YAWIK ' . trim($version);
59
        $width = $console->getWidth();
60
        return sprintf(
61
            "==%1\$s==\n%2\$s%3\$s\n**%1\$s**\n",
62
            str_repeat('-', $width - 4),
63
            str_repeat(' ', floor(($width - strlen($name)) / 2)),
64
            $name
65
        );
66
    }
67
    
68
    /**
69
     * Sets up services on the bootstrap event.
70
     *
71
     * @internal
72
     *     Creates the translation service and a ModuleRouteListener
73
     *
74
     * @param MvcEvent $e
75
     */
76
    public function onBootstrap(MvcEvent $e)
77
    {
78
        // Register the TimezoneAwareDate type with DoctrineMongoODM
79
        // Use it in Annotations ( @Field(type="tz_date") )
80
        if (!DoctrineType::hasType('tz_date')) {
81
            DoctrineType::addType(
82
                'tz_date',
83
                '\Core\Repository\DoctrineMongoODM\Types\TimezoneAwareDate'
84
            );
85
        }
86
        
87
        $sm = $e->getApplication()->getServiceManager();
88
        $translator = $sm->get('translator'); // initialise translator!
89
        \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...
90
        $eventManager        = $e->getApplication()->getEventManager();
91
        $sharedManager       = $eventManager->getSharedManager();
92
        
93
        if (!\Zend\Console\Console::isConsole()) {
94
            $redirectCallback = function () use ($e) {
95
                $routeMatch = $e->getRouteMatch();
96
                $lang = $routeMatch ? $routeMatch->getParam('lang', 'en') : 'en';
97
                $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...
98
                
99
                header('Location: ' . $uri);
100
            };
101
            
102
            $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...
103
            $errorHandlerListener->attach($eventManager);
104
105
            /* @var \Core\Options\ModuleOptions $options */
106
            $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...
107
            $languageRouteListener->attach($eventManager);
108
        
109
        
110
            $ajaxRenderListener = new AjaxRenderListener();
111
            $ajaxRenderListener->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
        $persistenceListener = new PersistenceListener();
128
        $persistenceListener->attach($eventManager);
129
        
130
        $eventManager->attach(
131
            MvcEvent::EVENT_DISPATCH_ERROR,
132
            function ($event) {
133
                $application = $event->getApplication();
134
                if ($application::ERROR_EXCEPTION == $event->getError()) {
135
                    $ex = $event->getParam('exception');
136
                    if (404 == $ex->getCode()) {
137
                        $event->setError($application::ERROR_CONTROLLER_NOT_FOUND);
138
                    }
139
                }
140
            
141
            },
142
            500
143
        );
144
        $eventManager->attach(
145
            MvcEvent::EVENT_DISPATCH,
146
            function ($event) use ($eventManager) {
147
                $eventManager->trigger('postDispatch', $event);
148
            },
149
            -150
150
        );
151
        
152
    }
153
154
    /**
155
     * Loads module specific configuration.
156
     *
157
     * @return array
158
     */
159
    public function getConfig()
160
    {
161
        $config = include __DIR__ . '/config/module.config.php';
162
        return $config;
163
        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...
164
            $config['doctrine']['configuration']['odm_default']['generate_proxies'] = false;
165
            $config['doctrine']['configuration']['odm_default']['generate_hydrators'] = false;
166
            
167
        }
168
        return $config;
169
    }
170
171
    /**
172
     * Loads module specific autoloader configuration.
173
     *
174
     * @return array
175
     */
176
    public function getAutoloaderConfig()
177
    {
178
        return array(
179
            'Zend\Loader\StandardAutoloader' => array(
180
                'namespaces' => array(
181
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
182
                    'CoreTest' => __DIR__ . '/test/' . 'CoreTest',
183
                    'CoreTestUtils' => __DIR__ . '/test/CoreTestUtils',
184
                ),
185
            ),
186
        );
187
    }
188
}
189