forked from webiny/Entity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EntityAbstract.php
executable file
·789 lines (696 loc) · 23.4 KB
/
EntityAbstract.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
<?php
/**
* Webiny Framework (http://www.webiny.com/framework)
*
* @copyright Copyright Webiny LTD
*/
namespace Webiny\Component\Entity;
use Webiny\Component\Entity\Attribute\AttributeAbstract;
use Webiny\Component\Entity\Attribute\AttributeType;
use Webiny\Component\Entity\Attribute\CharAttribute;
use Webiny\Component\Entity\Attribute\Exception\ValidationException;
use Webiny\Component\Entity\Attribute\Many2ManyAttribute;
use Webiny\Component\Entity\Attribute\One2ManyAttribute;
use Webiny\Component\Entity\AttributeStorage\Many2ManyStorage;
use Webiny\Component\Mongo\MongoResult;
use Webiny\Component\StdLib\FactoryLoaderTrait;
use Webiny\Component\StdLib\StdLibTrait;
use Webiny\Component\StdLib\StdObject\ArrayObject\ArrayObject;
use Webiny\Component\StdLib\StdObject\StdObjectWrapper;
/**
* Entity
* @package \Webiny\Component\Entity
*/
abstract class EntityAbstract implements \ArrayAccess
{
use StdLibTrait, EntityTrait, FactoryLoaderTrait;
/**
* This array serves as a log to prevent infinite save loop
* @var array
*/
private static $saved = [];
/**
* Entity attributes
* @var ArrayObject
*/
protected $attributes;
/**
* @var EntityAttributeBuilder
*/
protected $attributeBuilder;
/**
* @var string Entity collection name
*/
protected static $entityCollection = null;
/**
* View mask (used for grids and many2one input fields)
* @var string
*/
protected static $entityMask = '{id}';
/**
* This method is called during instantiation to build entity structure
* @return void
*/
protected abstract function entityStructure();
/**
* Get collection name
* @return string
*/
public static function getEntityCollection()
{
return static::$entityCollection;
}
/**
* Find entity by ID
*
* @param $id
*
* @return null|EntityAbstract
*/
public static function findById($id)
{
if (!$id || strlen($id) != 24) {
return null;
}
$instance = static::entity()->get(get_called_class(), $id);
if ($instance) {
return $instance;
}
$data = static::entity()->getDatabase()->findOne(static::$entityCollection, ['_id' => new \MongoId($id)]);
if (!$data) {
return null;
}
$instance = new static;
$data['__webiny_db__'] = true;
$instance->populate($data);
return static::entity()->add($instance);
}
/**
* Count records using given criteria
*
* @param array $conditions
*
* @return int
*
*/
public static function count(array $conditions = [])
{
return static::entity()->getDatabase()->count(static::$entityCollection, $conditions);
}
/**
* Find entity by array of conditions
*
* @param array $conditions
*
* @return null|EntityAbstract
* @throws EntityException
*/
public static function findOne(array $conditions = [])
{
$data = static::entity()->getDatabase()->findOne(static::$entityCollection, $conditions);
if (!$data) {
return null;
}
$instance = new static;
$data['__webiny_db__'] = true;
$instance->populate($data);
return static::entity()->add($instance);
}
/**
* Find a random entity
*
* @param array $conditions
*
* @return null|EntityAbstract
* @throws EntityException
*/
public static function random(array $conditions = [])
{
$count = static::entity()->getDatabase()->count(static::$entityCollection, $conditions);
if ($count === 0) {
return null;
}
$instance = new static;
$data = static::find($conditions, [], 1, rand(0, $count));
return $data[0];
}
/**
* Find entities
*
* @param mixed $conditions
*
* @param array $order Example: ['-name', '+title']
* @param int $limit
* @param int $page
*
* @return EntityCollection
*/
public static function find(array $conditions = [], array $order = [], $limit = 0, $page = 0)
{
/**
* Convert order parameters to Mongo format
*/
$order = self::parseOrderParameters($order);
$offset = $limit * ($page > 0 ? $page - 1 : 0);
return new EntityCollection(get_called_class(), static::$entityCollection, $conditions, $order, $limit, $offset);
}
/**
* Entity constructor
*/
public function __construct()
{
if (!$this->attributes) {
$this->attributes = $this->arr();
}
if (!$this->attributeBuilder) {
$this->attributeBuilder = new EntityAttributeBuilder($this, $this->attributes);
}
/**
* Add ID to the list of attributes
*/
$this->attr('id')->char();
$this->entityStructure();
}
/**
* @param $attribute
*
* @return EntityAttributeBuilder
*/
public function attr($attribute)
{
return $this->attributeBuilder->attr($attribute);
}
/**
* Convert EntityAbstract to array with specified fields.
* If no fields are specified, array will contain all simple and Many2One attributes
*
* @param string $fields List of fields to extract
*
* @param int $nestedLevel How many levels to extract (Default: 1, means SELF + 1 level)
*
* @return array
*/
public function toArray($fields = '', $nestedLevel = 1)
{
$dataExtractor = new EntityDataExtractor($this, $nestedLevel);
return $dataExtractor->extractData($fields);
}
/**
* Return string representation of entity
* @return mixed
*/
public function __toString()
{
return $this->getMaskedValue();
}
/**
* Is this entity already saved?
*
* @return bool
*/
public function exists()
{
return $this->id !== null;
}
/**
* Get entity attribute
*
* @param string $attribute
*
* @throws EntityException
* @return AttributeAbstract
*/
public function getAttribute($attribute)
{
if (!$this->attributes->keyExists($attribute)) {
throw new EntityException(EntityException::ATTRIBUTE_NOT_FOUND, [
$attribute,
get_class($this)
]);
}
return $this->attributes[$attribute];
}
/**
* Get all entity attributes
*
* @return ArrayObject
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* Get entity ID
* @return CharAttribute
*/
public function getId()
{
return $this->attributes['id'];
}
public function getMaskedValue()
{
$maskItems = [];
preg_match_all('/\{(.*?)\}/', static::$entityMask, $maskItems);
$maskedValue = $this->str(static::$entityMask);
foreach ($maskItems[1] as $attr) {
$maskedValue->replace('{' . $attr . '}', $this->getAttribute($attr)->getValue());
}
return $maskedValue->val();
}
/**
* Save entity attributes to database
*/
public function save()
{
$data = [];
foreach ($this->getAttributes() as $key => $attr) {
if (!$this->isInstanceOf($attr, AttributeType::ONE2MANY) && !$this->isInstanceOf($attr, AttributeType::MANY2MANY)) {
if ($attr->getStoreToDb()) {
$data[$key] = $attr->getDbValue();
}
}
}
/**
* Insert or update
*/
if (!$this->exists()) {
$data['_id'] = new \MongoId();
$data['id'] = (string)$data['_id'];
$this->entity()->getDatabase()->insert(static::$entityCollection, $data);
$this->id = $data['id'];
} else {
// Check if this entity was already saved during save cycle through other relational attributes
if (array_key_exists($this->id, self::$saved)) {
return;
}
$where = ['_id' => new \MongoId($this->id)];
$this->entity()->getDatabase()->update(static::$entityCollection, $where, ['$set' => $data], ['upsert' => true]);
}
// Store this entity's id to prevent infinite saving loop
self::$saved[$this->id] = true;
/**
* Now save One2Many values
*/
foreach ($this->getAttributes() as $attr) {
/* @var $attr One2ManyAttribute */
if ($this->isInstanceOf($attr, AttributeType::ONE2MANY) && $attr->isLoaded()) {
foreach ($attr->getValue() as $item) {
$item->getAttribute($attr->getRelatedAttribute())->setValue($this);
$item->save();
}
/**
* The value of one2many attribute must be set to null to trigger data reload on next access.
* This is necessary when we have circular references, and parent record does not get it's many2one ID saved
* until all child referenced objects are saved. Only then can we get proper links between referenced classes.
*/
$attr->setValue(null, true);
}
}
/**
* Now save Many2Many values
*/
foreach ($this->getAttributes() as $attr) {
/* @var $attr Many2ManyAttribute */
if ($this->isInstanceOf($attr, AttributeType::MANY2MANY)) {
Many2ManyStorage::getInstance()->save($attr);
}
}
// Now that this entity is saved, remove its id from save log
unset(self::$saved[$this->id]);
return true;
}
/**
* Delete entity
* @return bool
* @return bool
* @throws EntityException
*/
public function delete()
{
/**
* Check for many2many attributes and make sure related Entity has a corresponding many2many attribute defined.
* If not - deleting is not allowed.
*/
/* @var $attr Many2ManyAttribute */
$thisClass = '\\' . get_class($this);
foreach ($this->getAttributes() as $attrName => $attr) {
if ($this->isInstanceOf($attr, AttributeType::MANY2MANY)) {
$foundMatch = false;
$relatedClass = $attr->getEntity();
$relatedEntity = new $relatedClass;
/* @var $relAttr Many2ManyAttribute */
foreach ($relatedEntity->getAttributes() as $relAttr) {
if ($this->isInstanceOf($relAttr, AttributeType::MANY2MANY) && $relAttr->getEntity() == $thisClass) {
$foundMatch = true;
}
}
if (!$foundMatch) {
throw new EntityException(EntityException::NO_MATCHING_MANY2MANY_ATTRIBUTE_FOUND, [
$thisClass,
$relatedClass,
$attrName
]);
}
}
}
/**
* First check all one2many records to see if deletion is restricted
*/
$deleteAttributes = [];
foreach ($this->getAttributes() as $key => $attr) {
if ($this->isInstanceOf($attr, AttributeType::ONE2MANY)) {
/* @var $attr One2ManyAttribute */
if ($attr->getOnDelete() == 'restrict' && $this->getAttribute($key)->getValue()->count() > 0) {
throw new EntityException(EntityException::ENTITY_DELETION_RESTRICTED, [$key]);
}
$deleteAttributes[] = $key;
}
}
/**
* Delete many2many records
*/
foreach ($this->getAttributes() as $attr) {
/* @var $attr Many2ManyAttribute */
if ($this->isInstanceOf($attr, AttributeType::MANY2MANY)) {
$firstClassName = $this->extractClassName($attr->getParentEntity());
$query = [$firstClassName => $this->id];
$this->entity()->getDatabase()->remove($attr->getIntermediateCollection(), $query);
}
}
/**
* Delete one2many records
*/
foreach ($deleteAttributes as $attr) {
foreach ($this->getAttribute($attr)->getValue() as $item) {
$item->delete();
}
}
/**
* Delete $this
*/
$this->entity()->getDatabase()->remove(static::$entityCollection, ['_id' => $this->entity()->getDatabase()->id($this->id)]);
static::entity()->remove($this);
return true;
}
/**
* Populate entity with given data
*
* @param array $data
*
* @throws EntityException
* @return $this
*/
public function populate($data)
{
if (is_null($data)) {
return $this;
}
$data = $this->normalizeData($data);
$fromDb = false;
if ($this->isDbData($data)) {
$fromDb = true;
} else {
unset($data['id']);
unset($data['_id']);
}
$validation = $this->arr();
/* @var $entityAttribute AttributeAbstract */
foreach ($this->attributes as $attributeName => $entityAttribute) {
if (!$entityAttribute->getAfterPopulate()) {
$this->populateAttribute($attributeName, $entityAttribute, $validation, $data, $fromDb);
}
}
foreach ($this->attributes as $attributeName => $entityAttribute) {
if ($entityAttribute->getAfterPopulate()) {
$this->populateAttribute($attributeName, $entityAttribute, $validation, $data, $fromDb);
}
}
if ($validation->count() > 0) {
$attributes = [];
foreach ($validation as $attr => $error) {
foreach ($error as $key => $value) {
$attributes[$key] = $value;
}
}
$ex = new EntityException(EntityException::VALIDATION_FAILED, [$validation->count()]);
$ex->setInvalidAttributes($attributes);
throw $ex;
}
return $this;
}
/**
* This method allows us to use simplified accessor methods.
* Ex: $person->company->name
*
* @param $name
*
* @return AttributeAbstract
*/
public function __get($name)
{
return $this->getAttribute($name)->getValue();
}
/**
* This method allows setting attribute values through simple assignment
* Ex: $person->name = 'Webiny';
*
* @param $name
* @param $value
*/
public function __set($name, $value)
{
$this->getAttribute($name)->setValue($value);
}
/**
* (PHP 5 >= 5.0.0)<br/>
* Whether a offset exists
* @link http://php.net/manual/en/arrayaccess.offsetexists.php
*
* @param mixed $offset <p>
* An offset to check for.
* </p>
*
* @return boolean true on success or false on failure.
* </p>
* <p>
* The return value will be casted to boolean if non-boolean was returned.
*/
public function offsetExists($offset)
{
return isset($this->attributes[$offset]);
}
/**
* (PHP 5 >= 5.0.0)<br/>
* Offset to retrieve
* @link http://php.net/manual/en/arrayaccess.offsetget.php
*
* @param mixed $offset <p>
* The offset to retrieve.
* </p>
*
* @return mixed Can return all value types.
*/
public function offsetGet($offset)
{
return $this->__get($offset);
}
/**
* (PHP 5 >= 5.0.0)<br/>
* Offset to set
* @link http://php.net/manual/en/arrayaccess.offsetset.php
*
* @param mixed $offset <p>
* The offset to assign the value to.
* </p>
* @param mixed $value <p>
* The value to set.
* </p>
*
* @return void
*/
public function offsetSet($offset, $value)
{
$this->__set($offset, $value);
}
/**
* (PHP 5 >= 5.0.0)<br/>
* Offset to unset
* @link http://php.net/manual/en/arrayaccess.offsetunset.php
*
* @param mixed $offset <p>
* The offset to unset.
* </p>
*
* @return void
*/
public function offsetUnset($offset)
{
// Nothing to unset
}
/**
* Used for checking if the entity populate data is coming from database
*
* @param $data
*
* @return bool
*/
protected function isDbData($data)
{
return isset($data['__webiny_db__']) && $data['__webiny_db__'];
}
/**
* Parse order parameters and construct parameters suitable for MongoDB
*
* @param $order
*
* @return array
*/
private static function parseOrderParameters($order)
{
$parsedOrder = [];
if (count($order) > 0) {
foreach ($order as $key => $o) {
// Check if $order array is already formatted properly
if (!is_numeric($key) && is_numeric($o)) {
$parsedOrder[$key] = $o;
continue;
}
$o = self::str($o);
if ($o->startsWith('-')) {
$parsedOrder[$o->subString(1, 0)->val()] = -1;
} elseif ($o->startsWith('+')) {
$parsedOrder[$o->subString(1, 0)->val()] = 1;
} else {
$parsedOrder[$o->val()] = 1;
}
}
}
return $parsedOrder;
}
private function populateAttribute($attributeName, AttributeAbstract $entityAttribute, $validation, $data, $fromDb)
{
// Skip population of protected attributes if data is not coming from DB
if (!$fromDb && $entityAttribute->getSkipOnPopulate()) {
return;
}
// Dynamic attributes from database should be populated without any checks, and skipped otherwise
if ($this->isInstanceOf($entityAttribute, AttributeType::DYNAMIC)) {
if ($fromDb && isset($data[$attributeName])) {
$entityAttribute->setValue($data[$attributeName], $fromDb);
}
return;
}
/**
* Check if attribute is required and it's value is set or maybe value was already assigned
*/
$hasValue = $entityAttribute->hasValue();
if ($entityAttribute->isRequired() && !isset($data[$attributeName]) && !$this->exists() && !$hasValue) {
$message = $entityAttribute->getValidationMessages('required');
if (!$message) {
$message = ValidationException::REQUIRED;
}
$ex = new ValidationException(ValidationException::VALIDATION_FAILED);
$ex->addError($attributeName, $message, []);
$validation[$attributeName] = $ex;
return;
}
/**
* In case it is an update - if the attribute is not in new $data, it's no big deal, we already have the previous value.
*/
$dataIsSet = array_key_exists($attributeName, $data);
if (!$dataIsSet && $this->exists()) {
return;
}
$canPopulate = !$this->exists() || $fromDb || !$entityAttribute->getOnce();
if ($dataIsSet && $canPopulate) {
$dataValue = $data[$attributeName];
$isOne2Many = $this->isInstanceOf($entityAttribute, AttributeType::ONE2MANY);
$isMany2Many = $this->isInstanceOf($entityAttribute, AttributeType::MANY2MANY);
$isMany2One = $this->isInstanceOf($entityAttribute, AttributeType::MANY2ONE);
if ($isMany2One) {
try {
// If simple ID or null - set and forget
if (is_string($dataValue) || is_null($dataValue)) {
$entityAttribute->setValue($dataValue, $fromDb);
return;
}
$entityAttribute->setValue($dataValue, $fromDb);
} catch (ValidationException $e) {
$validation[$attributeName] = $e;
return;
}
} elseif ($isOne2Many) {
$entityClass = $entityAttribute->getEntity();
$entityCollectionClass = '\Webiny\Component\Entity\EntityCollection';
// Validate One2Many attribute value
if (!$this->isArray($dataValue) && !$this->isArrayObject($dataValue) && !$this->isInstanceOf($dataValue,
$entityCollectionClass)
) {
$ex = new ValidationException(ValidationException::VALIDATION_FAILED);
$ex->addError($attributeName, ValidationException::DATA_TYPE, [
'array, ArrayObject or EntityCollection',
gettype($dataValue)
]);
$validation[$attributeName] = $ex;
return;
}
/* @var $entityAttribute One2ManyAttribute */
$values = [];
foreach ($dataValue as $item) {
$itemEntity = false;
// $item can be an array of data, EntityAbstract or a simple MongoId string
if ($this->isInstanceOf($item, '\Webiny\Component\Entity\EntityAbstract')) {
$itemEntity = $item;
} elseif ($this->isArray($item) || $this->isArrayObject($item)) {
$itemEntity = $entityClass::findById(isset($item['id']) ? $item['id'] : false);
} elseif ($this->isString($item) && $this->entity()->getDatabase()->isMongoId($item)) {
$itemEntity = $entityClass::findById($item);
}
// If instance was not found, create a new entity instance
if (!$itemEntity) {
$itemEntity = new $entityClass;
}
// If $item is an array - use it to populate the entity instance
if ($this->isArray($item) || $this->isArrayObject($item)) {
$itemEntity->populate($item);
}
$values[] = $itemEntity;
}
// Set attribute value
$entityAttribute->setValue($values);
} elseif ($isMany2Many) {
$entityAttribute->add($dataValue);
} else {
try {
$entityAttribute->setValue($dataValue, $fromDb);
} catch (ValidationException $e) {
$validation[$attributeName] = $e;
}
}
}
}
/**
* Extract short class name from class namespace or class instance
*
* @param string|EntityAbstract $class
*
* @return string
*/
private function extractClassName($class)
{
if (!$this->isString($class)) {
$class = get_class($class);
}
return $this->str($class)->explode('\\')->last()->val();
}
private function normalizeData($data)
{
if ($data instanceof MongoResult) {
return $data->toArray();
}
if ($this->isArray($data) || $this->isArrayObject($data)) {
return StdObjectWrapper::toArray($data);
}
return $data;
}
}