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

FilePathToKeyTokenModifier   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 14
c 1
b 0
f 0
dl 0
loc 29
ccs 12
cts 12
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A toUnderscore() 0 4 1
A __construct() 0 4 1
A modifyAll() 0 11 2
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