Passed
Pull Request — master (#116)
by Arnaud
03:38
created

StringField::setTranslator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace LAG\AdminBundle\Field;
4
5
use LAG\AdminBundle\Configuration\ActionConfiguration;
6
use LAG\AdminBundle\Field\Traits\TranslatorTrait;
7
use Symfony\Component\OptionsResolver\OptionsResolver;
8
9
class StringField extends AbstractField implements TranslatorAwareFieldInterface
10
{
11
    use TranslatorTrait;
12
13
    public function configureOptions(OptionsResolver $resolver, ActionConfiguration $actionConfiguration)
14
    {
15
        $resolver->setDefaults([
16
            'length' => $actionConfiguration->getParameter('string_length'),
17
            'replace' => $actionConfiguration->getParameter('string_length_truncate'),
18
            'translation' => true,
19
        ]);
20
    }
21
22
    public function isSortable(): bool
23
    {
24
        return true;
25
    }
26
27
    public function render($value = null): string
28
    {
29
        if ($this->options['translation']) {
30
            $value = $this
31
                ->translator
32
                ->trans($value)
33
            ;
34
        }
35
        $maximumStringLength = $this->options['length'];
36
        $replaceString = $this->options['replace'];
37
38
        // Truncate string if required
39
        if ($maximumStringLength && mb_strlen($value) > $maximumStringLength) {
40
            $value = mb_substr($value, 0, $maximumStringLength).$replaceString;
41
        }
42
        // #69 : strip tags to avoid to break the layout when content contains html
43
        $value = strip_tags($value);
44
45
        return $value;
46
    }
47
}
48