Passed
Push — develop ( 28c299...928e2a )
by Mathias
12:40
created

Module   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 200
Duplicated Lines 0 %

Test Coverage

Coverage 75.29%

Importance

Changes 0
Metric Value
wmc 17
eloc 92
dl 0
loc 200
c 0
b 0
f 0
ccs 64
cts 85
cp 0.7529
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
B onBootstrap() 0 75 6
A getRequiredDirectoryLists() 0 7 1
A init() 0 4 1
A getConsoleBanner() 0 9 1
A getRequiredFileLists() 0 4 1
A onMergeConfig() 0 15 4
A getConfig() 0 4 1
A isInMainDevelopment() 0 3 1
A getConsoleUsage() 0 16 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 Core\Listener\AjaxRouteListener;
17
use Core\Options\ModuleOptions;
18
use Yawik\Composer\RequireDirectoryPermissionInterface;
19
use Yawik\Composer\RequireFilePermissionInterface;
20
use Zend\ModuleManager\Feature\ConsoleUsageProviderInterface;
21
use Zend\ModuleManager\ModuleEvent;
22
use Zend\ModuleManager\ModuleManager;
23
use Zend\Mvc\MvcEvent;
24
use Core\Listener\LanguageRouteListener;
25
use Core\Listener\AjaxRenderListener;
26
use Core\Listener\XmlRenderListener;
27
use Core\Listener\EnforceJsonResponseListener;
28
use Core\Listener\StringListener;
29
use Zend\ModuleManager\Feature\ConsoleBannerProviderInterface;
30
use Zend\Console\Adapter\AdapterInterface as Console;
31
use Core\Listener\ErrorHandlerListener;
32
use Core\Listener\NotificationAjaxHandler;
33
use Core\Listener\Events\NotificationEvent;
34
use Doctrine\ODM\MongoDB\Types\Type as DoctrineType;
35
use Zend\Stdlib\ArrayUtils;
36
37
/**
38
 * Bootstrap class of the Core module
39
 */
40
class Module implements
41
    ConsoleBannerProviderInterface,
42
    ConsoleUsageProviderInterface,
43
    RequireFilePermissionInterface,
44
    RequireDirectoryPermissionInterface
45
{
46
    const VERSION = '0.32.0';
47
48
    /**
49
     * @param ModuleOptions $options
50
     * @inheritdoc
51
     * @return array
52
     */
53
    public function getRequiredFileLists(ModuleOptions $options)
54
    {
55
        return [
56
            $options->getLogDir().'/yawik.log'
57
        ];
58
    }
59
60
    /**
61
     * @param ModuleOptions $options
62
     * @return array
63
     */
64
    public function getRequiredDirectoryLists(ModuleOptions $options)
65
    {
66
        return [
67
            $options->getConfigDir().'/autoload',
68
            $options->getCacheDir(),
69
            $options->getLogDir(),
70
            $options->getLogDir().'/tracy'
71
        ];
72
    }
73
74
75
    public function getConsoleBanner(Console $console)
76
    {
77
        $name = Application::getCompleteVersion();
78
        $width = $console->getWidth();
79
        return sprintf(
80
            "==%1\$s==\n%2\$s%3\$s\n**%1\$s**\n",
81
            str_repeat('-', $width - 4),
82
            str_repeat(' ', floor(($width - strlen($name)) / 2)),
0 ignored issues
show
Bug introduced by
floor($width - strlen($name) / 2) of type double is incompatible with the type integer expected by parameter $multiplier of str_repeat(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

82
            str_repeat(' ', /** @scrutinizer ignore-type */ floor(($width - strlen($name)) / 2)),
Loading history...
83
            $name
84
        );
85
    }
86
87
    public function getConsoleUsage(Console $console)
88
    {
89
        return [
90
            'purge [--no-check] [--options=] <entity> [<id>]'  => 'Purge entities',
91
            'This command will load entities to be purged, checks the dependency of each and removes all entities completely from the',
92
            'database. However, called with no <entity> and options it will output a list of all available entity loaders and its options.',
93
            '',
94
            ['--no-check', 'Skip the dependency check and remove all entities and dependencies straight away.'],
95
            ['--options=STRING', 'JSON string represents options for the specific entity loader used.'],
96
            "",
97
            // assets-install info
98
            'assets-install [--symlink] [--relative] <target>' => 'Install assets in the given target',
99
            'The assets-install command will install assets in the given <target> directory. If no option given this command will copy assets into the target.',
100
            ['--symlink','This option will install assets using absolute symlink directory'],
101
            ['--relative','This option will install assets using relative symlink'],
102
            ""
103
        ];
104
    }
105
106
    /**
107
     * Sets up services on the bootstrap event.
108
     *
109
     * @internal
110
     *     Creates the translation service and a ModuleRouteListener
111
     *
112
     * @param MvcEvent $e
113
     * @throws \Doctrine\ODM\MongoDB\Mapping\MappingException
114
     */
115 4
    public function onBootstrap(MvcEvent $e)
116
    {
117
        // Register the TimezoneAwareDate type with DoctrineMongoODM
118
        // Use it in Annotations ( @Field(type="tz_date") )
119 4
        if (!DoctrineType::hasType('tz_date')) {
120 1
            DoctrineType::addType(
121 1
                'tz_date',
122 1
                '\Core\Repository\DoctrineMongoODM\Types\TimezoneAwareDate'
123
            );
124
        }
125
        
126 4
        $sm = $e->getApplication()->getServiceManager();
127 4
        $translator = $sm->get('translator'); // initialize translator!
128 4
        \Zend\Validator\AbstractValidator::setDefaultTranslator($translator);
129 4
        $eventManager        = $e->getApplication()->getEventManager();
130 4
        $sharedManager       = $eventManager->getSharedManager();
131
132 4
        if (!\Zend\Console\Console::isConsole()) {
133 4
            (new ErrorHandlerListener())->attach($eventManager);
134
135
            /* @var \Core\Options\ModuleOptions $options */
136 4
            $languageRouteListener = new LanguageRouteListener(
137 4
                $sm->get('Core/Locale'),
138 4
                $sm->get('Core/Options')
139
            );
140 4
            $languageRouteListener->attach($eventManager);
141
        
142 4
            $ajaxRenderListener = new AjaxRenderListener();
143 4
            $ajaxRenderListener->attach($eventManager);
144
145 4
            $ajaxRouteListener = $sm->get(AjaxRouteListener::class);
146 4
            $ajaxRouteListener->attach($eventManager);
147
148 4
            $xmlRenderListener = new XmlRenderListener();
149 4
            $xmlRenderListener->attach($eventManager);
150
        
151 4
            $enforceJsonResponseListener = new EnforceJsonResponseListener();
152 4
            $enforceJsonResponseListener->attach($eventManager);
153
        
154 4
            $stringListener = new StringListener();
155 4
            $stringListener->attach($eventManager);
156
        }
157
158 4
        $notificationListener = $sm->get('Core/Listener/Notification');
159 4
        $notificationListener->attachShared($sharedManager);
160 4
        $notificationAjaxHandler = new NotificationAjaxHandler();
161 4
        $eventManager->attach(MvcEvent::EVENT_DISPATCH, array($notificationAjaxHandler, 'injectView'), -20);
162 4
        $notificationListener->attach(NotificationEvent::EVENT_NOTIFICATION_HTML, array($notificationAjaxHandler, 'render'), -20);
163
        
164
165 4
        $eventManager->attach(
166 4
            MvcEvent::EVENT_DISPATCH_ERROR,
167 4
            function ($event) {
168 2
                if ($event instanceof MvcEvent) {
169 2
                    $application = $event->getApplication();
170
                    
171 2
                    if ($application::ERROR_EXCEPTION == $event->getError()) {
0 ignored issues
show
Bug introduced by
The constant Zend\Mvc\ApplicationInterface::ERROR_EXCEPTION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
172
                        $ex = $event->getParam('exception');
173
                        if (404 == $ex->getCode()) {
174
                            $event->setError($application::ERROR_CONTROLLER_NOT_FOUND);
0 ignored issues
show
Bug introduced by
The constant Zend\Mvc\ApplicationInte...OR_CONTROLLER_NOT_FOUND was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
175
                        }
176
                    }
177
                }
178 4
            },
179 4
            500
180
        );
181 4
        $eventManager->attach(
182 4
            MvcEvent::EVENT_DISPATCH,
183 4
            function ($event) use ($eventManager) {
184 4
                $eventManager->trigger('postDispatch', $event);
185 4
            },
186 4
            -150
187
        );
188
189 4
        $sm->get('Tracy')->startDebug();
190 4
    }
191
192
    /**
193
     * Loads module specific configuration.
194
     *
195
     * @return array
196
     */
197 5
    public function getConfig()
198
    {
199 5
        $config = include __DIR__ . '/../config/module.config.php';
200 5
        return $config;
201
    }
202
203
    /**
204
     * @param ModuleManager $manager
205
     */
206 5
    public function init(ModuleManager $manager)
207
    {
208 5
        $events = $manager->getEventManager();
209 5
        $events->attach(ModuleEvent::EVENT_MERGE_CONFIG, [$this,'onMergeConfig']);
210 5
    }
211
212
    /**
213
     * Manipulate configuration
214
     * @param ModuleEvent $event
215
     */
216 5
    public function onMergeConfig(ModuleEvent $event)
217
    {
218 5
        $listener = $event->getConfigListener();
219 5
        $config = $listener->getMergedConfig(false);
220
221
        // disable subsplit command if we not in main development
222
        if (
223 5
            isset($config['console'])
224 5
            && !$this->isInMainDevelopment()
225 5
            && isset($config['console']['router']['routes']['subsplit'])
226
        ) {
227
            unset($config['console']['router']['routes']['subsplit']);
228
        }
229
230 5
        $listener->setMergedConfig($config);
231 5
    }
232
233
    /**
234
     * Returns true if this module in the main development mode
235
     * @return bool
236
     */
237 5
    private function isInMainDevelopment()
238
    {
239 5
        return strpos(__DIR__, 'module/Core') !== false;
240
    }
241
}
242