DbReference   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 73
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 16 1
A buildFormElement() 0 21 3
1
<?php
2
3
namespace AtDataGrid\Column;
4
5
use Zend\Db\Adapter\Adapter;
6
use Zend\Db\Sql\Sql;
7
use Zend\Form\Element\Select;
8
9
class DbReference extends Column
10
{
11
    /**
12
     * @var Adapter
13
     */
14
    protected $dbAdapter;
15
16
    /**
17
     * @var string
18
     */
19
    protected $refTable;
20
21
    /**
22
     * @var string
23
     */
24
    protected $refField;
25
26
    /**
27
     * @var string
28
     */
29
    protected $resultField;
30
31
    /**
32
     * @param $name
33
     * @param Adapter $dbAdapter
34
     * @param $refTable
35
     * @param $refField
36
     * @param $resultField
37
     */
38
    public function __construct($name, Adapter $dbAdapter, $refTable, $refField, $resultField)
39
    {
40
        parent::__construct($name);
41
42
        $this->dbAdapter = $dbAdapter;
43
        $this->refTable = $refTable;
44
        $this->refField = $refField;
45
        $this->resultField = $resultField;
46
47
        $sql = new Sql($this->dbAdapter, $this->refTable);
48
49
        $this->addDecorator(new Decorator\DbReference($sql, $this->refField, $this->resultField));
50
51
        // Form element
52
        $this->setFormElement($this->buildFormElement());
53
    }
54
55
    /**
56
     * @param string $identityColumn
57
     * @param bool $addEmptyOption
58
     * @return Select
59
     */
60
    protected function buildFormElement($identityColumn = 'id', $addEmptyOption = true)
61
    {
62
        $sql = new Sql($this->dbAdapter, $this->refTable);
63
        $select = $sql->select();
64
        $statement = $sql->prepareStatementForSqlObject($select);
65
        $rowset = $statement->execute();
66
67
        $options = [];
68
        foreach ($rowset as $row) {
69
            $options[$row[$identityColumn]] = $row[$this->resultField];
70
        }
71
72
        $formElement = new Select($this->getName());
73
        $formElement->setValueOptions($options);
74
75
        if ($addEmptyOption) {
76
            $formElement->setEmptyOption('');
77
        }
78
79
        return $formElement;
80
    }
81
}