Completed
Branch feature/goaop-parser (08838c)
by Alexander
03:32
created

WeavingTransformer   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 264
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Test Coverage

Coverage 68.37%

Importance

Changes 13
Bugs 4 Features 0
Metric Value
wmc 29
c 13
b 4
f 0
lcom 1
cbo 12
dl 0
loc 264
ccs 67
cts 98
cp 0.6837
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
B transform() 0 40 6
B processSingleClass() 0 47 6
A adjustOriginalClass() 0 15 3
B processFunctions() 0 27 6
B saveProxyToCache() 0 35 5
A loadAndRegisterAspects() 0 6 2
1
<?php
2
/*
3
 * Go! AOP framework
4
 *
5
 * @copyright Copyright 2011, Lisachenko Alexander <[email protected]>
6
 *
7
 * This source file is subject to the license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace Go\Instrument\Transformer;
12
13
use Go\Aop\Advisor;
14
use Go\Aop\Aspect;
15
use Go\Aop\Framework\AbstractJoinpoint;
16
use Go\Core\AdviceMatcher;
17
use Go\Core\AspectContainer;
18
use Go\Core\AspectKernel;
19
use Go\Core\AspectLoader;
20
use Go\Instrument\ClassLoading\CachePathManager;
21
use Go\ParserReflection\ReflectionEngine;
22
use Go\ParserReflection\ReflectionFile;
23
use Go\ParserReflection\ReflectionFileNamespace;
24
use Go\Proxy\ClassProxy;
25
use Go\Proxy\FunctionProxy;
26
use Go\Proxy\TraitProxy;
27
use ReflectionClass;
28
29
/**
30
 * Main transformer that performs weaving of aspects into the source code
31
 */
32
class WeavingTransformer extends BaseSourceTransformer
33
{
34
35
    /**
36
     * @var AdviceMatcher
37
     */
38
    protected $adviceMatcher;
39
40
    /**
41
     * @var CachePathManager
42
     */
43
    private $cachePathManager;
44
45
    /**
46
     * Instance of aspect loader
47
     *
48
     * @var AspectLoader
49
     */
50
    protected $aspectLoader;
51
52
    /**
53
     * Constructs a weaving transformer
54
     *
55
     * @param AspectKernel $kernel Instance of aspect kernel
56
     * @param AdviceMatcher $adviceMatcher Advice matcher for class
57
     * @param CachePathManager $cachePathManager Cache manager
58
     * @param AspectLoader $loader Loader for aspects
59
     */
60 8
    public function __construct(
61
        AspectKernel $kernel,
62
        AdviceMatcher $adviceMatcher,
63
        CachePathManager $cachePathManager,
64
        AspectLoader $loader
65
    )
0 ignored issues
show
Coding Style introduced by
There must be a single space between the closing parenthesis and the opening brace of a multi-line function declaration; found newline
Loading history...
66
    {
67 8
        parent::__construct($kernel);
68 8
        $this->adviceMatcher    = $adviceMatcher;
69 8
        $this->cachePathManager = $cachePathManager;
70 8
        $this->aspectLoader     = $loader;
71 8
    }
72
73
    /**
74
     * This method may transform the supplied source and return a new replacement for it
75
     *
76
     * @param StreamMetaData $metadata Metadata for source
77
     * @return boolean Return false if transformation should be stopped
78
     */
79 8
    public function transform(StreamMetaData $metadata)
80
    {
81 8
        $totalTransformations = 0;
82
83 8
        $fileName = $metadata->uri;
84
85 8
        $astTree      = ReflectionEngine::parseFile($fileName, $metadata->source);
86 8
        $parsedSource = new ReflectionFile($fileName, $astTree);
87
88
        // Check if we have some new aspects that weren't loaded yet
89 8
        $unloadedAspects = $this->aspectLoader->getUnloadedAspects();
90 8
        if (!empty($unloadedAspects)) {
91
            $this->loadAndRegisterAspects($unloadedAspects);
92
        }
93 8
        $advisors = $this->container->getByTag('advisor');
94
95
        /** @var $namespaces ReflectionFileNamespace[] */
96 8
        $namespaces = $parsedSource->getFileNamespaces();
97 8
        $lineOffset = 0;
98
99 8
        foreach ($namespaces as $namespace) {
100
101
            /** @var $classes ReflectionClass[] */
102 8
            $classes = $namespace->getClasses();
103 8
            foreach ($classes as $class) {
104
105
                // Skip interfaces and aspects
106 7
                if ($class->isInterface() || in_array(Aspect::class, $class->getInterfaceNames())) {
107 2
                    continue;
108
                }
109 5
                $wasClassProcessed = $this->processSingleClass($advisors, $metadata, $class, $lineOffset);
110 5
                $totalTransformations += (integer) $wasClassProcessed;
111
            }
112 8
            $wasFunctionsProcessed = $this->processFunctions($advisors, $metadata, $namespace);
113 8
            $totalTransformations += (integer) $wasFunctionsProcessed;
114
        }
115
116
        // If we return false this will indicate no more transformation for following transformers
117 8
        return $totalTransformations > 0;
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 5
    private function processSingleClass(array $advisors, StreamMetaData $metadata, ReflectionClass $class, &$lineOffset)
131
    {
132 5
        $advices = $this->adviceMatcher->getAdvicesForClass($class, $advisors);
133
134 5
        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 5
        foreach ($advices as &$typeAdvices) {
141 5
            foreach ($typeAdvices as &$joinpointAdvices) {
142 5
                if (is_array($joinpointAdvices)) {
143 5
                    $joinpointAdvices = AbstractJoinpoint::sortAdvices($joinpointAdvices);
144
                }
145
            }
146
        }
147
148
        // Prepare new parent name
149 5
        $newParentName = $class->getShortName() . AspectContainer::AOP_PROXIED_SUFFIX;
150
151
        // Replace original class name with new
152 5
        $metadata->source = $this->adjustOriginalClass($class, $metadata->source, $newParentName);
153
154
        // Prepare child Aop proxy
155 5
        $child = $class->isTrait()
156
            ? new TraitProxy($class, $advices)
157 5
            : new ClassProxy($class, $advices);
158
159
        // Set new parent name instead of original
160 5
        $child->setParentName($newParentName);
161 5
        $contentToInclude = $this->saveProxyToCache($class, $child);
162
163
        // Add child to source
164 5
        $lastLine  = $class->getEndLine() + $lineOffset; // returns the last line of class
165 5
        $dataArray = explode("\n", $metadata->source);
166
167 5
        $currentClassArray = array_splice($dataArray, 0, $lastLine);
168 5
        $childClassArray   = explode("\n", $contentToInclude);
169 5
        $lineOffset += count($childClassArray) + 2; // returns LoC for child class + 2 blank lines
170
171 5
        $dataArray = array_merge($currentClassArray, array(''), $childClassArray, array(''), $dataArray);
172
173 5
        $metadata->source = implode("\n", $dataArray);
174
175 5
        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 5
    private function adjustOriginalClass($class, $source, $newParentName)
188
    {
189 5
        $type = $class->isTrait() ? 'trait' : 'class';
190 5
        $source = preg_replace(
191 5
            "/{$type}\s+(" . $class->getShortName() . ')(\b)/iS',
192 5
            "{$type} {$newParentName}$2",
193
            $source
194
        );
195 5
        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 5
        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 8
    private function processFunctions(array $advisors, StreamMetaData $metadata, $namespace)
213
    {
214 8
        static $cacheDirSuffix = '/_functions/';
215
216 8
        $wasProcessedFunctions = false;
217 8
        $functionAdvices = $this->adviceMatcher->getAdvicesForFunctions($namespace, $advisors);
218 8
        $cacheDir        = $this->cachePathManager->getCacheDir();
219 8
        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, 0770, true);
228
                }
229
                $source = new FunctionProxy($namespace, $functionAdvices);
230
                file_put_contents($functionFileName, $source);
231
            }
232
            $content = 'include_once AOP_CACHE_DIR . ' . var_export($cacheDirSuffix . $fileName, true) . ';' . PHP_EOL;
233
            $metadata->source .= $content;
234
            $wasProcessedFunctions = true;
235
        }
236
237 8
        return $wasProcessedFunctions;
238
    }
239
240
    /**
241
     * Save AOP proxy to the separate file anr returns the php source code for inclusion
242
     *
243
     * @param ReflectionClass $class Original class reflection
244
     * @param string|ClassProxy $child
245
     *
246
     * @return string
247
     */
248 5
    private function saveProxyToCache($class, $child)
249
    {
250 5
        static $cacheDirSuffix = '/_proxies/';
251
252 5
        $cacheDir = $this->cachePathManager->getCacheDir();
253
254
        // Without cache we should rewrite original file
255 5
        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...
256 5
            return $child;
257
        }
258
        $cacheDir = $cacheDir . $cacheDirSuffix;
259
        $fileName = str_replace($this->options['appDir'] . DIRECTORY_SEPARATOR, '', $class->getFileName());
260
261
        $proxyFileName = $cacheDir . $fileName;
262
        $dirname       = dirname($proxyFileName);
263
        if (!file_exists($dirname)) {
264
            mkdir($dirname, 0770, true);
265
        }
266
267
        $body      = '<?php' . PHP_EOL;
268
        $namespace = $class->getNamespaceName();
269
        if ($namespace) {
270
            $body .= "namespace {$namespace};" . PHP_EOL . PHP_EOL;
271
        }
272
273
        $refNamespace = new ReflectionFileNamespace($class->getFileName(), $namespace);
274
        foreach ($refNamespace->getNamespaceAliases() as $fqdn => $alias) {
275
            $body .= "use {$fqdn} as {$alias};" . PHP_EOL;
276
        }
277
278
        $body .= $child;
279
        file_put_contents($proxyFileName, $body);
280
281
        return 'include_once AOP_CACHE_DIR . ' . var_export($cacheDirSuffix . $fileName, true) . ';' . PHP_EOL;
282
    }
283
284
    /**
285
     * Utility method to load and register unloaded aspects
286
     *
287
     * @param array $unloadedAspects List of unloaded aspects
288
     */
289
    private function loadAndRegisterAspects(array $unloadedAspects)
290
    {
291
        foreach ($unloadedAspects as $unloadedAspect) {
292
            $this->aspectLoader->loadAndRegister($unloadedAspect);
293
        }
294
    }
295
}
296