Completed
Push — master ( 25bb76...eaeb56 )
by Philip
02:45
created

TwigExtensions::arrayColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 3
rs 10
c 1
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file is part of the CRUDlex package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CRUDlex;
13
14
use Pimple\Container;
15
use Symfony\Component\Intl\Intl;
16
17
/**
18
 * Provides and setups the Twig extensions like filters.
19
 */
20
class TwigExtensions {
21
22
    /**
23
     * Registers all extensions.
24
     *
25
     * @param Container $app
26
     * the current application
27
     */
28
    public function registerTwigExtensions(Container $app) {
29
        $self = $this;
30
        $app->extend('twig', function(\Twig_Environment $twig) use ($self) {
31
            $twig->addFilter(new \Twig_SimpleFilter('arrayColumn', 'array_column'));
32
            $twig->addFilter(new \Twig_SimpleFilter('languageName', [$self, 'getLanguageName']));
33
            $twig->addFilter(new \Twig_SimpleFilter('float', [$self, 'formatFloat']));
34
            $twig->addFilter(new \Twig_SimpleFilter('basename', 'basename'));
35
            return $twig;
36
        });
37
    }
38
39
    /**
40
     * Gets a language name in the given language.
41
     *
42
     * @param string $language
43
     * the language code of the desired language name
44
     *
45
     * @return string
46
     * the language name in the given language or null if not available
47
     */
48
    public function getLanguageName($language) {
49
        return Intl::getLanguageBundle()->getLanguageName($language, $language, $language);
50
    }
51
52
    /**
53
     * Formats a float to not display in scientific notation.
54
     *
55
     * @param float $float
56
     * the float to format
57
     *
58
     * @return double|string
59
     * the formated float
60
     */
61
    public function formatFloat($float) {
62
63
        if (!$float) {
64
            return $float;
65
        }
66
67
        $zeroFraction = $float - floor($float) == 0 ? '0' : '';
68
69
        // We don't want values like 0.004 converted to  0.00400000000000000008
70
        if ($float > 0.0001) {
71
            return $float.($zeroFraction === '0' ? '.'.$zeroFraction : '');
72
        }
73
74
        // We don't want values like 0.00004 converted to its scientific notation 4.0E-5
75
        return rtrim(sprintf('%.20F', $float), '0').$zeroFraction;
76
    }
77
}
78