Completed
Push — master ( bd4cbc...df0c76 )
by Arnaud
9s
created

StringField::render()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.0466

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 23
ccs 12
cts 14
cp 0.8571
rs 8.7972
c 1
b 0
f 1
cc 4
eloc 15
nc 4
nop 1
crap 4.0466
1
<?php
2
3
namespace LAG\AdminBundle\Field\Field;
4
5
use LAG\AdminBundle\Field\Field;
6
use Symfony\Component\OptionsResolver\OptionsResolver;
7
8
/**
9
 * String field.
10
 *
11
 * It render a string that can be truncated according to is length
12
 * Note : according php7 (nightly), class can not be named String anymore
13
 */
14
class StringField extends Field
15
{
16
17
    /**
18
     * Render a string that can be truncated according to is length.
19
     *
20
     * @param $value
21
     * @return string
22
     */
23 2
    public function render($value)
24
    {
25 2
        if ($this->options->get('translation')) {
26 2
            $value = $this
27
                ->translator
28 2
                ->trans($value);
29 2
        }
30 2
        $maximumStringLength = $this
31
            ->options
32 2
            ->get('length');
33 2
        $replaceString = $this
34
            ->options
35 2
            ->get('replace');
36
37
        // truncate string if required
38 2
        if ($maximumStringLength && strlen($value) > $maximumStringLength) {
39
            $value = substr($value, 0, $maximumStringLength).$replaceString;
40
        }
41
        // #69 : strip tags to avoid layout destruction when content contains html
42 2
        $value = strip_tags($value);
43
44 2
        return $value;
45
    }
46
47
    /**
48
     * Configure options resolver.
49
     *
50
     * @param OptionsResolver $resolver
51
     */
52 2
    public function configureOptions(OptionsResolver $resolver)
53
    {
54 2
        $resolver->setDefaults([
55 2
            'length' => $this->applicationConfiguration->getParameter('string_length'),
56 2
            'replace' => $this->applicationConfiguration->getParameter('string_length_truncate'),
57 2
            'translation' => true,
58 2
        ]);
59 2
    }
60
61
    /**
62
     * Return form type.
63
     *
64
     * @return string
65
     */
66
    public function getType()
67
    {
68
        return 'string';
69
    }
70
}
71