Completed
Pull Request — master (#3)
by
unknown
15:35
created

Serializer::formatData()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 1
ccs 0
cts 0
cp 0
nc 1
1
<?php
2
3
namespace leandrogehlen\exporter\serializers;
4
5
use leandrogehlen\exporter\data\Column;
6
use leandrogehlen\exporter\data\Dictionary;
7
use leandrogehlen\exporter\data\Exporter;
8
use leandrogehlen\exporter\data\Provider;
9
use leandrogehlen\exporter\data\Session;
10
use yii\base\InvalidConfigException;
11
use yii\base\Object;
12
use yii\db\Query;
13
use yii\helpers\ArrayHelper;
14
15
16
17
/**
18
 * Serializer converts DB data into specific before it is sent out
19
 *
20
 * @author Leandro Guindani Gehlen <[email protected]>
21
 */
22
abstract class Serializer extends Object
23
{
24
25
    /**
26
     * @event Event an event raised at the beginning of serialize row
27
     */
28
    const EVENT_BEFORE_SERIALIZE_ROW = 'beforeSerializeRow';
29
30
    /**
31
     * @var Exporter
32
     */
33
    public $exporter;
34
35
    /**
36
     * Serializes the given session into a format that can be easily turned into other formats.
37
     * @param Session[] $sessions
38
     * @param array $master
39
     * @return array
40
     */
41
    abstract public function serialize($sessions, $master = []);
42
43
44
    /**
45
     * Formats the specified data.
46
     * @param array $data
47
     * @return string
48
     */
49
    abstract public function formatData($data);
50
51
    /**
52
     * Executes the query statement and returns ALL rows at once.
53
     * @param Provider $provider the provider name
54
     * @return array
55
     * @throws InvalidConfigException
56
     */
57 7
    protected function executeProvider($provider, $master)
58
    {
59 7
        $db = $this->exporter->db;
60 7
        $query = $provider->query;
61
62 7
        if ($query instanceof Query) {
63 2
            list($sql, $params) = $db->getQueryBuilder()->build($query);
64 7
        } elseif (is_string($query)) {
65 6
            $sql = $query;
66 6
            $params = [];
67 1
        } else {
68
            throw new InvalidConfigException('The query of provider "' . $provider->name .  '" must be string or Query object');
69
        }
70 6
71 6
        if (preg_match_all('/:\w+/', $sql, $matches)) {
72 3
            foreach ($matches[0] as $param) {
73 3
                $name = substr($param, 1);
74 3
                if (!isset($params[$name]) && !isset($params[$param])) {
75
                    $value = ArrayHelper::getValue($master, $name);
76 3
77 1
                    if ($value === null) {
78 1
                        $parameter = $this->exporter->findParameter($name);
79 1
                        if ($parameter !== null) {
80 1
                            $value = is_callable($parameter->value) ? call_user_func($parameter->value) : $parameter->value;
81 1
                        }
82 3
                    }
83 3
                    $params[$name] = $value;
84 3
                }
85
            }
86 6
        }
87
88
        return $db->createCommand($sql, $params)->queryAll();
89
    }
90
91
    /**
92
     * This method is invoked before serialize row.
93
     * @param string|array $record
94
     * @param Session $session
95 5
     * @return string|array
96
     */
97 5
    public function beforeSerializeRow($record, $session)
98 4
    {
99
        $event = $this->exporter->findEvent(self::EVENT_BEFORE_SERIALIZE_ROW);
100
        return ($event !== null) ? call_user_func($event->expression, $record, $session) : $record;
101
    }
102
103
    /**
104
     * Extract formatted value.
105
     * @param Column $column
106
     * @param array $row
107 6
     * @return mixed|string
108
     */
109 6
    protected function extractValue($column, $row)
110 6
    {
111 6
        $complete = $column->complete;
112 6
        $size = $column->size;
113 6
        $format = $column->format;
114 6
        $align = $column->align;
115
        $expression = null;
116 6
        $value = ArrayHelper::getValue($row, $column->name);
117 4
118 6
        if (is_callable($column->value)){
119 6
            $expression = $column->value;
120 6
        } elseif ($column->value !== null) {
121
            $value = $column->value;
122 6
        }
123 6
124 3
        $dictionary = $column->dictionary ? $this->exporter->findDictionary($column->dictionary) : null;
125 3
        if ($dictionary) {
126 1
            if ($dictionary->value) {
127 3
                if ($expression === null && is_callable($dictionary->value)) {
128 2
                    $expression = $dictionary->value;
129 2
                } elseif ($value === null) {
130 3
                    $value = $dictionary->value;
131 3
                }
132 3
            }
133 3
            if ($complete === null) {
134 3
                $complete = $dictionary->complete;
135 3
            }
136 3
            if ($align === null) {
137 3
                $align = $dictionary->align;
138 3
            }
139 3
            if ($size === null) {
140 3
                $size = $dictionary->size;
141 3
            }
142 3
            if ($format === null) {
143 3
                $format = $dictionary->format;
144
            }
145 6
        }
146 1
147 1
        if ($format) {
148
            $value = $this->exporter->formatter->format($value, $format);
149 6
        }
150 4
151 4
        if (is_callable($expression)) {
152
            $value = call_user_func($expression, $value, $row);
153 6
        }
154 6
155 3
        $value = (string) $value;
156
        if ($size === null) {
157 3
            return $value;
158 3
        } else {
159
            $padding = $this->toPadding($align);
160
            return ($size > strlen($value) && $complete !== null) ? str_pad($value, $size, $complete, $padding) : substr($value, 0, $size);
161
        }
162
    }
163
164
    /**
165
     * Converts the [[align]] property to valid padding type.
166
     * @see {@link http://php.net/manual/pt_BR/function.str-pad.php php manual}.
167
     * @param string $align the column alignment
168 3
     * @return int
169
     */
170 3
    private function toPadding($align)
171 1
    {
172 3
        if ($align == Dictionary::ALIGN_RIGHT) {
173
            return STR_PAD_LEFT;
174
        } elseif ($align == Dictionary::ALIGN_BOTH) {
175 3
            return STR_PAD_BOTH;
176
        } else {
177
            return STR_PAD_RIGHT;
178
        }
179
    }
180
}
181