Completed
Push — master ( b66ca6...b12848 )
by Samuel
15:09 queued 05:11
created

FilePathToKeyTokenModifier::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Efabrica\TranslationsAutomatization\TokenModifier;
4
5
use Efabrica\TranslationsAutomatization\Tokenizer\TokenCollection;
6
use Nette\Utils\Strings;
7
8
class FilePathToKeyTokenModifier implements TokenModifierInterface
9
{
10
    private $basePath;
11
12
    private $excludeDirectoryNames;
13 6
14
    public function __construct(string $basePath, array $excludeDirectoryNames = [])
15 6
    {
16 6
        $this->basePath = rtrim($basePath, '/');
17 6
        $this->excludeDirectoryNames = array_map('strtolower', $excludeDirectoryNames);
18
    }
19 6
20
    public function modifyAll(TokenCollection $tokenCollection): TokenCollection
21 6
    {
22 6
        $pathParts = array_unique(explode('/', str_replace($this->basePath . '/', '', pathinfo($tokenCollection->getFilePath(), PATHINFO_DIRNAME) . '/' . pathinfo($tokenCollection->getFilePath(), PATHINFO_FILENAME))));
23
        foreach ($tokenCollection->getTokens() as $token) {
24 6
            $newKeyParts = array_filter(array_map([$this, 'toUnderscore'], $pathParts), function ($pathPart) {
25 6
                return !in_array($pathPart, $this->excludeDirectoryNames);
26 6
            });
27 6
            $newKeyParts[] = $token->getTranslationKey();
28
            $token->changeTranslationKey(implode('.', $newKeyParts));
29 6
        }
30
        return $tokenCollection;
31
    }
32
33
    private function toUnderscore(string $string): string
34
    {
35
        $result = preg_replace('/[A-Z]/', '_${0}', $string);
36
        return strtolower(trim($result, '_'));
37
    }
38
}
39