Completed
Push — master ( ef04ac...5d4f5b )
by Shcherbak
02:40
created

Checkbox::setLabel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
cc 1
eloc 3
nc 1
nop 1
crap 2
1
<?php
2
3
  namespace Fiv\Form\Element;
4
5
  use Fiv\Form\Elements\DataElementInterface;
6
  use Fiv\Form\FormData;
7
8
  /**
9
   * Generate <input type="submit" /> element
10
   *
11
   * @author Ivan Shcherbak <[email protected]>
12
   */
13
  class Checkbox extends Html implements DataElementInterface {
14
15
    protected $attributes = [
16
      'type' => 'checkbox',
17
    ];
18
19
    /**
20
     * @var string
21
     */
22
    protected $label = '';
23
24
    protected $isChecked = false;
25
26
27 9
    public function __construct(string $name, string $label = null) {
28 9
      $this->tag = 'input';
29
30 9
      $this->setAttribute('name', $name);
31 9
      if ($label !== null) {
32
        $this->setLabel($label);
33
      }
34 9
    }
35
36
37
    public function isValid() {
38
      return true;
39
    }
40
41
42
    /**
43
     * @inheritdoc
44
     */
45 8
    public function handle(FormData $data) {
46 8
      $this->setChecked($data->has($this->getName()));
47 8
      return $this;
48
    }
49
50
51 7
    public function isChecked() : bool {
52 7
      return $this->isChecked;
53
    }
54
55
56 8
    public function setChecked(bool $isChecked) : self {
57 8
      $this->isChecked = ($isChecked === true);
58 8
      if ($this->isChecked) {
59 8
        $this->setAttribute('checked', 'checked');
60
      } else {
61 2
        $this->removeAttribute('checked');
62
      }
63 8
      return $this;
64
    }
65
66
67
    /**
68
     * @inheritdoc
69
     */
70 9
    public function setAttribute($name, $value) {
71 9
      if ($name == 'checked') {
72 8
        $this->isChecked = true;
73
      }
74 9
      return parent::setAttribute($name, $value);
75
    }
76
77
78
    /**
79
     * @inheritdoc
80
     */
81 2
    public function removeAttribute($name) {
82 2
      if ($name == 'checked') {
83 2
        $this->isChecked = false;
84
      }
85 2
      return parent::removeAttribute($name);
86
    }
87
88
89
    /**
90
     * @param string $text
91
     * @return $this
92
     */
93
    public function setLabel(string $text) : self {
94
      $this->label = $text;
95
      return $this;
96
    }
97
98
99
    /**
100
     * @return string
101
     */
102 1
    public function render() {
103 1
      return '<label>' . static::tag($this->tag, $this->attributes) . $this->label . '</label>';
104
    }
105
106
107
    /**
108
     * @return string
109
     */
110 8
    public function getName() {
111 8
      return $this->getAttribute('name');
112
    }
113
114
115
  }