Completed
Push — master ( 345cbf...06ef8e )
by Alexander
02:03
created

WeavingTransformer   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 254
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 78.05%

Importance

Changes 0
Metric Value
wmc 30
lcom 1
cbo 13
dl 0
loc 254
ccs 64
cts 82
cp 0.7805
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
C transform() 0 32 7
B processSingleClass() 0 40 6
B adjustOriginalClass() 0 21 5
B processFunctions() 0 34 5
B saveProxyToCache() 0 31 4
A loadAndRegisterAspects() 0 6 2
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\ReflectionClass;
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
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 9
    public function __construct(
61
        AspectKernel $kernel,
62
        AdviceMatcher $adviceMatcher,
63
        CachePathManager $cachePathManager,
64
        AspectLoader $loader
65
    ) {
66 9
        parent::__construct($kernel);
67 9
        $this->adviceMatcher    = $adviceMatcher;
68 9
        $this->cachePathManager = $cachePathManager;
69 9
        $this->aspectLoader     = $loader;
70 9
    }
71
72
    /**
73
     * This method may transform the supplied source and return a new replacement for it
74
     *
75
     * @param StreamMetaData $metadata Metadata for source
76
     * @return string See RESULT_XXX constants in the interface
77
     */
78 9
    public function transform(StreamMetaData $metadata): string
79
    {
80 9
        $totalTransformations = 0;
81 9
        $parsedSource         = new ReflectionFile($metadata->uri, $metadata->syntaxTree);
82
83
        // Check if we have some new aspects that weren't loaded yet
84 9
        $unloadedAspects = $this->aspectLoader->getUnloadedAspects();
85 9
        if (!empty($unloadedAspects)) {
86
            $this->loadAndRegisterAspects($unloadedAspects);
87
        }
88 9
        $advisors = $this->container->getByTag('advisor');
89
90 9
        $namespaces = $parsedSource->getFileNamespaces();
91
92 9
        foreach ($namespaces as $namespace) {
93 9
            $classes = $namespace->getClasses();
94 9
            foreach ($classes as $class) {
95
                // Skip interfaces and aspects
96 8
                if ($class->isInterface() || in_array(Aspect::class, $class->getInterfaceNames())) {
97 2
                    continue;
98
                }
99 6
                $wasClassProcessed = $this->processSingleClass($advisors, $metadata, $class);
100
                $totalTransformations += (integer) $wasClassProcessed;
101
            }
102 3
            $wasFunctionsProcessed = $this->processFunctions($advisors, $metadata, $namespace);
103 3
            $totalTransformations += (integer) $wasFunctionsProcessed;
104
        }
105
106 3
        $result = ($totalTransformations > 0) ? self::RESULT_TRANSFORMED : self::RESULT_ABSTAIN;
107
108 3
        return $result;
109
    }
110
111
    /**
112
     * Performs weaving of single class if needed
113
     *
114
     * @param array|Advisor[] $advisors
115
     * @param StreamMetaData $metadata Source stream information
116
     * @param ReflectionClass $class Instance of class to analyze
117
     *
118
     * @return bool True if was class processed, false otherwise
119
     */
120 6
    private function processSingleClass(array $advisors, StreamMetaData $metadata, ReflectionClass $class): bool
121
    {
122 6
        $advices = $this->adviceMatcher->getAdvicesForClass($class, $advisors);
123
124 6
        if (empty($advices)) {
125
            // Fast return if there aren't any advices for that class
126
            return false;
127
        }
128
129
        // Sort advices in advance to keep the correct order in cache
130 6
        foreach ($advices as &$typeAdvices) {
131 6
            foreach ($typeAdvices as &$joinpointAdvices) {
132 6
                if (is_array($joinpointAdvices)) {
133 6
                    $joinpointAdvices = AbstractJoinpoint::sortAdvices($joinpointAdvices);
134
                }
135
            }
136
        }
137
138
        // Prepare new class name
139 6
        $newClassName = $class->getShortName() . AspectContainer::AOP_PROXIED_SUFFIX;
140
141
        // Replace original class name with new
142 6
        $this->adjustOriginalClass($class, $metadata, $newClassName);
143
144
        // Prepare child Aop proxy
145 6
        $child = $class->isTrait()
146
            ? new TraitProxy($class, $advices)
147 6
            : new ClassProxy($class, $advices);
148
149
        // Set new parent name instead of original
150 6
        $child->setParentName($newClassName);
151 6
        $contentToInclude = $this->saveProxyToCache($class, $child);
152
153
        // Get last token for this class
154
        $lastClassToken = $class->getNode()->getAttribute('endTokenPos');
155
156
        $metadata->tokenStream[$lastClassToken][1] .= PHP_EOL . $contentToInclude;
157
158
        return true;
159
    }
160
161
    /**
162
     * Adjust definition of original class source to enable extending
163
     *
164
     * @param ReflectionClass $class Instance of class reflection
165
     * @param StreamMetaData $streamMetaData Source code metadata
166
     * @param string $newClassName New name for the class
167
     */
168 6
    private function adjustOriginalClass(ReflectionClass $class, StreamMetaData $streamMetaData, string $newClassName)
169
    {
170 6
        $classNode = $class->getNode();
171 6
        $position  = $classNode->getAttribute('startTokenPos');
172
        do {
173 6
            if (isset($streamMetaData->tokenStream[$position])) {
174 6
                $token = $streamMetaData->tokenStream[$position];
175
                // Remove final and following whitespace from the class, child will be final instead
176 6
                if ($token[0] === T_FINAL) {
177 1
                    unset($streamMetaData->tokenStream[$position], $streamMetaData->tokenStream[$position+1]);
178
                }
179
                // First string is class/trait name
180 6
                if ($token[0] === T_STRING) {
181 6
                    $streamMetaData->tokenStream[$position][1] = $newClassName;
182
                    // We have finished our job, can break this loop
183 6
                    break;
184
                }
185
            }
186 6
            ++$position;
187 6
        } while (true);
188 6
    }
189
190
    /**
191
     * Performs weaving of functions in the current namespace
192
     *
193
     * @param array|Advisor[] $advisors List of advisors
194
     * @param StreamMetaData $metadata Source stream information
195
     * @param ReflectionFileNamespace $namespace Current namespace for file
196
     *
197
     * @return boolean True if functions were processed, false otherwise
198
     */
199 3
    private function processFunctions(
200
        array $advisors,
201
        StreamMetaData $metadata,
202
        ReflectionFileNamespace $namespace
203
    ): bool {
204 3
        static $cacheDirSuffix = '/_functions/';
205
206 3
        $wasProcessedFunctions = false;
207 3
        $functionAdvices = $this->adviceMatcher->getAdvicesForFunctions($namespace, $advisors);
208 3
        $cacheDir        = $this->cachePathManager->getCacheDir();
209 3
        if (!empty($functionAdvices)) {
210
            $cacheDir .= $cacheDirSuffix;
211
            $fileName = str_replace('\\', '/', $namespace->getName()) . '.php';
212
213
            $functionFileName = $cacheDir . $fileName;
214
            if (!file_exists($functionFileName) || !$this->container->isFresh(filemtime($functionFileName))) {
215
                $dirname = dirname($functionFileName);
216
                if (!file_exists($dirname)) {
217
                    mkdir($dirname, $this->options['cacheFileMode'], true);
218
                }
219
                $source = new FunctionProxy($namespace, $functionAdvices);
220
                file_put_contents($functionFileName, $source, LOCK_EX);
221
                // For cache files we don't want executable bits by default
222
                chmod($functionFileName, $this->options['cacheFileMode'] & (~0111));
223
            }
224
            $content = 'include_once AOP_CACHE_DIR . ' . var_export($cacheDirSuffix . $fileName, true) . ';';
225
226
            $lastTokenPosition = $namespace->getLastTokenPosition();
227
            $metadata->tokenStream[$lastTokenPosition][1] .= PHP_EOL . $content;
228
            $wasProcessedFunctions = true;
229
        }
230
231 3
        return $wasProcessedFunctions;
232
    }
233
234
    /**
235
     * Save AOP proxy to the separate file anr returns the php source code for inclusion
236
     *
237
     * @param ReflectionClass $class Original class reflection
238
     * @param string|ClassProxy $child
239
     *
240
     * @return string
241
     */
242 6
    private function saveProxyToCache(ReflectionClass $class, $child): string
243
    {
244 6
        static $cacheDirSuffix = '/_proxies/';
245
246 6
        $cacheDir = $this->cachePathManager->getCacheDir() . $cacheDirSuffix;
247 6
        $fileName = str_replace($this->options['appDir'] . DIRECTORY_SEPARATOR, '', $class->getFileName());
248
249 6
        $proxyFileName = $cacheDir . $fileName;
250 6
        $dirname       = dirname($proxyFileName);
251 6
        if (!file_exists($dirname)) {
252 6
            mkdir($dirname, $this->options['cacheFileMode'], true);
253
        }
254
255
        $body      = '<?php' . PHP_EOL;
256
        $namespace = $class->getNamespaceName();
257
        if ($namespace) {
258
            $body .= "namespace {$namespace};" . PHP_EOL . PHP_EOL;
259
        }
260
261
        $refNamespace = new ReflectionFileNamespace($class->getFileName(), $namespace);
262
        foreach ($refNamespace->getNamespaceAliases() as $fqdn => $alias) {
263
            $body .= "use {$fqdn} as {$alias};" . PHP_EOL;
264
        }
265
266
        $body .= $child;
267
        file_put_contents($proxyFileName, $body, LOCK_EX);
268
        // For cache files we don't want executable bits by default
269
        chmod($proxyFileName, $this->options['cacheFileMode'] & (~0111));
270
271
        return 'include_once AOP_CACHE_DIR . ' . var_export($cacheDirSuffix . $fileName, true) . ';';
272
    }
273
274
    /**
275
     * Utility method to load and register unloaded aspects
276
     *
277
     * @param array $unloadedAspects List of unloaded aspects
278
     */
279
    private function loadAndRegisterAspects(array $unloadedAspects)
280
    {
281
        foreach ($unloadedAspects as $unloadedAspect) {
282
            $this->aspectLoader->loadAndRegister($unloadedAspect);
283
        }
284
    }
285
}
286