Completed
Push — master ( 48758c...cfe763 )
by Vitaly
03:33
created

Router::getAssets()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 3
eloc 8
c 2
b 0
f 1
nc 3
nop 1
dl 0
loc 21
ccs 0
cts 10
cp 0
crap 12
rs 9.3142
1
<?php
2
namespace samsonphp\resource;
3
4
use samson\core\ExternalModule;
5
use samsonphp\event\Event;
6
7
/**
8
 * Resource router for serving static resource from unreachable web-root paths.
9
 *
10
 * TODO: Validate old files that do not exists anymore to remove them
11
 *
12
 * @author Vitaly Iegorov <[email protected]>
13
 */
14
class Router extends ExternalModule
15
{
16
    /** @deprecated Use E_MODULES */
17
    const EVENT_START_GENERATE_RESOURCES = 'resourcer.modulelist';
18
    /** Event for modifying modules */
19
    const E_MODULES = 'resourcer.modulelist';
20
    /** Event for resources preloading */
21
    const E_RESOURCE_PRELOAD = ResourceManager::E_ANALYZE;
22
    /** Event for resources compiling */
23
    const E_RESOURCE_COMPILE = ResourceManager::E_COMPILE;
24
    /** Event when recourse management is finished */
25
    const E_FINISHED = 'resourcer.finished';
26
27
    /** @deprecated Identifier */
28
    protected $id = STATIC_RESOURCE_HANDLER;
29
30
    /** @var array Assets cache */
31
    protected $cache = [];
32
33
    /** @var array Template markers for inserting assets */
34
    protected $templateMarkers = [
35
        'css' => '</head>',
36
        'js' => '</body>'
37
    ];
38
    /** @var array Collection of static resources */
39
    protected $resources = [];
40
41
    /** @var array Collection of static resource URLs */
42
    protected $resourceUrls = [];
43
44
    /**
45
     * Module initialization stage.
46
     *
47
     * @see ModuleConnector::init()
48
     *
49
     * @param array $params Initialization parameters
50
     *
51
     * @return bool True if resource successfully initialized
52
     */
53
    public function init(array $params = array())
54
    {
55
        // Subscribe for CSS handling
56
        Event::subscribe(self::E_RESOURCE_COMPILE, [new CSS(), 'compile']);
57
58
        // Subscribe to core template rendering event
59
        Event::subscribe('core.rendered', [$this, 'renderTemplate']);
60
61
        $resourceManager = new ResourceManager(new FileManager());
62
        $resourceManager::$cacheRoot = $this->cache_path;
63
        $resourceManager::$webRoot = getcwd();
64
        $resourceManager::$projectRoot = dirname($resourceManager::$webRoot) . '/';
65
66
        // Get loaded modules
67
        $moduleList = $this->system->module_stack;
0 ignored issues
show
Bug introduced by
Accessing module_stack on the interface samsonframework\core\SystemInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
68
69
        // Event for modification of resource list
70
        Event::fire(self::E_MODULES, [&$moduleList]);
71
72
        $appResourcePaths = $this->getAssets($moduleList);
73
74
        // Get assets
75
        $this->resources = $resourceManager->manage($appResourcePaths);
76
77
        // Fire completion event
78
        Event::fire(self::E_FINISHED, [&$this->resources]);
79
80
        // Get asset URLs
81
        $this->resourceUrls = array_map([$this, 'getAssetCachedUrl'], $this->resources);
82
83
        // Continue parent initialization
84
        return parent::init($params);
85
    }
86
87
    /**
88
     * Get asset files from modules.
89
     *
90
     * @param array $moduleList Collection of modules
91
     *
92
     * @return array Resources paths
93
     */
94
    private function getAssets($moduleList)
95
    {
96
        $projectRoot = dirname(getcwd()) . '/';
97
98
        // Add resource paths
99
        $paths = [];
100
        foreach ($moduleList as $module) {
101
            /**
102
             * We need to exclude project root because vendor folder will be scanned
103
             * and all assets from there would be added.
104
             */
105
            if ($module->path() !== $projectRoot) {
106
                $paths[] = $module->path();
107
            }
108
        }
109
110
        // Add web-root as last path
111
        $paths[] = getcwd();
112
113
        return $paths;
114
    }
115
116
    /**
117
     * Template rendering handler by injecting static assets url
118
     * in appropriate.
119
     *
120
     * @param $view
121
     *
122
     * @return mixed
123
     */
124
    public function renderTemplate(&$view)
125
    {
126
        foreach ($this->resourceUrls as $type => $urls) {
127
            if (array_key_exists($type, $this->templateMarkers)) {
128
                // Replace template marker by type with collection of links to resources of this type
129
                $view = str_ireplace(
130
                    $this->templateMarkers[$type],
131
                    implode("\n", array_map(function ($value) use ($type) {
132
                        if ($type === 'css') {
133
                            return '<link type="text/css" rel="stylesheet" property="stylesheet" href="' . $value . '">';
134
                        } elseif ($type === 'js') {
135
                            return '<script type="text/javascript" src="' . $value . '"></script>';
136
                        }
137
                    }, $urls)) . "\n" . $this->templateMarkers[$type],
138
                    $view
139
                );
140
            }
141
        }
142
143
        return $view;
144
    }
145
146
    /**
147
     * Get cached asset URL.
148
     *
149
     * @param string $cachedAsset Full path to cached asset
150
     *
151
     * @return mixed Cached asset URL
152
     */
153
    private function getAssetCachedUrl($cachedAsset)
154
    {
155
        return str_replace(ResourceManager::$webRoot, '', $cachedAsset);
156
    }
157
}
158