Completed
Push — master ( f95aab...ce10dc )
by Basil
04:32
created

HtmlEncodeBehavior::events()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace luya\behaviors;
4
5
use yii\base\Behavior;
6
use yii\db\ActiveRecord;
7
use luya\helpers\Html;
8
9
/**
10
 * Auto Encodes value after find.
11
 *
12
 * ```php
13
 * public function behaviors()
14
 * {
15
 *     return [
16
 *         'encode' => [
17
 *             'class' => 'luya\behaviors\HtmlEncodeBehavior',
18
 *             'attributes' => [
19
 *                 'firstname', 'lastname', 'text',
20
 *             ],
21
 *         ],
22
 *     ];
23
 * }
24
 * ```
25
 *
26
 * You can also use the {{luya\behaviors\HtmlEncodeBehavior::htmlEncode()}} function when behavior is
27
 * attached like a trait would.
28
 *
29
 * @author Basil Suter <[email protected]>
30
 */
31
class HtmlEncodeBehavior extends Behavior
32
{
33
    public $attributes = [];
34
35
    /**
36
     * @inheritdoc
37
     */
38
    public function events()
39
    {
40
        return [
41
            ActiveRecord::EVENT_AFTER_FIND => 'afterFind',
42
        ];
43
    }
44
    
45
    /**
46
     * Event will be triggered after find.
47
     *
48
     * @param \yii\base\Event $event The after find event.
49
     */
50
    public function afterFind($event)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
51
    {
52
        foreach ($this->attributes as $attribute) {
53
            $this->owner->{$attribute} = $this->htmlEncode($this->owner->{$attribute});
54
        }
55
    }
56
    
57
    /**
58
     * Encodes the given value based on {{luya\helpers\Html::encode()}}.
59
     *
60
     * @param string $value The value which should be encoded.
61
     * @return string Returns the encoded value.
62
     */
63
    public function htmlEncode($value)
64
    {
65
        return Html::encode($value);
66
    }
67
}
68