DoctrineDriver::getData()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
namespace Netdudes\DataSourceryBundle\DataSource\Driver\Doctrine;
3
4
use Doctrine\ORM\NoResultException;
5
use Doctrine\ORM\QueryBuilder;
6
use Netdudes\DataSourceryBundle\DataSource\Configuration\Field;
7
use Netdudes\DataSourceryBundle\DataSource\DataSourceInterface;
8
use Netdudes\DataSourceryBundle\DataSource\Driver\Doctrine\Events\PostFetchEvent;
9
use Netdudes\DataSourceryBundle\DataSource\Driver\Doctrine\Exception\ColumnNotFoundException;
10
use Netdudes\DataSourceryBundle\DataSource\Driver\Doctrine\Exception\ColumnNotSelectedException;
11
use Netdudes\DataSourceryBundle\DataSource\Driver\Doctrine\QueryBuilder\BuilderFactory;
12
use Netdudes\DataSourceryBundle\DataSource\Driver\DriverInterface;
13
use Netdudes\DataSourceryBundle\Query\Query;
14
use Netdudes\DataSourceryBundle\Query\QueryInterface;
15
16
class DoctrineDriver implements DriverInterface
17
{
18
    const EVENT_GENERATE_SELECTS = 1;
19
    const EVENT_GENERATE_JOINS = 2;
20
    const EVENT_POST_GENERATE_QUERY_BUILDER = 3;
21
    const EVENT_POST_FETCH = 4;
22
23
    /**
24
     * @var BuilderFactory
25
     */
26
    private $queryBuilderBuilderFactory;
27
28
    /**
29
     * @param BuilderFactory $queryBuilderBuilderFactory
30
     */
31
    public function __construct(BuilderFactory $queryBuilderBuilderFactory)
32
    {
33
        $this->queryBuilderBuilderFactory = $queryBuilderBuilderFactory;
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function getData(DataSourceInterface $dataSource, QueryInterface $query)
40
    {
41
        $queryBuilder = $this->getQueryBuilder($dataSource, $query);
42
        $rows = $this->fetchData($queryBuilder, $query, $dataSource);
0 ignored issues
show
Compatibility introduced by
$query of type object<Netdudes\DataSour...e\Query\QueryInterface> is not a sub-type of object<Netdudes\DataSourceryBundle\Query\Query>. It seems like you assume a concrete implementation of the interface Netdudes\DataSourceryBundle\Query\QueryInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
43
44
        return $rows;
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function getRecordCount(DataSourceInterface $dataSource, QueryInterface $query)
51
    {
52
        $queryBuilder = $this->getQueryBuilder($dataSource, $query);
53
        $queryBuilder->select('count(DISTINCT ' . $queryBuilder->getDQLPart('from')[0]->getAlias() . ')');
54
        $queryBuilder->resetDQLPart('groupBy');
55
        $queryBuilder->resetDQLPart('orderBy');
56
        $queryBuilder->setMaxResults(null);
57
        $queryBuilder->setFirstResult(null);
58
        try {
59
            return $queryBuilder->getQuery()->getSingleScalarResult();
60
        } catch (NoResultException $e) {
61
            return 0;
62
        }
63
    }
64
65
    /**
66
     * @param DataSourceInterface $dataSource
67
     * @param QueryInterface      $query
68
     *
69
     * @return \Doctrine\DBAL\Query\QueryBuilder|null
70
     */
71
    public function getQueryBuilder(DataSourceInterface $dataSource, QueryInterface $query)
72
    {
73
        $queryBuilderBuilder = $this->queryBuilderBuilderFactory->create($dataSource);
74
        $queryBuilder = $queryBuilderBuilder->buildQueryBuilder($query, $dataSource->getEntityClass());
0 ignored issues
show
Compatibility introduced by
$query of type object<Netdudes\DataSour...e\Query\QueryInterface> is not a sub-type of object<Netdudes\DataSourceryBundle\Query\Query>. It seems like you assume a concrete implementation of the interface Netdudes\DataSourceryBundle\Query\QueryInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
75
76
        return $queryBuilder;
77
    }
78
79
    /**
80
     * Transforms a fully-built query builder into a row collection with the results
81
     *
82
     * @param QueryBuilder        $queryBuilder
83
     *
84
     * @param Query               $query
85
     * @param DataSourceInterface $dataSource
86
     *
87
     * @return array
88
     * @throws ColumnNotSelectedException
89
     * @throws \Netdudes\DataSourceryBundle\DataSource\Driver\Doctrine\Exception\ColumnNotFoundException
90
     *
91
     */
92
    protected function fetchData(QueryBuilder $queryBuilder, Query $query, DataSourceInterface $dataSource)
93
    {
94
        $fields = $dataSource->getFields();
95
        $rowCollection = [];
96
        $queryResults = $queryBuilder->getQuery()->getResult();
97
        foreach ($queryResults as $queryResultsRow) {
98
            $row = [];
99
            foreach ($fields as $queryBuilderDataSourceField) {
100
                if (!in_array($queryBuilderDataSourceField->getUniqueName(), $query->getSelect(), true)) {
101
                    continue;
102
                }
103
104
                $row[$queryBuilderDataSourceField->getUniqueName()] =
105
                    $this->getCellValueByDataSourceField($queryResultsRow, $queryBuilderDataSourceField, $fields);
106
            }
107
            $rowCollection[] = $row;
108
        }
109
110
        $event = new PostFetchEvent($dataSource, $rowCollection);
111
        $dataSource->getEventDispatcher()->dispatch(
112
            self::EVENT_POST_FETCH,
113
            $event
114
        );
115
116
        return $event->data;
117
    }
118
119
    /**
120
     * Helper method: gets the data of a defined data source field
121
     * from a row of the database scalar results
122
     *
123
     * @param array $dataRow Plain array of data for a single row, from the database
124
     * @param Field $dataSourceField
125
     *
126
     * @throws \Exception
127
     *
128
     * @return mixed
129
     */
130
    protected function getCellValueByDataSourceField(array $dataRow, Field $dataSourceField, $fields)
131
    {
132
        $selectAlias = $dataSourceField->getDatabaseSelectAlias();
133
134
        if (is_array($selectAlias)) {
135
            // Alias is an array of aliases. The cell value is an array then too.
136
            $cellValue = [];
137
            foreach ($selectAlias as $key => $subAlias) {
138
                // Resolve recursively
139
                $field = $this->findQueryBuilderDataSourceFieldByUniqueName($subAlias, $fields);
140
                if (is_null($field)) {
141
                    throw new ColumnNotFoundException("Could not find data source field $subAlias, alias of  $selectAlias");
142
                }
143
                foreach ($fields as $field) {
144
                    if ($field->getUniqueName() === $subAlias) {
145
                        $cellValue[$key] = $this->getCellValueByDataSourceField($dataRow, $field, $fields);
146
                        break;
147
                    }
148
                }
149
            }
150
151
            return $cellValue;
152
        }
153
154
        // Try to get the data from the result row
155
        if (array_key_exists($selectAlias, $dataRow)) {
156
            return $dataRow[$selectAlias];
157
        }
158
159
        throw new ColumnNotSelectedException("Value for column '$selectAlias' cannot be found as the field was not selected");
160
    }
161
162
    private function findQueryBuilderDataSourceFieldByUniqueName($uniqueName, $fields)
163
    {
164
        foreach ($fields as $field) {
165
            if ($field->getUniqueName() === $uniqueName) {
166
                return $field;
167
            }
168
        }
169
170
        return null;
171
    }
172
}
173