Completed
Push — master ( 1f9fde...c86638 )
by Matze
05:56
created

CompilerPass::getTokens()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.4746

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 5
cts 8
cp 0.625
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 4
nop 1
crap 3.4746
1
<?php
2
3
namespace BrainExe\Core\Translation;
4
5
use BrainExe\Core\Annotations\CompilerPass as CompilerPassAnnotation;
6
use BrainExe\Core\Traits\FileCacheTrait;
7
use Exception;
8
use ReflectionClass;
9
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
10
use Symfony\Component\DependencyInjection\ContainerBuilder;
11
12
/**
13
 * @CompilerPassAnnotation("Core.Translation.CompilerPass")
14
 */
15
class CompilerPass implements CompilerPassInterface
16
{
17
18
    const CACHE_FILE = ROOT . 'cache/translation_token';
19
    const TAG = 'middleware';
20
21
    use FileCacheTrait;
22
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function process(ContainerBuilder $container)
27 2
    {
28
        $tokens = $this->getTokens($container);
29 2
30
        $this->dumpTranslations($tokens);
31 2
    }
32 2
33
    /**
34 2
     * @param ContainerBuilder $container
35 2
     * @return string[]
36
     */
37
    private function getTokens(ContainerBuilder $container) : array
38
    {
39
        $tokens = [];
40 2
41
        $serviceIds = $container->getServiceIds();
42 2
        foreach ($serviceIds as $serviceId) {
43
            try {
44 2
                $class = $container->getDefinition($serviceId)->getClass();
45
                $reflection = new ReflectionClass($class);
46
            } catch (Exception $e) {
47
                continue;
48 2
            }
49
50
            $this->getTokensForService($tokens, $container, $reflection, $serviceId);
51 2
        }
52
53
        return $tokens;
54
    }
55
56 2
    /**
57 2
     * @param array $tokens
58
     * @param ContainerBuilder $container
59
     * @param ReflectionClass $reflection
60
     * @param string $serviceId
61
     */
62 2
    private function getTokensForService(
63
        array &$tokens,
64 2
        ContainerBuilder $container,
65
        ReflectionClass $reflection,
66
        string $serviceId
67
    ) {
68 2
        if ($reflection->implementsInterface(ServiceTranslationProvider::class)) {
69
            /** @var ServiceTranslationProvider $class */
70 2
            $service = $container->get($serviceId);
71
72 2
            foreach ($service->getTokens() as $token) {
73
                $tokens[] = $token;
74 2
            }
75 2
        } elseif ($reflection->implementsInterface(TranslationProvider::class)) {
76 2
            /** @var TranslationProvider $className */
77 2
            $className = $reflection->getName();
78
            foreach ($className::getTokens() as $token) {
79
                $tokens[] = $token;
80
            }
81
        }
82
    }
83
84
    /**
85
     * @param array $tokens
86
     */
87
    protected function dumpTranslations(array $tokens)
88
    {
89
        sort($tokens);
90
91
        $contentPhp = sprintf("return [\n    %s\n];\n", implode(",\n    ", array_map(function ($token) {
92
            return sprintf('_("%s")', addslashes($token));
93
        }, $tokens)));
94
95
        $contentHtml = sprintf("%s", implode("\n", array_map(function ($token) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal %s does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
96
            return sprintf('<span translate>%s</span>', addslashes($token));
97
        }, $tokens)));
98
99
        $this->dumpCacheFile(self::CACHE_FILE, $contentPhp);
100
        file_put_contents(self::CACHE_FILE . '.html', $contentHtml);
101
        chmod(self::CACHE_FILE . '.html', 0777);
102
    }
103
}
104