Completed
Push — master ( 3f1d1d...0341ae )
by Matze
05:15
created

CompilerPass::getTokensForService()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 13.125

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 7
cts 14
cp 0.5
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 17
nc 7
nop 3
crap 13.125
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 Generator;
9
use ReflectionClass;
10
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
11
use Symfony\Component\DependencyInjection\ContainerBuilder;
12
use Translation\Token;
13
14
/**
15
 * @CompilerPassAnnotation("Core.Translation.CompilerPass")
16
 */
17
class CompilerPass implements CompilerPassInterface
18
{
19
20
    const CACHE_FILE = ROOT . 'cache/translation_token';
21
    const TAG = 'middleware';
22
23
    use FileCacheTrait;
24
25
    /**
26
     * {@inheritdoc}
27
     */
28 1
    public function process(ContainerBuilder $container)
29
    {
30 1
        $tokens = iterator_to_array($this->getTokens($container));
31
32 1
        $this->dumpTranslations($tokens);
33 1
    }
34
35
    /**
36
     * @param ContainerBuilder $container
37
     * @return Generator|Token[]
38
     */
39 1
    private function getTokens(ContainerBuilder $container) : Generator
40
    {
41 1
        $serviceIds = $container->getServiceIds();
42 1
        foreach ($serviceIds as $serviceId) {
43
            try {
44 1
                $class = $container->findDefinition($serviceId)->getClass();
45 1
                $reflection = new ReflectionClass($class);
46 1
            } catch (Exception $e) {
47 1
                continue;
48
            }
49
50 1
            yield from $this->getTokensForService($container, $reflection, $serviceId);
51
        }
52 1
    }
53
54
    /**
55
     * @param ContainerBuilder $container
56
     * @param ReflectionClass $reflection
57
     * @param string $serviceId
58
     * @return Generator|Token[]
59
     */
60 1
    private function getTokensForService(
61
        ContainerBuilder $container,
62
        ReflectionClass $reflection,
63
        string $serviceId
64
    ) : Generator {
65 1
        if ($reflection->implementsInterface(ServiceTranslationProvider::class)) {
66
            /** @var ServiceTranslationProvider $class */
67 1
            $service = $container->get($serviceId);
68
69 1
            foreach ($service->getTokens() as $token) {
70
                if (!$token instanceof Token) {
71
                    $token = new Token($token);
72
                }
73
74 1
                yield $token->token => $token;
75
            }
76 1
        } elseif ($reflection->implementsInterface(TranslationProvider::class)) {
77
            /** @var TranslationProvider $className */
78
            $className = $reflection->getName();
79
            foreach ($className::getTokens() as $token) {
80
                if (!$token instanceof Token) {
81
                    $token = new Token($token);
82
                }
83
84
                yield $token->token => $token;
85
            }
86
        }
87 1
    }
88
89
    /**
90
     * @param array $tokens
91
     */
92 1
    protected function dumpTranslations(array $tokens)
93
    {
94 1
        ksort($tokens);
95
96
        $contentPhp = sprintf("return [\n    %s\n];\n", implode(",\n    ", array_map(function (Token $token) {
97
            return sprintf('_("%s")', addslashes($token->token));
98 1
        }, $tokens)));
99
100 1
        $contentHtml = sprintf("%s", implode("\n", array_map(function (Token $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...
101
            return sprintf('<span translate>%s</span>', addslashes($token->token));
102 1
        }, $tokens)));
103
104 1
        $this->dumpCacheFile(self::CACHE_FILE, $contentPhp);
105 1
        file_put_contents(self::CACHE_FILE . '.html', $contentHtml);
106 1
    }
107
}
108