Completed
Push — master ( 0ffdb7...7e1267 )
by Nikita
08:30
created

Core::createMetadata()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 11
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 14
ccs 0
cts 0
cp 0
crap 2
rs 9.4285
1
<?php
2
/*
3
 * This file is part of the SamsonPHP\Core package.
4
 * (c) 2013 Vitaly Iegorov <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
namespace samson\core;
10
11
use samsonframework\container\Builder;
12
use samsonframework\container\metadata\ClassMetadata;
13
use samsonframework\container\metadata\MethodMetadata;
14
use samsonframework\core\SystemInterface;
15
use samsonframework\di\ContainerInterface;
16
use samsonframework\resource\ResourceMap;
17
use samsonphp\config\Scheme;
18
use samsonphp\core\exception\CannotLoadModule;
19
use samsonphp\core\exception\ViewPathNotFound;
20
use samsonphp\event\Event;
21
use samsonphp\generator\Generator;
22
23
/**
24
 * Core of SamsonPHP
25
 * 
26
 * @package SamsonPHP
27
 * @author 	Vitaly Iegorov <[email protected]>
28
 * @version @version@
29
 */
30
class Core implements SystemInterface
31
{
32
    /* Rendering models */
33
    /** Standard algorithm for view rendering */
34
    const RENDER_STANDART = 1;
35
    /** View rendering algorithm from array of view variables */
36
    const RENDER_VARIABLE = 3;
37
38
    /** @var  ResourceMap Current web-application resource map */
39
    public $map;
40
41
    /** @var ContainerInterface */
42
    protected $container;
43
44
   
45
    /** @var string Path to current web-application */
46
    public $system_path = __SAMSON_CWD__;
47
    /** @var string View path loading mode */
48
    public $render_mode = self::RENDER_STANDART;
49
    /** @var Module Pointer to current active module */
50
    protected $active = null;
51
    /** @var bool Flag for outputting layout template, used for asynchronous requests */
52
    protected $async = false;
53
    /** @var string Path to main system template */
54
    protected $template_path = __SAMSON_DEFAULT_TEMPLATE;
55
    /** @var string Current system environment */
56
    protected $environment;
57
58
    protected $metadataCollection = [];
59
60
    /**
61
     * Core constructor.
62
     *
63
     * @param ResourceMap|null $map system resources
64
     */
65
    public function __construct(ResourceMap $map = null)
66
    {
67
        if (!isset($map)) {
68
            // Get correct web-application path
69
            $this->system_path = __SAMSON_CWD__;
70
71
            // Get web-application resource map
72
            $this->map = ResourceMap::get($this->system_path, false, array('src/'));
73
        } else { // Use data from passed map
74
            $this->map = $map;
75
            $this->system_path = $map->entryPoint;
76
        }
77
78
        // Connect static collection with this dynamic field to avoid duplicates
79
        $this->module_stack = &Module::$instances;
0 ignored issues
show
Bug introduced by
The property module_stack does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
80
81
        // Temporary add template worker
82
        $this->subscribe('core.rendered', array($this, 'generateTemplate'));
83
84
        $whoops = new \Whoops\Run;
85
        $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler);
0 ignored issues
show
Documentation introduced by
new \Whoops\Handler\PrettyPageHandler() is of type object<Whoops\Handler\PrettyPageHandler>, but the function expects a callable.

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...
86
        $whoops->register();
87
88
        // Fire core creation event
89
        Event::fire('core.created', array(&$this));
90
91
        // Signal core configure event
92
        Event::signal('core.configure', array($this->system_path . __SAMSON_CONFIG_PATH));
93
    }
94
95
    /**
96
     * Generic wrap for Event system subscription.
97
     * @see \samson\core\\samsonphp\event\Event::subscribe()
98
     *
99
     * @param string   $key     Event identifier
100
     * @param callable $handler Event handler
101
     * @param array    $params  Event parameters
102
     *
103
     * @return $this Chaining
104
     */
105
    public function subscribe($key, $handler, $params = array())
106
    {
107
        Event::subscribe($key, $handler, $params);
108
109
        return $this;
110 1
    }
111
112
    /**
113
     * Change current system working environment or receive
114
     * current system enviroment if no arguments are passed.
115
     *
116
     * @param string $environment Environment identifier
117
     *
118
     * TODO: Function has two different logics - needs to be changed!
119
     * @return $this|string Chaining or current system environment
120
     */
121 1
    public function environment($environment = Scheme::BASE)
122
    {
123
        if (func_num_args() !== 0) {
124
            $this->environment = $environment;
125
126
            // Signal core environment change
127
            Event::signal('core.environment.change', array($environment, &$this));
128
            return $this;
129
        }
130
131
        return $this->environment;
132
    }
133
134
    /**
135
     * Generate special response header triggering caching mechanisms
136
     * @param int $cacheLife Amount of seconds for cache(default 3600 - 1 hour)
137
     * @param string $accessibility Cache-control accessibility value(default public)
138
     */
139
    public function cached($cacheLife = 3600, $accessibility = 'public')
140
    {
141
        static $cached;
142
        // Protect sending cached headers once
143
        if (!isset($cached) or $cached !== true) {
144
            header('Expires: ' . gmdate('D, d M Y H:i:s T', time() + $cacheLife));
145
            header('Cache-Control: ' . $accessibility . ', max-age=' . $cacheLife);
146
            header('Pragma: cache');
147
148
            $cached = true;
149
        }
150
    }
151
152
    /**
153
     * Set asynchronous mode.
154
     * This mode will not output template and will just path everything that
155
     * was outputted to client.
156
     *
157
     * @param bool $async True to switch to asynchronous output mode
158
     *
159
     * @return $this Chaining
160
     */
161
    public function async($async)
162
    {
163
        $this->async = $async;
164
165
        return $this;
166
    }
167
168
    /** @see iCore::path() */
169
    public function path($path = null)
170
    {
171
        // Если передан аргумент
172
        if (func_num_args()) {
173
            // Сформируем новый относительный путь к главному шаблону системы
174
            $this->template_path = $path . $this->template_path;
175
176
            // Сохраним относительный путь к Веб-приложению
177
            $this->system_path = $path;
178
179
            // Продолжил цепирование
180
            return $this;
181
        }
182
183
        // Вернем текущее значение
184
        return $this->system_path;
185
    }
186
187
    /**    @see iModule::active() */
188
    public function &active(iModule &$module = null)
189
    {
190
        // Сохраним старый текущий модуль
191
        $old = &$this->active;
192
193
        // Если передано значение модуля для установки как текущий - проверим и установим его
194
        if (isset($module)) {
195
            $this->active = &$module;
196
        }
197
198
        // Вернем значение текущего модуля
199
        return $old;
200
    }
201
202
    /**
203
     * Retrieve module instance by identifier.
204
     *
205
     * @param string|null $module Module identifier
206
     *
207
     * @return null|Module Found or active module
208
     */
209
    public function &module($module = null)
210
    {
211
        $return = null;
212
213
        // Ничего не передано - вернем текущуй модуль системы
214
        if (!isset($module) && isset($this->active)) {
215
            $return = &$this->active;
216
        } elseif (is_object($module)) {
217
            $return = &$module;
218
        } elseif (is_string($module)) {
219
            $return = $this->container->get($module);
220
        }
221
222
        // Ничего не получилось вернем ошибку
223
        if ($return === null) {
224
            e('Не возможно получить модуль(##) системы', E_SAMSON_CORE_ERROR, array($module));
0 ignored issues
show
Deprecated Code introduced by
The function e() has been deprecated with message: Use custom exceptions

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
225
        }
226
227
        return $return;
228
    }
229
230
    /**
231
     * Unload module from core.
232
     *
233
     * @param string $moduleID Module identifier
234
     */
235
    public function unload($moduleID)
236
    {
237
        if (isset($this->module_stack[$moduleID])) {
238
            unset($this->module_stack[$moduleID]);
239
        }
240
    }
241
242
    /**
243
     * Insert generic html template tags and data
244
     *
245
     * @param string $templateHtml Generated HTML
246
     *
247
     * @deprecated Must be moved to a new HTML output object
248
     * @return mixed Changed HTML template
249
     */
250
    public function generateTemplate(&$templateHtml)
251
    {
252
        // Добавим путь к ресурсам для браузера
253
        $headHtml = "\n" . '<base href="' . url()->base() . '">';
254
        // Добавим отметку времени для JavaScript
255
        $headHtml .= "\n" . '<script type="text/javascript">var __SAMSONPHP_STARTED = new Date().getTime();</script>';
256
257
        // Добавим поддержку HTML для старых IE
258
        $headHtml .= "\n" . '<!--[if lt IE 9]>';
259
        $headHtml .= "\n" . '<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>';
260
        $headHtml .= "\n" . '<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>';
261
        $headHtml .= "\n" . '<![endif]-->';
262
263
        // Выполним вставку главного тега <base> от которого зависят все ссылки документа
264 2
        // также подставим МЕТА-теги для текущего модуля и сгенерированный минифицированный CSS
265
        $templateHtml = str_ireplace('<head>', '<head>' . $headHtml, $templateHtml);
266
267
        // Вставим указатель JavaScript ресурсы в конец HTML документа
268
        $templateHtml = str_ireplace('</html>', '</html>' . __SAMSON_COPYRIGHT, $templateHtml);
269
270
        return $templateHtml;
271 2
    }
272
273
    /**
274 2
     * Start SamsonPHP framework.
275
     *
276
     * @param string $default Default module identifier
277
     *
278 2
     * @throws ViewPathNotFound
279
     */
280 2
    public function start($default)
281
    {
282 2
        // TODO: Change ExternalModule::init() signature
283 2
        // Fire core started event
284
        Event::fire('core.started');
285
286 2
        // TODO: Does not see why it should be here
287
        // Set main template path
288 2
        $this->template($this->template_path);
289
290 2
        // Security layer
291
        $securityResult = true;
292
        // Fire core security event
293
        Event::fire('core.security', array(&$this, &$securityResult));
294
295 2
        /** @var mixed $result External route controller action result */
296
        $result = false;
297
298
        // If we have passed security application layer
299
        if ($securityResult) {
300
            // Fire core routing event - go to routing application layer
301
            Event::signal('core.routing', array(&$this, &$result, $default));
302
        }
303
304
        // If no one has passed back routing callback
305
        if (!isset($result) || $result === false) {
306
            // Fire core e404 - routing failed event
307
            $result = Event::signal('core.e404', array(url()->module, url()->method));
308
        }
309
310
        // Response
311
        $output = '';
312
313
        // If this is not asynchronous response and controller has been executed
314
        if (!$this->async && ($result !== false)) {
315
            // Store module data
316
            $data = $this->active->toView();
317
318
            // Render main template
319
            $output = $this->render($this->template_path, $data);
320 2
321
            // Fire after render event
322
            Event::fire('core.rendered', array(&$output));
323 2
        }
324
325
        // Output results to client
326 2
        echo $output;
327
328
        // Fire ended event
329 2
        Event::fire('core.ended', array(&$output));
330
    }
331
332 2
    /**	@see iCore::template() */
333
    public function template( $template = NULL, $absolutePath = false )
0 ignored issues
show
Coding Style introduced by
Expected 0 spaces between opening bracket and argument "$template"; 1 found
Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
Coding Style introduced by
Expected 0 spaces between argument "$absolutePath" and closing bracket; 1 found
Loading history...
334
    {
335 2
        // Если передан аргумент
336
        if( func_num_args() ){
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
337
            $this->template_path = ($absolutePath)?$template:$this->active->path().$template;
338 2
        }
339
340
        // Аргументы не переданы - вернем текущий путь к шаблону системы
341
        return $this->template_path;
342
    }
343
344
    /**
345
     * Render file to a buffer.
346
     *
347
     * @param string $view Path to file
348
     * @param array  $data Collection of variables to path to file
349
     *
350
     * @return string Rendered file contents
351
     * @throws ViewPathNotFound
352 7
     */
353
    public function render($view, $data = array())
354 7
    {
355
        // TODO: Make rendering as external system, to split up these 3 rendering options
356 7
357
        // Объявить ассоциативный массив переменных в данном контексте
358
        if (is_array($data)) {
359
            extract($data);
360
        }
361
362
        // Начать вывод в буффер
363
        ob_start();
364
365
        // Path to another template view, by default we are using default template folder path,
366
        // for meeting first condition
367
        $templateView = $view;
368
369
        if (locale() != SamsonLocale::DEF) {
370
            // Modify standard view path with another template
371
            $templateView = str_replace(__SAMSON_VIEW_PATH, __SAMSON_VIEW_PATH . locale() . '/', $templateView);
372
        }
373
374
        // Depending on core view rendering model
375
        switch ($this->render_mode) {
376
            // Standard algorithm for view rendering
377
            case self::RENDER_STANDART:
378
                // Trying to find another template path, by default it's an default template path
379
                if (file_exists($templateView)) {
380
                    include($templateView);
381
                } elseif (file_exists($view)) {
382
                    // If another template wasn't found - we will use default template path
383
                    include($view);
384
                } else { // Error no template view was found
385
                    throw(new ViewPathNotFound($view));
386
                }
387
                break;
388
389
            // View rendering algorithm from array of view variables
390
            case self::RENDER_VARIABLE:
391
                // Collection of views
392
                $views = &$GLOBALS['__compressor_files'];
393
                // Trying to find another template path, by default it's an default template path
394
                if (isset($views[$templateView])) {
395
                    eval(' ?>' . $views[$templateView] . '<?php ');
396
                } elseif (isset($views[$view])) {
397
                    // If another template wasn't found - we will use default template path
398
                    eval(' ?>' . $views[$view] . '<?php ');
399
                } else { // Error no template view was found
400
                    throw(new ViewPathNotFound($view));
401
                }
402
                break;
403 2
        }
404
405
        // Получим данные из буффера вывода
406 2
        $html = ob_get_contents();
407
408
        // Очистим буффер
409 2
        ob_end_clean();
410 2
411 2
        // Fire core render event
412
        Event::fire('core.render', array(&$html, &$data, &$this->active));
413
414 2
        ////elapsed('End rendering '.$__view);
415
        return $html;
416
    }
417
418
    //[PHPCOMPRESSOR(remove,start)]
419
420
    /**
421
     * Load system from composer.json
422
     * @param string $dependencyFilePath Path to dependencies file
423
     * @return $this Chaining
424
     */
425
    public function composer($dependencyFilePath = null)
426
    {
427
        $composerModules = array();
428
429
        Event::fire(
430
            'core.composer.create',
431
            array(
432
                &$composerModules,
433
                isset($dependencyFilePath) ? $dependencyFilePath : $this->system_path,
434
                array(
435
                    'vendorsList' => array('samsonphp/', 'samsonos/', 'samsoncms/', 'samsonjavascript/'),
436
                    'ignoreKey' => 'samson_module_ignore',
437
                    'includeKey' => 'samson_module_include'
438
                )
439
            )
440
        );
441
442
        $modulesToLoad = [];
443
444
        // Iterate requirements
445
        foreach ($composerModules as $requirement => $parameters) {
446
            $moduleName = $this->load(__SAMSON_CWD__ . __SAMSON_VENDOR_PATH . $requirement,
447
            array_merge(
448
                is_array($parameters) ? $parameters : array($parameters),
449
                array('module_id' => $requirement)
450
            ));
451
452
            $modulesToLoad[$moduleName] = $parameters;
453
        }
454
455
        $localModulesPath = '../src';
456
        ResourceMap::get('cache');
457
        // TODO: Nested modules relation
458
        for ($i = 0; $i < 2; $i++) {
459
            $resourceMap = ResourceMap::get($localModulesPath);
460
461
            foreach ($resourceMap->modules as $moduleFile) {
462
                $modulePath = str_replace(realpath($localModulesPath), '', $moduleFile[1]);
463
                $modulePath = explode('/', $modulePath);
464
                $modulePath = $localModulesPath . '/' . $modulePath[1];
465
                $moduleName = $this->load($modulePath, $parameters);
0 ignored issues
show
Bug introduced by
The variable $parameters seems to be defined by a foreach iteration on line 445. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
466
                $modulesToLoad[$moduleName] = $parameters;
467
            }
468
        }
469
470
        //$this->active = new VirtualModule($this->system_path, $this->map, $this, 'local');
471
472
        // Create local module and set it as active
473
        $this->createMetadata(VirtualModule::class, 'local', $this->system_path);
474
475
        // TODO: This should be changed to one single logic
476
        // Require all local module model files
477
        foreach ($this->map->models as $model) {
478
            // TODO: Why have to require once?
479
            require_once($model);
480
        }
481
482
        // Create all local modules
483
        foreach ($this->map->controllers as $controller) {
484
            // Require class into PHP
485
            require($controller);
486
487
            //new VirtualModule($this->system_path, $this->map, $this, basename($controller, '.php'));
488
489
            $this->createMetadata(VirtualModule::class, basename($controller, '.php'), $this->system_path);
490
        }
491
492
        $this->createMetadata(get_class($this), get_class($this), $this->system_path);
493
494
        $metadata = new ClassMetadata();
495
        $metadata->className = get_class($this);
496
        $metadata->name = get_class($this);
497
        $metadata->scopes[] = Builder::SCOPE_SERVICES;
498
        $metadata->methodsMetadata['__construct'] = new MethodMetadata($metadata);
499
        $metadata->methodsMetadata['__construct']->dependencies['map'] = ResourceMap::class;
500
501
        $this->metadataCollection[$metadata->name] = $metadata;
502
503
        $metadata = new ClassMetadata();
504
        $metadata->className = ResourceMap::class;
505
        $metadata->name = ResourceMap::class;
506
        $metadata->scopes[] = Builder::SCOPE_SERVICES;
507
508
        $this->metadataCollection[$metadata->name] = $metadata;
509
510
        $builder = new Builder(new Generator(), $this->metadataCollection);
0 ignored issues
show
Unused Code introduced by
$builder is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
511
        $containerPath = $this->path().'www/cache/Container.php';
512
513
        //file_put_contents($containerPath, $builder->build());
514
515
        require_once($containerPath);
516
517
        $this->container = new \Container();
0 ignored issues
show
Documentation Bug introduced by
It seems like new \Container() of type object<Container> is incompatible with the declared type object<samsonframework\di\ContainerInterface> of property $container.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
518
        $containerReflection = new \ReflectionClass(get_class($this->container));
519
        $serviceProperty = $containerReflection->getProperty('servicesInstances');
520
        $serviceProperty->setAccessible(true);
521
        $containerServices = $serviceProperty->getValue($this->container);
522
        $containerServices[get_class($this)] = $this;
523
        $serviceProperty->setValue(null, $containerServices);
524
        $serviceProperty->setAccessible(false);
525
526
        foreach ($modulesToLoad as $name => $parameters) {
527
            $instance = $this->container->get($name);
528
            $this->initModule($instance, $parameters);
529
        }
530
531
        $this->active = $this->container->getLocal();
532
533
        return $this;
534
    }
535
536
    /**
537
     * Initialize module.
538
     *
539
     * @param ExternalModule $instance           Module instance for initialization
540
     * @param array          $composerParameters Collection of extra parameters from composer.json file
541
     */
542
    protected function initModule($instance, $composerParameters)
543
    {
544
        $identifier = $instance->id();
545
546
        // Set composer parameters
547
        $instance->composerParameters = $composerParameters;
548
549
        // TODO: Change event signature to single approach
550
        // Fire core module load event
551
        Event::fire('core.module_loaded', array($identifier, &$instance));
552
553
        // Signal core module configure event
554
        Event::signal('core.module.configure', array(&$instance, $identifier));
555
556
        // Call module preparation handler
557
        if (!$instance->prepare()) {
558 7
            // Handle module failed preparing
559
        }
560
561 7
        // Trying to find parent class for connecting to it to use View/Controller inheritance
562
        $parentClass = get_parent_class($instance);
563
        if (!in_array($parentClass,
564 7
            array('samson\core\ExternalModule', 'samson\core\CompressableExternalModule'))
565
        ) {
566
            // Переберем загруженные в систему модули
567 7
            foreach ($this->module_stack as &$m) {
568
                // Если в систему был загружен модуль с родительским классом
569
                if (get_class($m) === $parentClass) {
570 7
                    $instance->parent = &$m;
571
                    //elapsed('Parent connection for '.$moduleClass.'('.$connector->uid.') with '.$parent_class.'('.$m->uid.')');
572
                }
573 7
            }
574
        }
575
    }
576 7
577 7
    /**
578
     * Load module from path to core.
579
     *
580
     * @param string $path       Path for module loading
581
     * @param array  $parameters Collection of loading parameters
582
     *
583
     * @return string module name
584
     * @throws \samsonphp\core\exception\CannotLoadModule
585
     */
586
    public function load($path, $parameters = array())
587
    {
588
        $name = '';
589
        // Check path
590
        if (file_exists($path)) {
591
            /** @var ResourceMap $resourceMap Gather all resources from path */
592
            $resourceMap = ResourceMap::get($path);
593
            if (isset($resourceMap->module[0])) {
594
595
                /** @var string $controllerPath Path to module controller file */
596
                $controllerPath = $resourceMap->module[1];
597
598
                /** @var string $moduleClass Name of module controller class to load */
599
                $moduleClass = $resourceMap->module[0];
600
601
                // Require module controller class into PHP
602
                if (file_exists($controllerPath)) {
603
                    require_once($controllerPath);
604
                }
605
606
                // TODO: this should be done via composer autoload file field
607
                // Iterate all function-style controllers and require them
608
                foreach ($resourceMap->controllers as $controller) {
609
                    require_once($controller);
610
                }
611
612
                $reflection = new \ReflectionClass($moduleClass);
613
                $name = $reflection->getDefaultProperties();
614
                $name = $name['id'] ?? str_replace('/', '', $moduleClass);
615
616
                $this->createMetadata($moduleClass, $name, $path);
617
618
                /*$this->initModule(
619
                    new $moduleClass($path, $resourceMap, $this),
620
                    $parameters
621
                );*/
622
            } elseif (is_array($parameters) && isset($parameters['samsonphp_package_compressable']) && ($parameters['samsonphp_package_compressable'] == 1)) {
623
                $name = str_replace('/', '', $parameters['module_id']);
624
                $this->createMetadata(VirtualModule::class, str_replace('/', '', $parameters['module_id']), $path);
625
626
                /*$this->initModule(
627
                    new VirtualModule($path, $resourceMap, $this, str_replace('/', '', $parameters['module_id'])),
628
                    $parameters
629
                );*/
630
            } elseif (count($resourceMap->classes)) {
631
                /** Update for future version: Search classes that implement LoadableInterface */
632
                foreach ($resourceMap->classes as $classPath => $class) {
633
                    // This class implements LoadableInterface LoadableInterface::class
634
                    if (in_array('\samsonframework\core\LoadableInterface', $resourceMap->classData[$classPath]['implements'])) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
635
636
                        $name =  str_replace('/', '', $parameters['module_id']);
637
638
                        $this->createMetadata(VirtualModule::class, str_replace('/', '', $parameters['module_id']), $path);
639
640
                        /*$this->initModule(
641
                            new VirtualModule(
642
                                $path,
643
                                $resourceMap,
644
                                $this,
645
                                str_replace('/', '', $resourceMap->classData[$classPath]['className'])
646
                            ),
647
                            $parameters
648
                        );*/
649
                    }
650
                }
651
            }
652
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
653
        } else {
654
            throw new CannotLoadModule($path);
655
        }
656
657
        return $name;
658
    }
659
    //[PHPCOMPRESSOR(remove,end)]
660
661
    /** Магический метод для десериализации объекта */
662
    public function __wakeup()
663
    {
664
        $this->active = &$this->module_stack['local'];
665
    }
666
667
    /** Магический метод для сериализации объекта */
668
    public function __sleep()
669
    {
670
        return array('module_stack', 'render_mode');
671
    }
672
673
    protected function createMetadata($class, $name, $path)
674
    {
675
        $metadata = new ClassMetadata();
676
        $class = ltrim($class, '\\');
677
        $metadata->className = $class;
678
        $metadata->name = str_replace('/', '', $name ?? $class);
679
        $metadata->scopes[] = Builder::SCOPE_SERVICES;
680
        $metadata->methodsMetadata['__construct'] = new MethodMetadata($metadata);
681
        $metadata->methodsMetadata['__construct']->dependencies['path'] = $path;
682
        $metadata->methodsMetadata['__construct']->dependencies['resources'] = ResourceMap::class;
683
        $metadata->methodsMetadata['__construct']->dependencies['system'] = get_class($this);
684
685
        $this->metadataCollection[$metadata->name] = $metadata;
686
    }
687
}
688