Completed
Push — master ( 94fd5d...0151b6 )
by Vitaly
02:11
created

Module::compressionHandler()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 16
rs 9.4285
cc 3
eloc 6
nc 2
nop 1
1
<?php
2
/**
3
 * Created by Vitaly Iegorov <[email protected]>.
4
 * on 21.02.16 at 14:14
5
 */
6
namespace samsonphp\view;
7
8
use samsonframework\core\ResourcesInterface;
9
use samsonframework\core\SystemInterface;
10
use samsonframework\view\Generator;
11
use samsonphp\Event\Event;
12
13
/**
14
 * SamsonPHP view module
15
 * @package samsonphp\view
16
 */
17
class Module extends \samson\core\ExternalModule implements \samsonframework\core\CompressInterface
18
{
19
    /** View handling events */
20
    const EVENT_VIEW_HANDLER = 'samsonphp.view.handler';
21
    const EVENT_VIEW_COMPRESSION = 'samsonphp.view.compression';
22
23
    /** Pattern for compressing $this->src() calls with resource path */
24
    const SRC_COMPRESSION_PATTERN = '/(<\?=|<\?php\s*echo\s*\(?)\s*\$this->src\(\s*(\'|\")\s*(src|www)\/(?<path>[^\'\"]+)(\'|\")\s*\)\s*\?>/';
25
    /** Pattern for replacing $this->src() calls with controller url */
26
    const SRC_PATTERN = '/(<\?=|<\?php\s*echo\s*\(?)\s*\$this->src\(\s*(\'|\")(?<path>[^\'\"]+)(\'|\")\s*\)\s*\?>/';
27
28
    /** @var string Module identifier */
29
    protected $id = STATIC_RESOURCE_HANDLER;
30
31
    /** @var Generator */
32
    protected $generator;
33
34
    /**
35
     * Module constructor.
36
     *
37
     * @param string             $path
38
     * @param ResourcesInterface $resources
39
     * @param SystemInterface    $system
40
     * @param Generator          $generator
41
     */
42
    public function __construct($path, ResourcesInterface $resources, SystemInterface $system, Generator $generator = null)
43
    {
44
        parent::__construct($path, $resources, $system);
45
46
        $this->generator = isset($generator)
47
            ? $generator
48
            : new Generator(
49
                new \samsonphp\generator\Generator(),
50
                'view',
51
                array('\www', '\view'),
52
                View::class
53
            );
54
55
        // Register View class file autoloader
56
        spl_autoload_register(array($this, 'autoload'));
57
    }
58
59
    /**
60
     * This method should be used to override generic compression logic.
61
     *
62
     * @param mixed $obj Pointer to compressor instance
63
     * @param array|null $code Collection of already compressed code
64
     *
65
     * @return bool False if generic compression needs to be avoided
66
     */
67
    public function beforeCompress(&$obj = null, array &$code = null)
68
    {
69
70
    }
71
72
    /**
73
     * This method is called after generic compression logic has finished.
74
     *
75
     * @param mixed      $obj  Pointer to compressor instance
76
     * @param array|null $code Collection of already compressed code
77
     *
78
     * @return bool False if generic compression needs to be avoided
79
     */
80
    public function afterCompress(&$obj = null, array &$code = null)
81
    {
82
        $this->generator->generate($this->cache_path, array($this, 'compressionHandler'));
0 ignored issues
show
Unused Code introduced by
The call to Generator::generate() has too many arguments starting with array($this, 'compressionHandler').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
83
        // Iterate through generated php code
84
        foreach ($this->generator->metadata as $file => $metadata) {
85
            // Compress generated php code
86
            $obj->compress_php($metadata->generatedPath, $this, $code, $metadata->namespace);
87
        }
88
    }
89
90
    /**
91
     * Generator view code handler.
92
     *
93
     * @param string $viewCode Source view code
94
     *
95
     * @return string Modified view code
96
     */
97
    public function viewHandler($viewCode)
98
    {
99
        // Fire event
100
        Event::fire(self::EVENT_VIEW_HANDLER, array(&$viewCode));
101
102
        // Find all paths to intermediate controller
103
        if (preg_match_all(self::SRC_PATTERN, $viewCode, $matches)) {
104
            for ($i = 0, $size = count($matches['path']); $i < $size; $i++) {
105
                // Remove function call just leave path related to src(for modules) or www(for local)
106
                $viewCode = str_replace($matches[0][$i], '/' . STATIC_RESOURCE_HANDLER . '/?p=' . $matches['path'][$i], $viewCode);
107
            }
108
        }
109
110
        // Return modified view code
111
        return $viewCode;
112
    }
113
114
    /**
115
     * Compression view code handler.
116
     *
117
     * @param string $viewCode Source view code
118
     *
119
     * @return string Modified view code
120
     */
121
    public function compressionHandler($viewCode)
122
    {
123
        // Fire event
124
        Event::fire(self::EVENT_VIEW_COMPRESSION, array(&$viewCode));
125
126
        // Find all pathes to intermediate controller
127
        if (preg_match_all(self::SRC_COMPRESSION_PATTERN, $viewCode, $matches)) {
128
            for ($i = 0, $size = count($matches['path']); $i < $size; $i++) {
129
                // Remove function call just leave path related to src(for modules) or www(for local)
130
                $viewCode = str_replace($matches[0][$i], $matches['path'][$i], $viewCode);
131
            }
132
        }
133
134
        // Return modified view code
135
        return $viewCode;
136
    }
137
138
    /**
139
     * Help autoloading view classes as we know where we store them.
140
     *
141
     * @param string $class View class name for searching
142
     */
143
    public function autoload($class)
144
    {
145
        $classPath = $this->cache_path.str_replace('\\', '/', $class).'.php';
146
        if (file_exists($classPath)) {
147
            require_once($classPath);
148
        }
149
    }
150
151
    /**
152
     * Module preparation stage.
153
     * This function called after module instance creation but before
154
     * initialization stage.
155
     *
156
     * @param array $params Preparation stage parameters
157
     *
158
     * @return bool|void Preparation stage result
159
     */
160
    public function prepare(array $params = array())
161
    {
162
        $this->generator->scan(__SAMSON_CWD__.'/src');
163
        //$this->generator->scan(__SAMSON_CWD__.'/app');
164
        $signature = $this->generator->hash();
165
        if ($this->cache_refresh($signature) != -1) {
166
            $this->generator->generate($this->cache_path, array($this, 'viewHandler'));
0 ignored issues
show
Unused Code introduced by
The call to Generator::generate() has too many arguments starting with array($this, 'viewHandler').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
167
            // Store cache file
168
            file_put_contents($signature, '');
169
        }
170
171
        // Add system static variable to all classes
172
        require_once 'View.php';
173
        View::$system = &$this->system;
174
175
        // Continue parent logic
176
        return parent::prepare($params);
0 ignored issues
show
Unused Code introduced by
The call to ExternalModule::prepare() has too many arguments starting with $params.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
177
    }
178
}
179