Completed
Push — master ( 842449...fcd89a )
by Arnold
02:08
created

ArrayExtension::getFilters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 0
1
<?php
2
3
namespace Jasny\Twig;
4
5
/**
6
 * Expose PHP's array functions to Twig
7
 */
8
class ArrayExtension extends \Twig_Extension
9
{
10
    /**
11
     * Return extension name
12
     * 
13
     * @return string
14
     */
15
    public function getName()
16
    {
17
        return 'jasny/array';
18
    }
19
20
    /**
21
     * Callback for Twig
22
     * @ignore
23
     */
24
    public function getFilters()
25
    {
26
        return [
27
            new \Twig_SimpleFilter('sum', [$this, 'sum']),
28
            new \Twig_SimpleFilter('product', [$this, 'product']),
29
            new \Twig_SimpleFilter('values', [$this, 'values']),
30
            new \Twig_SimpleFilter('as_array', [$this, 'asArray']),
31
            new \Twig_SimpleFilter('html_attr', [$this, 'htmlAttributes']),
32
        ];
33
    }
34
    
35
36
    /**
37
     * Calculate the sum of values in an array
38
     * 
39
     * @param array $array
40
     * @return int
41
     */
42
    public function sum($array)
43
    {
44
        return isset($array) ? array_sum((array)$array) : null;
45
    }
46
    
47
    /**
48
     * Calculate the product of values in an array
49
     * 
50
     * @param array $array
51
     * @return int
52
     */
53
    public function product($array)
54
    {
55
       return isset($array) ? array_product((array)$array) : null;
56
    }
57
    
58
    /**
59
     * Return all the values of an array or object
60
     * 
61
     * @param array|object $array
62
     * @return array
63
     */
64
    public function values($array)
65
    {
66
       return isset($array) ? array_values((array)$array) : null;
67
    }
68
    
69
    /**
70
     * Cast value to an array
71
     * 
72
     * @param object|mixed $value
73
     * @return array
74
     */
75
    public function asArray($value)
76
    {
77
        return is_object($value) ? get_object_vars($value) : (array)$value;
78
    }
79
    
80
    /**
81
     * Cast an array to an HTML attribute string
82
     * 
83
     * @param mixed $array
84
     * @return string
85
     */
86
    public function htmlAttributes($array)
87
    {
88
        if (!isset($array)) {
89
            return null;
90
        }
91
       
92
        $str = "";
93
        foreach ($array as $key => $value) {
94
            if (!isset($value) || $value === false) {
95
                continue;
96
            }
97
            
98
            if ($value === true) {
99
                $value = $key;
100
            }
101
            
102
            $str .= ' ' . $key . '="' . addcslashes($value, '"') . '"';
103
        }
104
        
105
        return trim($str);
106
    }
107
}
108