Completed
Push — master ( c47098...bd2863 )
by Shcherbak
37:44 queued 22:47
created

CheckboxList   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 60
rs 10
c 1
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setValue() 0 15 4
A setChecked() 0 3 1
A render() 0 22 3
1
<?php
2
3
  namespace Fiv\Form\Element;
4
5
  /**
6
   * Class TextArea
7
   * Generate
8
   * ```html
9
   * <input type="checkbox" name="languages[]" value="en">
10
   * <input type="checkbox" name="languages[]" value="ru">
11
   * ```
12
   * html tags
13
   *
14
   * @author  Ivan Shcherbak <[email protected]>
15
   * @package Fiv\Form
16
   */
17
  class CheckboxList extends \Fiv\Form\Element\Multiple {
18
19
    /**
20
     * @param array|string $data
21
     * @return $this
22
     */
23
    public function setValue($data) {
24
      if (!is_array($data)) {
25
        $data = (array) $data;
26
      }
27
28
      foreach ($data as $i => $value) {
29
        # remove invalid values
30
        if (!isset($this->options[$value])) {
31
          unset($data[$i]);
32
        }
33
      }
34
35
      $this->value = array_values($data);
0 ignored issues
show
Documentation Bug introduced by
It seems like array_values($data) of type array<integer,?> is incompatible with the declared type null|string of property $value.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
36
      return $this;
37
    }
38
39
40
    /**
41
     * Alias of setValue
42
     *
43
     * @param string[] $values
44
     * @return $this
45
     */
46
    public function setChecked($values) {
47
      return $this->setValue($values);
48
    }
49
50
51
    /**
52
     * @return string
53
     */
54
    public function render() {
55
      $html = '';
56
      $currentValues = $this->getValue();
57
      $attributes = $this->attributes;
58
      $attributes['type'] = 'checkbox';
59
60
      $name = $this->getName();
61
62
      foreach ($this->options as $value => $text) {
63
        $attributes['value'] = $value;
64
        $attributes['name'] = $name . '[]';
65
        if (in_array($value, $currentValues)) {
66
          $attributes['checked'] = 'checked';
67
        } else {
68
          unset($attributes['checked']);
69
        }
70
71
        $html .= '<label>' . static::tag('input', $attributes) . $text . '</label>';
72
      }
73
74
      return $html;
75
    }
76
  }