Module::onDispatch()   B
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 43
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 3 Features 0
Metric Value
c 3
b 3
f 0
dl 0
loc 43
rs 8.5806
cc 4
eloc 27
nc 4
nop 1
1
<?php
2
3
/**
4
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
 *
16
 * This software consists of voluntary contributions made by many individuals
17
 * and is licensed under the MIT license.
18
 */
19
namespace Application;
20
21
use Zend\Console\Adapter\AdapterInterface as Console;
22
use Zend\EventManager\EventInterface;
23
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
24
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
25
use Zend\ModuleManager\Feature\ConfigProviderInterface;
26
use Zend\Mvc\ModuleRouteListener;
27
use Zend\Mvc\MvcEvent;
28
29
class Module implements
30
    AutoloaderProviderInterface,
31
    BootstrapListenerInterface,
32
    ConfigProviderInterface
33
{
34
    /**
35
     * @var \Zend\ServiceManager\ServiceManager
36
     */
37
    protected $services;
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function onBootstrap(EventInterface $e)
43
    {
44
        $this->services = $e->getApplication()->getServiceManager();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\EventManager\EventInterface as the method getApplication() does only exist in the following implementations of said interface: Zend\Mvc\MvcEvent.

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...
45
46
        $eventManager = $e->getApplication()->getEventManager();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\EventManager\EventInterface as the method getApplication() does only exist in the following implementations of said interface: Zend\Mvc\MvcEvent.

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...
47
        $eventManager->attach(MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch']);
48
        $eventManager->attach(MvcEvent::EVENT_RENDER, [$this, 'onRender']);
49
50
        $moduleRouteListener = new ModuleRouteListener();
51
        $moduleRouteListener->attach($eventManager);
52
    }
53
54
    /**
55
     * Handle layout on 'dispatch' event.
56
     *
57
     * @param MvcEvent $e
58
     */
59
    public function onDispatch(MvcEvent $e)
60
    {
61
        $routeMatch = $e->getRouteMatch();
62
        $activeController = $routeMatch->getParam('controller');
63
64
        $listController1Columns = [
65
            'Application\Controller\Index',
66
            'Application\Controller\Credits',
67
            'Application\Controller\Contributors',
68
        ];
69
70
        $controller = $e->getTarget();
71
        if (!$e->getViewModel()->terminate()) {
72
            if (!in_array($activeController, $listController1Columns)) {
73
                $controllerClass = get_class($controller);
74
                $moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
75
76
                $fbMeta['title'] = 'Real Live Learn ZF2';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$fbMeta was never initialized. Although not strictly required by PHP, it is generally a good practice to add $fbMeta = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
77
                $fbMeta['description'] = '';
78
79
                // set title prepend of module desc...
80
                $moduleDetail = $this->services->get('Doctrine\ORM\EntityManager')->getRepository('Application\Entity\ModuleList')->findOneBy([
81
                    'moduleName' => $moduleNamespace,
82
                ]);
83
84
                if ($moduleDetail) {
85
                    $this->services->get('ViewHelperManager')->get('headTitle')->prepend($moduleDetail->getModuleDesc());
86
                    $title = $moduleDetail->getModuleDesc();
87
                    $description = $moduleDetail->getModuleDesc();
88
89
                    $fbMeta['title'] = $title.'-'.$fbMeta['title'];
90
                    $fbMeta['description'] = $description.'-'.$fbMeta['description'];
91
                }
92
93
                $e->getViewModel()->setVariable('fbMeta', $fbMeta);
94
95
                $e->getViewModel()->setVariable('modulenamespace', $moduleNamespace);
96
                $controller->layout('layout/2columns');
97
            } else {
98
                $controller->layout('layout/1columns');
99
            }
100
        }
101
    }
102
103
    /**
104
     * Set variable layout on 'render' event.
105
     *
106
     * @param MvcEvent $e
107
     */
108
    public function onRender(MvcEvent $e)
109
    {
110
        if (!$e->getViewModel()->terminate()) {
111
            $entityManager = $this->services->get('Doctrine\ORM\EntityManager');
112
            $e->getViewModel()
113
              ->setVariable('modules_list', $entityManager->getRepository('Application\Entity\ModuleList')->findBy([], ['id' => 'DESC']));
114
        }
115
    }
116
117
    /**
118
     * Get console usage description.
119
     */
120
    public function getConsoleUsage(Console $console)
0 ignored issues
show
Unused Code introduced by
The parameter $console is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
121
    {
122
        return [
123
            'get contributors' => 'get contributors list',
124
        ];
125
    }
126
127
    /**
128
     * @return array|mixed|\Traversable
129
     */
130
    public function getConfig()
131
    {
132
        return include __DIR__.'/config/module.config.php';
133
    }
134
135
    /**
136
     * @return array
137
     */
138
    public function getAutoloaderConfig()
139
    {
140
        return [
141
            'Zend\Loader\StandardAutoloader' => [
142
                'namespaces' => [
143
                    __NAMESPACE__ => __DIR__.'/src/'.__NAMESPACE__,
144
                ],
145
            ],
146
        ];
147
    }
148
}
149