Completed
Push — master ( 090f96...5ad5e6 )
by Alexander
02:26
created

WeavingTransformer::transform()   C

Complexity

Conditions 7
Paths 16

Size

Total Lines 39
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 7.0046

Importance

Changes 0
Metric Value
dl 0
loc 39
ccs 21
cts 22
cp 0.9545
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 22
nc 16
nop 1
crap 7.0046
1
<?php
2
declare(strict_types = 1);
3
/*
4
 * Go! AOP framework
5
 *
6
 * @copyright Copyright 2011, Lisachenko Alexander <[email protected]>
7
 *
8
 * This source file is subject to the license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Go\Instrument\Transformer;
13
14
use Go\Aop\Advisor;
15
use Go\Aop\Aspect;
16
use Go\Aop\Framework\AbstractJoinpoint;
17
use Go\Core\AdviceMatcher;
18
use Go\Core\AspectContainer;
19
use Go\Core\AspectKernel;
20
use Go\Core\AspectLoader;
21
use Go\Instrument\ClassLoading\CachePathManager;
22
use Go\ParserReflection\ReflectionEngine;
23
use Go\ParserReflection\ReflectionFile;
24
use Go\ParserReflection\ReflectionFileNamespace;
25
use Go\Proxy\ClassProxy;
26
use Go\Proxy\FunctionProxy;
27
use Go\Proxy\TraitProxy;
28
use ReflectionClass;
29
30
/**
31
 * Main transformer that performs weaving of aspects into the source code
32
 */
33
class WeavingTransformer extends BaseSourceTransformer
34
{
35
36
    /**
37
     * @var AdviceMatcher
38
     */
39
    protected $adviceMatcher;
40
41
    /**
42
     * @var CachePathManager
43
     */
44
    private $cachePathManager;
45
46
    /**
47
     * Instance of aspect loader
48
     *
49
     * @var AspectLoader
50
     */
51
    protected $aspectLoader;
52
53
    /**
54
     * Constructs a weaving transformer
55
     *
56
     * @param AspectKernel $kernel Instance of aspect kernel
57
     * @param AdviceMatcher $adviceMatcher Advice matcher for class
58
     * @param CachePathManager $cachePathManager Cache manager
59
     * @param AspectLoader $loader Loader for aspects
60
     */
61 9
    public function __construct(
62
        AspectKernel $kernel,
63
        AdviceMatcher $adviceMatcher,
64
        CachePathManager $cachePathManager,
65
        AspectLoader $loader
66
    )
67
    {
0 ignored issues
show
Coding Style introduced by
The closing parenthesis and the opening brace of a multi-line function declaration must be on the same line
Loading history...
68 9
        parent::__construct($kernel);
69 9
        $this->adviceMatcher    = $adviceMatcher;
70 9
        $this->cachePathManager = $cachePathManager;
71 9
        $this->aspectLoader     = $loader;
72 9
    }
73
74
    /**
75
     * This method may transform the supplied source and return a new replacement for it
76
     *
77
     * @param StreamMetaData $metadata Metadata for source
78
     * @return string See RESULT_XXX constants in the interface
79
     */
80 9
    public function transform(StreamMetaData $metadata): string
81
    {
82 9
        $totalTransformations = 0;
83
84 9
        $fileName = $metadata->uri;
85
86 9
        $astTree      = ReflectionEngine::parseFile($fileName, $metadata->source);
87 9
        $parsedSource = new ReflectionFile($fileName, $astTree);
88
89
        // Check if we have some new aspects that weren't loaded yet
90 9
        $unloadedAspects = $this->aspectLoader->getUnloadedAspects();
91 9
        if (!empty($unloadedAspects)) {
92
            $this->loadAndRegisterAspects($unloadedAspects);
93
        }
94 9
        $advisors = $this->container->getByTag('advisor');
95
96 9
        $namespaces = $parsedSource->getFileNamespaces();
97 9
        $lineOffset = 0;
98
99 9
        foreach ($namespaces as $namespace) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
100
101 9
            $classes = $namespace->getClasses();
102 9
            foreach ($classes as $class) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
103
104
                // Skip interfaces and aspects
105 8
                if ($class->isInterface() || in_array(Aspect::class, $class->getInterfaceNames())) {
106 2
                    continue;
107
                }
108 6
                $wasClassProcessed = $this->processSingleClass($advisors, $metadata, $class, $lineOffset);
109 6
                $totalTransformations += (integer) $wasClassProcessed;
110
            }
111 9
            $wasFunctionsProcessed = $this->processFunctions($advisors, $metadata, $namespace);
112 9
            $totalTransformations += (integer) $wasFunctionsProcessed;
113
        }
114
115 9
        $result = ($totalTransformations > 0) ? self::RESULT_TRANSFORMED : self::RESULT_ABSTAIN;
116
117 9
        return $result;
118
    }
119
120
    /**
121
     * Performs weaving of single class if needed
122
     *
123
     * @param array|Advisor[] $advisors
124
     * @param StreamMetaData $metadata Source stream information
125
     * @param ReflectionClass $class Instance of class to analyze
126
     * @param integer $lineOffset Current offset, will be updated to store the last position
127
     *
128
     * @return bool True if was class processed, false otherwise
129
     */
130 6
    private function processSingleClass(array $advisors, StreamMetaData $metadata, ReflectionClass $class, &$lineOffset)
131
    {
132 6
        $advices = $this->adviceMatcher->getAdvicesForClass($class, $advisors);
133
134 6
        if (empty($advices)) {
135
            // Fast return if there aren't any advices for that class
136
            return false;
137
        }
138
139
        // Sort advices in advance to keep the correct order in cache
140 6
        foreach ($advices as &$typeAdvices) {
141 6
            foreach ($typeAdvices as &$joinpointAdvices) {
142 6
                if (is_array($joinpointAdvices)) {
143 6
                    $joinpointAdvices = AbstractJoinpoint::sortAdvices($joinpointAdvices);
144
                }
145
            }
146
        }
147
148
        // Prepare new parent name
149 6
        $newParentName = $class->getShortName() . AspectContainer::AOP_PROXIED_SUFFIX;
150
151
        // Replace original class name with new
152 6
        $metadata->source = $this->adjustOriginalClass($class, $metadata->source, $newParentName);
153
154
        // Prepare child Aop proxy
155 6
        $child = $class->isTrait()
156
            ? new TraitProxy($class, $advices)
157 6
            : new ClassProxy($class, $advices);
158
159
        // Set new parent name instead of original
160 6
        $child->setParentName($newParentName);
161 6
        $contentToInclude = $this->saveProxyToCache($class, $child);
162
163
        // Add child to source
164 6
        $lastLine  = $class->getEndLine() + $lineOffset; // returns the last line of class
165 6
        $dataArray = explode("\n", $metadata->source);
166
167 6
        $currentClassArray = array_splice($dataArray, 0, $lastLine);
168 6
        $childClassArray   = explode("\n", $contentToInclude);
169 6
        $lineOffset += count($childClassArray) + 2; // returns LoC for child class + 2 blank lines
170
171 6
        $dataArray = array_merge($currentClassArray, [''], $childClassArray, [''], $dataArray);
172
173 6
        $metadata->source = implode("\n", $dataArray);
174
175 6
        return true;
176
    }
177
178
    /**
179
     * Adjust definition of original class source to enable extending
180
     *
181
     * @param ReflectionClass $class Instance of class reflection
182
     * @param string $source Source code
183
     * @param string $newParentName New name for the parent class
184
     *
185
     * @return string Replaced code for class
186
     */
187 6
    private function adjustOriginalClass($class, $source, $newParentName)
188
    {
189 6
        $type = $class->isTrait() ? 'trait' : 'class';
190 6
        $source = preg_replace(
191 6
            "/{$type}\s+(" . $class->getShortName() . ')(\b)/iS',
192 6
            "{$type} {$newParentName}$2",
193
            $source
194
        );
195 6
        if ($class->isFinal()) {
196
            // Remove final from class, child will be final instead
197 1
            $source = str_replace("final {$type}", $type, $source);
198
        }
199
200 6
        return $source;
201
    }
202
203
    /**
204
     * Performs weaving of functions in the current namespace
205
     *
206
     * @param array|Advisor[] $advisors List of advisors
207
     * @param StreamMetaData $metadata Source stream information
208
     * @param ReflectionFileNamespace $namespace Current namespace for file
209
     *
210
     * @return boolean True if functions were processed, false otherwise
211
     */
212 9
    private function processFunctions(array $advisors, StreamMetaData $metadata, $namespace)
213
    {
214 9
        static $cacheDirSuffix = '/_functions/';
215
216 9
        $wasProcessedFunctions = false;
217 9
        $functionAdvices = $this->adviceMatcher->getAdvicesForFunctions($namespace, $advisors);
218 9
        $cacheDir        = $this->cachePathManager->getCacheDir();
219 9
        if (!empty($functionAdvices) && $cacheDir) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cacheDir of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
220
            $cacheDir = $cacheDir . $cacheDirSuffix;
221
            $fileName = str_replace('\\', '/', $namespace->getName()) . '.php';
222
223
            $functionFileName = $cacheDir . $fileName;
224
            if (!file_exists($functionFileName) || !$this->container->isFresh(filemtime($functionFileName))) {
225
                $dirname = dirname($functionFileName);
226
                if (!file_exists($dirname)) {
227
                    mkdir($dirname, $this->options['cacheFileMode'], true);
228
                }
229
                $source = new FunctionProxy($namespace, $functionAdvices);
230
                file_put_contents($functionFileName, $source, LOCK_EX);
231
                // For cache files we don't want executable bits by default
232
                chmod($functionFileName, $this->options['cacheFileMode'] & (~0111));
233
            }
234
            $content = 'include_once AOP_CACHE_DIR . ' . var_export($cacheDirSuffix . $fileName, true) . ';' . PHP_EOL;
235
            $metadata->source .= $content;
236
            $wasProcessedFunctions = true;
237
        }
238
239 9
        return $wasProcessedFunctions;
240
    }
241
242
    /**
243
     * Save AOP proxy to the separate file anr returns the php source code for inclusion
244
     *
245
     * @param ReflectionClass $class Original class reflection
246
     * @param string|ClassProxy $child
247
     *
248
     * @return string
249
     */
250 6
    private function saveProxyToCache($class, $child): string
251
    {
252 6
        static $cacheDirSuffix = '/_proxies/';
253
254 6
        $cacheDir = $this->cachePathManager->getCacheDir();
255
256
        // Without cache we should rewrite original file
257 6
        if (!$cacheDir) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cacheDir of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
258 6
            return (string) $child;
259
        }
260
        $cacheDir = $cacheDir . $cacheDirSuffix;
261
        $fileName = str_replace($this->options['appDir'] . DIRECTORY_SEPARATOR, '', $class->getFileName());
262
263
        $proxyFileName = $cacheDir . $fileName;
264
        $dirname       = dirname($proxyFileName);
265
        if (!file_exists($dirname)) {
266
            mkdir($dirname, $this->options['cacheFileMode'], true);
267
        }
268
269
        $body      = '<?php' . PHP_EOL;
270
        $namespace = $class->getNamespaceName();
271
        if ($namespace) {
272
            $body .= "namespace {$namespace};" . PHP_EOL . PHP_EOL;
273
        }
274
275
        $refNamespace = new ReflectionFileNamespace($class->getFileName(), $namespace);
276
        foreach ($refNamespace->getNamespaceAliases() as $fqdn => $alias) {
277
            $body .= "use {$fqdn} as {$alias};" . PHP_EOL;
278
        }
279
280
        $body .= $child;
281
        file_put_contents($proxyFileName, $body, LOCK_EX);
282
        // For cache files we don't want executable bits by default
283
        chmod($proxyFileName, $this->options['cacheFileMode'] & (~0111));
284
285
        return 'include_once AOP_CACHE_DIR . ' . var_export($cacheDirSuffix . $fileName, true) . ';' . PHP_EOL;
286
    }
287
288
    /**
289
     * Utility method to load and register unloaded aspects
290
     *
291
     * @param array $unloadedAspects List of unloaded aspects
292
     */
293
    private function loadAndRegisterAspects(array $unloadedAspects)
294
    {
295
        foreach ($unloadedAspects as $unloadedAspect) {
296
            $this->aspectLoader->loadAndRegister($unloadedAspect);
297
        }
298
    }
299
}
300