-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathDynamicActiveRecord.php
563 lines (499 loc) · 15.6 KB
/
DynamicActiveRecord.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
<?php
/**
* @link https://github.com/tom--/dynamic-ar
* @copyright Copyright (c) 2015 Spinitron LLC
* @license http://opensource.org/licenses/ISC
*/
namespace spinitron\dynamicAr;
use Yii;
use yii\base\Exception;
use yii\base\UnknownPropertyException;
use yii\db\ActiveRecord;
/**
* DynamicActiveRecord represents relational data with structured dynamic attributes
* in addition to column attributes supported by ActiveRecord.
*
* DynamicActiveRecord adds structured dynamic attributes to Yii 2 ActiveRecord a bit
* like adding a document, in the sense of a NoSQL document store database, to each
* SQL table record. At present this is implemented for
* [Maria 10.0+ Dynamic Columns](https://mariadb.com/kb/en/mariadb/dynamic-columns/).
*
* You can read and write attributes of a DynamicActiveRecord model that are not
* instance variables, column attributes or virtual attribute. In other words, you can make
* up attribute names on-the-fly, assign values and they are stored in the database. You can
* then involve these dynamic attributes in queries using [[DynamicActiveQuery]].
*
* Dynamic attributes may also be data structures in the form of PHP arrays, elements of
* which can be accessed through dotted attribute notation.
*
* ```php
* $model->specs = ['dimensions' => ['length' => 20]];
* $model->setAttribute('specs.dimensions.width', 4);
* $model->setAttribute('specs.color', 'blue');
* // $model->specs now has the value
* // ['dimensions' => ['length' => 20, 'width' => 4], 'color' => 'blue']
* ```
*
* Model classes must implement the [[dynamicColumn()]] method to specify the name of the
* table column containing the serialized dynamic attributes.
*
* @author Tom Worster <[email protected]>
*/
class DynamicActiveRecord extends ActiveRecord
{
/**
* Prefix for base64 encoded dynamic attribute values
*/
const DATA_URI_PREFIX = 'data:application/octet-stream;base64,';
/**
* Prefix of PDO placeholders for Dynamic Column names and values
*/
const PARAM_PREFIX = ':dqp';
/**
* @var int Counter of PDO placeholders used in a query.
*/
protected static $placeholderCounter;
private $_dynamicAttributes = [];
/**
* Specifies the name of the table column containing dynamic attributes.
*
* @return string Name of the table column containing dynamic column data
* @throws \yii\base\Exception if not overriden by descendent class.
*/
public static function dynamicColumn()
{
throw new \yii\base\Exception('A DynamicActiveRecord class must override "dynamicColumn()"');
}
/**
* @inheritdoc
*/
public function __get($name)
{
return $this->getAttribute($name);
}
/**
* @inheritdoc
*
* @param string $name
* @param mixed $value
*/
public function __set($name, $value)
{
$this->setAttribute($name, $value);
}
/**
* @inheritdoc
*
* @param string $name
*/
public function __isset($name)
{
return $this->issetAttribute($name);
}
/**
* @inheritdoc
*
* @param string $name
*/
public function __unset($name)
{
$this->unsetAttribute($name);
}
/**
* Returns a model attribute value.
*
* @param string $name attribute name, use dotted notation for structured attributes.
*
* @return mixed|null the attribute value or null if the attribute does not exist
*/
public function getAttribute($name)
{
try {
return parent::__get($name);
} catch (UnknownPropertyException $ignore) {
}
$path = explode('.', $name);
$ref = &$this->_dynamicAttributes;
foreach ($path as $key) {
if (!isset($ref[$key])) {
return null;
}
$ref = &$ref[$key];
}
return $ref;
}
/**
* Sets a model attribute.
*
* @param string $name attribute name, use dotted notation for structured attributes.
* @param mixed $value the attribute value. A value of null effectively unsets the attribute.
*/
public function setAttribute($name, $value)
{
try {
parent::__set($name, $value);
return;
} catch (UnknownPropertyException $ignore) {
}
$path = explode('.', $name);
$ref = &$this->_dynamicAttributes;
// Walk forwards through $path to find the deepest key already set.
do {
$key = $path[0];
if (isset($ref[$key])) {
$ref = &$ref[$key];
array_shift($path);
} else {
break;
}
} while ($path);
// If the whole path already existed then we can just set it.
if (!$path) {
$ref = $value;
return;
}
// There is remaining path so we have to set a new leaf with the first
// part of the remaining path as key. But first, if there is any path
// beyond that then we need build an array to set as the new leaf value.
while (count($path) > 1) {
$key = array_pop($path);
$value = [$key => $value];
}
$ref[$path[0]] = $value;
}
/**
* Returns if a model attribute is set.
*
* @param string $name attribute name, use dotted notation for structured attributes.
*
* @return bool true if the attribute is set
*/
public function issetAttribute($name)
{
try {
if (parent::__get($name) !== null) {
return true;
}
} catch (Exception $ignore) {
}
$path = explode('.', $name);
$ref = &$this->_dynamicAttributes;
foreach ($path as $key) {
if (!isset($ref[$key])) {
return false;
}
$ref = &$ref[$key];
}
return true;
}
/**
* Unset a model attribute.
*
* @param string $name attribute name, use dotted notation for structured attributes.
*/
public function unsetAttribute($name)
{
try {
parent::__unset($name);
} catch (\Exception $ignore) {
}
if ($this->issetAttribute($name)) {
$this->setAttribute($name, null);
}
}
/**
* @inheritdoc
*/
public function fields()
{
$fields = array_keys((array) $this->_dynamicAttributes);
return array_merge(parent::fields(), $fields);
}
/**
* Convert a nested array to a map of dot-notation keys to values.
*
* @param string $prefix Prefix returned array keys with this string
* @param array $array Nested array of attributeName => value pairs
*
* @return array Map of keys in dotted notation to corresponding values
*/
protected static function dotKeyValues($prefix, $array)
{
$fields = [];
foreach ($array as $key => $value) {
if (is_string($key)) {
$newPos = $prefix . '.' . $key;
if (is_array($value)) {
$fields = array_merge($fields, static::dotKeyValues($newPos, $value));
} else {
$fields[$newPos] = $value;
}
}
}
return $fields;
}
/**
* Return a list of all model attribute names recursing structured dynamic attributes.
*
* @return array an array of all attribute names in dotted notation
* @throws Exception
*/
public function dotAttributeNames()
{
return array_merge(
array_values(parent::fields()),
array_keys(static::dotKeyValues(static::dynamicColumn(), $this->_dynamicAttributes))
);
}
/**
* Return a list of all attribute values with keys in dotted notation.
*
* @return array Array of attribute values with attribute names as array keys in dotted notation.
* @throws Exception
*/
public function dotAttributes()
{
return array_merge(
$this->attributes,
static::dotKeyValues(static::dynamicColumn(), $this->_dynamicAttributes)
);
}
/**
* Generate an SQL expression referring to the given dynamic column.
*
* @param string $name Attribute name
* @param string $type SQL datatype type
*
* @return string a Maria COLUMN_GET expression
*/
public static function columnExpression($name, $type = 'char')
{
$sql = '[[' . static::dynamicColumn() . ']]';
$parts = explode('.', $name);
$lastPart = array_pop($parts);
foreach ($parts as $column) {
$sql = "COLUMN_GET($sql, '$column' AS BINARY)";
}
$sql = "COLUMN_GET($sql, '$lastPart' AS $type)";
return $sql;
}
/**
* Returns a PDO parameter placeholder string, incrementing the placeholder counter.
*
* @return string the placeholder string
*/
public static function placeholder()
{
if (static::$placeholderCounter === null) {
static::$placeholderCounter = 1;
} else {
static::$placeholderCounter += 1;
}
return static::PARAM_PREFIX . static::$placeholderCounter;
}
/**
* Encode as data URIs strings that JSON cannot express.
*
* @param mixed $value a value to encode
*
* @return string the encoded data URI
*/
public static function encodeForMaria($value)
{
return is_string($value)
&& (!mb_check_encoding($value, 'UTF-8') || strpos($value, self::DATA_URI_PREFIX) === 0)
? self::DATA_URI_PREFIX . base64_encode($value)
: $value;
}
/**
* Decode strings encoded as data URIs.
*
* @param string $value the data URI to decode
*
* @return string the decoded value
*/
public static function decodeForMaria($value)
{
return is_string($value) && strpos($value, self::DATA_URI_PREFIX) === 0
? file_get_contents($value)
: $value;
}
/**
* Replacement for PHP's array walk and map builtins.
*
* @param array $array An array to walk, which may be nested
* @param callable $method A method to map on the array
*/
protected static function walk(& $array, $method)
{
if (is_scalar($array)) {
$array = static::$method($array);
return;
}
$replacements = [];
foreach ($array as $key => & $value) {
if (is_scalar($value) || $value === null) {
$value = static::$method($value);
} else {
static::walk($value, $method);
}
$newKey = static::$method($key);
if ($newKey !== $key) {
$replacements[$newKey] = $value;
unset($array[$key]);
}
}
foreach ($replacements as $key => $value2) {
$array[$key] = $value2;
}
}
/**
* Encodes as data URIs any "binary" strings in an array.
*
* @param array $array the array
*/
protected static function encodeArrayForMaria(& $array)
{
self::walk($array, 'encodeForMaria');
}
/**
* Decodes any data URI strings in an array.
*
* @param array $array the array
*/
protected static function decodeArrayForMaria(& $array)
{
self::walk($array, 'decodeForMaria');
}
/**
* Creates the SQL and parameter bindings for setting dynamic attributes
* in a DB record as Dynamic Columns in Maria.
*
* @param array $attrs the dynamic attributes, which may be nested
* @param array $params expression parameters for binding, passed by reference
*
* @return string SQL for a DB Expression
* @throws \yii\base\Exception
*/
protected static function dynColSqlMaria(array $attrs, & $params)
{
$sql = [];
foreach ($attrs as $key => $value) {
if (is_object($value) && !($value instanceof ValueExpression)) {
$value = method_exists($value, 'toArray') ? $value->toArray() : (array) $value;
}
if ($value === [] || $value === null) {
continue;
}
$phKey = static::placeholder();
$phValue = static::placeholder();
$sql[] = $phKey;
$params[$phKey] = $key;
if ($value instanceof ValueExpression || is_float($value)) {
$sql[] = $value;
} elseif (is_scalar($value)) {
$sql[] = $phValue;
$params[$phValue] = $value;
} elseif (is_array($value)) {
$sql[] = static::dynColSqlMaria($value, $params);
}
}
return $sql === [] ? 'null' : 'COLUMN_CREATE(' . implode(',', $sql) . ')';
}
/**
* Creates a dynamic column SQL expression representing the given attributes.
*
* @param array $attrs the dynamic attributes, which may be nested
*
* @return null|\yii\db\Expression
*/
public static function dynColExpression($attrs) {
if (!$attrs) {
return null;
}
$params = [];
// todo For now we only have Maria. Add PgSQL and generic JSON.
static::encodeArrayForMaria($attrs);
$sql = static::dynColSqlMaria($attrs, $params);
return new \yii\db\Expression($sql, $params);
}
/**
* Decode a serialized blob of dynamic attributes.
*
* At present the only supported input format is JSON returned from Maria. It may work
* also for PostgreSQL.
*
* @param string $encoded Serialized array of attributes in DB-specific form
*
* @return array Dynamic attributes in name => value pairs (possibly nested)
*/
public static function dynColDecode($encoded)
{
// Maria has a bug in its COLUMN_JSON funcion in which it fails to escape the
// control characters U+0000 through U+001F. This causes JSON decoders to fail.
// This workaround escapes those characters.
$encoded = preg_replace_callback(
'/[\x00-\x1f]/',
function ($matches) {
return sprintf('\u00%02x', ord($matches[0]));
},
$encoded
);
$decoded = json_decode($encoded, true);
if ($decoded) {
static::decodeArrayForMaria($decoded);
}
return $decoded;
}
/**
* Returns a query object for the model/class.
*
* @return DynamicActiveQuery
*/
public static function find()
{
return Yii::createObject(DynamicActiveQuery::className(), [get_called_class()]);
}
/**
* @param bool $insert
*
* @return bool
* @throws Exception
*/
public function beforeSave($insert)
{
if (!parent::beforeSave($insert)) {
return false;
}
$this->setAttribute(static::dynamicColumn(), static::dynColExpression($this->_dynamicAttributes));
return true;
}
/**
* @param DynamicActiveRecord $record
* @param array $row
*
* @throws Exception
*/
public static function populateRecord($record, $row)
{
$dynCol = static::dynamicColumn();
if (isset($row[$dynCol])) {
$record->_dynamicAttributes = static::dynColDecode($row[$dynCol]);
}
parent::populateRecord($record, $row);
}
/**
* @inheritdoc
*/
public function refresh()
{
if (!parent::refresh()) {
return false;
}
$dynCol = static::dynamicColumn();
if (isset($this->attributes[$dynCol])) {
$this->_dynamicAttributes = static::dynColDecode($this->attributes[$dynCol]);
}
return true;
}
}