Completed
Pull Request — develop (#521)
by
unknown
15:37
created

Module::getRequiredFileLists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
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 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-dev';
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
        $info = [
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
        if ($this->isInMainDevelopment()) {
106
            $info = ArrayUtils::merge($info, [
107
                // subsplit command info
108
                'subsplit [--heads] [--tags] [--skip-update] [--dry-run] [--verbose|v]' => 'Subsplit development repository',
109
                'The subsplit command will automatically subsplit all changes in the develop into github yawik/* repository'.PHP_EOL
110
                .'This command will available only in the Yawik main development repository',
111
                ['--heads','If defined then will subsplit that branch.'],
112
                ['--tags','Subsplit given tags only'],
113
                ['--skip-update','Directly subsplit repository without pull remote branch'],
114
                ['--dry-run','Only show the list of git command that will be executed.'],
115
                ['--verbose | -v', 'Show debug output.'],
116
            ]);
117
        }
118
        return $info;
119
    }
120
121
    /**
122
     * Sets up services on the bootstrap event.
123
     *
124
     * @internal
125
     *     Creates the translation service and a ModuleRouteListener
126
     *
127
     * @param MvcEvent $e
128
     * @throws \Doctrine\ODM\MongoDB\Mapping\MappingException
129
     */
130
    public function onBootstrap(MvcEvent $e)
131
    {
132
        // Register the TimezoneAwareDate type with DoctrineMongoODM
133
        // Use it in Annotations ( @Field(type="tz_date") )
134
        if (!DoctrineType::hasType('tz_date')) {
135
            DoctrineType::addType(
136
                'tz_date',
137
                '\Core\Repository\DoctrineMongoODM\Types\TimezoneAwareDate'
138
            );
139
        }
140
        
141
        $sm = $e->getApplication()->getServiceManager();
142
        $translator = $sm->get('translator'); // initialize translator!
143
        \Zend\Validator\AbstractValidator::setDefaultTranslator($translator);
144
        $eventManager        = $e->getApplication()->getEventManager();
145
        $sharedManager       = $eventManager->getSharedManager();
146
147
        if (!\Zend\Console\Console::isConsole()) {
148
            (new ErrorHandlerListener())->attach($eventManager);
149
150
            /* @var \Core\Options\ModuleOptions $options */
151
            $languageRouteListener = new LanguageRouteListener(
152
                $sm->get('Core/Locale'),
153
                $sm->get('Core/Options')
154
            );
155
            $languageRouteListener->attach($eventManager);
156
        
157
            $ajaxRenderListener = new AjaxRenderListener();
158
            $ajaxRenderListener->attach($eventManager);
159
160
            $ajaxRouteListener = $sm->get(AjaxRouteListener::class);
161
            $ajaxRouteListener->attach($eventManager);
162
163
            $xmlRenderListener = new XmlRenderListener();
164
            $xmlRenderListener->attach($eventManager);
165
        
166
            $enforceJsonResponseListener = new EnforceJsonResponseListener();
167
            $enforceJsonResponseListener->attach($eventManager);
168
        
169
            $stringListener = new StringListener();
170
            $stringListener->attach($eventManager);
171
        }
172
173
        $notificationListener = $sm->get('Core/Listener/Notification');
174
        $notificationListener->attachShared($sharedManager);
175
        $notificationAjaxHandler = new NotificationAjaxHandler();
176
        $eventManager->attach(MvcEvent::EVENT_DISPATCH, array($notificationAjaxHandler, 'injectView'), -20);
177
        $notificationListener->attach(NotificationEvent::EVENT_NOTIFICATION_HTML, array($notificationAjaxHandler, 'render'), -20);
178
        
179
180
        $eventManager->attach(
181
            MvcEvent::EVENT_DISPATCH_ERROR,
182
            function ($event) {
183
                if ($event instanceof MvcEvent) {
184
                    $application = $event->getApplication();
185
                    
186
                    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...
187
                        $ex = $event->getParam('exception');
188
                        if (404 == $ex->getCode()) {
189
                            $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...
190
                        }
191
                    }
192
                }
193
            },
194
            500
195
        );
196
        $eventManager->attach(
197
            MvcEvent::EVENT_DISPATCH,
198
            function ($event) use ($eventManager) {
199
                $eventManager->trigger('postDispatch', $event);
200
            },
201
            -150
202
        );
203
204
        $sm->get('Tracy')->startDebug();
205
    }
206
207
    /**
208
     * Loads module specific configuration.
209
     *
210
     * @return array
211
     */
212
    public function getConfig()
213
    {
214
        $config = include __DIR__ . '/../config/module.config.php';
215
        return $config;
216
    }
217
218
    /**
219
     * @param ModuleManager $manager
220
     */
221
    public function init(ModuleManager $manager)
222
    {
223
        $events = $manager->getEventManager();
224
        $events->attach(ModuleEvent::EVENT_MERGE_CONFIG, [$this,'onMergeConfig']);
225
    }
226
227
    /**
228
     * Manipulate configuration
229
     * @param ModuleEvent $event
230
     */
231
    public function onMergeConfig(ModuleEvent $event)
232
    {
233
        $listener = $event->getConfigListener();
234
        $config = $listener->getMergedConfig(false);
235
236
        // disable subsplit command if we not in main development
237
        if (
238
            isset($config['console'])
239
            && !$this->isInMainDevelopment()
240
            && isset($config['console']['router']['routes']['subsplit'])
241
        ) {
242
            unset($config['console']['router']['routes']['subsplit']);
243
        }
244
245
        $listener->setMergedConfig($config);
246
    }
247
248
    /**
249
     * Returns true if this module in the main development mode
250
     * @return bool
251
     */
252
    private function isInMainDevelopment()
253
    {
254
        return strpos(__DIR__, 'module/Core') !== false;
255
    }
256
}
257