-
Notifications
You must be signed in to change notification settings - Fork 2
/
AbstractEntity.php
executable file
·719 lines (628 loc) · 20 KB
/
AbstractEntity.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
<?php
/**
* Webiny Framework (http://www.webiny.com/framework)
*
* @copyright Copyright Webiny LTD
*/
namespace Webiny\Component\Entity;
use Webiny\Component\Entity\Attribute\AbstractAttribute;
use Webiny\Component\Entity\Attribute\AttributeType;
use Webiny\Component\Entity\Attribute\Validation\ValidationException;
use Webiny\Component\Entity\Attribute\Many2ManyAttribute;
use Webiny\Component\Entity\Attribute\One2ManyAttribute;
use Webiny\Component\StdLib\FactoryLoaderTrait;
use Webiny\Component\StdLib\StdLibTrait;
use Webiny\Component\StdLib\StdObject\StdObjectWrapper;
/**
* Entity
* @package \Webiny\Component\Entity
*/
abstract class AbstractEntity 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 EntityAttributeContainer
*/
protected $attributes;
/**
* @var string Entity collection name
*/
protected static $collection = null;
/**
* View mask (used for generation of readable string when converting an instance to string)
* @var string
*/
protected static $mask = '{id}';
/**
* Get collection name
* @return string
*/
public static function getCollection()
{
return static::$collection;
}
/**
* Find entity by ID
*
* @param $id
*
* @return null|AbstractEntity
*/
public static function findById($id)
{
if (!$id || strlen($id) != 24) {
return null;
}
$instance = static::entity()->get(get_called_class(), $id);
if ($instance) {
return $instance;
}
$mongo = static::entity()->getDatabase();
$data = $mongo->findOne(static::$collection, ['_id' => $mongo->id($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::$collection, $conditions);
}
/**
* Find entity by array of conditions
*
* @param array $conditions
*
* @return null|AbstractEntity
* @throws EntityException
*/
public static function findOne(array $conditions = [])
{
$data = static::entity()->getDatabase()->findOne(static::$collection, $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|AbstractEntity
* @throws EntityException
*/
public static function random(array $conditions = [])
{
$count = static::entity()->getDatabase()->count(static::$collection, $conditions);
if ($count === 0) {
return null;
}
$data = static::find($conditions, [], 1, rand(0, $count));
return $data[0];
}
/**
* Finds one or more latest entities
*
* @param int $limit
*
* @return mixed|null
*/
public static function latest($limit = 1)
{
$data = static::find([], ['_id' => -1], $limit);
return $limit == 1 ? $data->first() : $data;
}
/**
* 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);
$data = self::entity()->getDatabase()->find(static::$collection, $conditions, $order, $limit, $offset);
$parameters = [
'conditions' => $conditions,
'order' => $order,
'limit' => $limit,
'offset' => $offset
];
return new EntityCollection(get_called_class(), $data, $parameters);
}
/**
* Entity constructor
*/
public function __construct()
{
/**
* Add ID to the list of attributes
*/
$this->attr('id')->char();
}
/**
* @param string $attribute
*
* @return EntityAttributeContainer
*/
public function attr($attribute)
{
if (!$this->attributes instanceof EntityAttributeContainer) {
$this->attributes = $this->createEntityAttributeContainer();
}
return $this->attributes->attr($attribute);
}
/**
* Convert AbstractEntity 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
*
* @return array
*/
public function toArray($fields = '')
{
$dataExtractor = new EntityDataExtractor($this);
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 AbstractAttribute
*/
public function getAttribute($attribute)
{
if (!isset($this->attributes[$attribute])) {
throw new EntityException(EntityException::ATTRIBUTE_NOT_FOUND, [
$attribute,
get_class($this)
]);
}
return $this->attributes[$attribute];
}
/**
* Get all entity attributes
*
* @return EntityAttributeContainer
*/
public function getAttributes()
{
return $this->attributes;
}
public function getMaskedValue()
{
$maskItems = [];
preg_match_all('/\{(.*?)\}/', static::$mask, $maskItems);
$maskedValue = $this->str(static::$mask);
foreach ($maskItems[1] as $attr) {
$maskedValue->replace('{' . $attr . '}', $this->getAttribute($attr)->getValue());
}
return $maskedValue->val();
}
/**
* Save entity attributes to database
*/
public function save()
{
$objectHash = spl_object_hash($this);
if (array_key_exists($objectHash, self::$saved)) {
return true;
}
self::$saved[$objectHash] = true;
$data = [];
$validation = [];
$one2many = AttributeType::ONE2MANY;
$many2many = AttributeType::MANY2MANY;
/* @var $attr AbstractAttribute */
foreach ($this->getAttributes() as $key => $attr) {
if ($attr->isRequired() && !$attr->hasValue()) {
$ex = new ValidationException(ValidationException::VALIDATION_FAILED);
$ex->addError($key, ValidationException::REQUIRED);
$validation[$key] = $ex;
continue;
}
if (!count($validation) && !$this->isInstanceOf($attr, $one2many) && !$this->isInstanceOf($attr, $many2many)) {
if ($attr->getStoreToDb()) {
$data[$key] = $attr->getDbValue();
}
}
}
// Throw EntityException with invalid attributes
if (count($validation)) {
$attributes = [];
foreach ($validation as $attr => $error) {
foreach ($error as $key => $value) {
$attributes[$key] = $value;
}
}
$ex = new EntityException(EntityException::VALIDATION_FAILED, [get_class($this), count($validation)]);
$ex->setInvalidAttributes($attributes);
throw $ex;
}
/**
* Insert or update
*/
$mongo = $this->entity()->getDatabase();
if (!$this->exists()) {
$data['_id'] = $mongo->isId($data['id']) ? $mongo->id($data['id']) : $mongo->id();
$data['id'] = (string)$data['_id'];
$mongo->insertOne(static::$collection, $data);
$this->id = $data['id'];
} else {
$where = ['_id' => $mongo->id($this->id)];
$mongo->update(static::$collection, $where, ['$set' => $data], ['upsert' => 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)) {
$attr->save();
}
}
// Now that this entity is saved, remove it from save log
unset(self::$saved[$objectHash]);
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) && $this->isInstanceOf($this, $relAttr->getEntity())) {
$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
*/
$one2manyDelete = [];
$many2oneDelete = [];
$many2manyDelete = [];
foreach ($this->getAttributes() as $key => $attr) {
if ($this->isInstanceOf($attr, AttributeType::ONE2MANY)) {
if ($attr->getOnDelete() == 'ignore') {
continue;
}
/* @var $attr One2ManyAttribute */
if ($attr->getOnDelete() == 'restrict' && $this->getAttribute($key)->getValue()->count() > 0) {
throw new EntityException(EntityException::ENTITY_DELETION_RESTRICTED, [$key]);
}
$one2manyDelete[] = $attr;
}
if ($this->isInstanceOf($attr, AttributeType::MANY2ONE)) {
/* @var $attr Many2OneAttribute */
if ($attr->getOnDelete() === 'cascade') {
$many2oneDelete[] = $attr;
}
continue;
}
if ($this->isInstanceOf($attr, AttributeType::MANY2MANY)) {
$many2manyDelete[] = $attr;
}
}
/**
* Delete one2many records
*/
foreach ($one2manyDelete as $attr) {
foreach ($attr->getValue() as $item) {
$item->delete();
}
}
/**
* Delete many2many records
*/
foreach ($many2manyDelete as $attr) {
$attr->unlinkAll();
}
/**
* Delete many2one records that are set to 'cascade'
*/
foreach ($many2oneDelete as $attr) {
$value = $attr->getValue();
if ($value && $value instanceof AbstractEntity) {
$value->delete();
}
}
/**
* Delete $this
*/
$this->entity()->getDatabase()->delete(static::$collection, ['_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 AbstractAttribute */
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, [get_class($this), $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 AbstractAttribute
*/
public function __get($name)
{
return $this->getAttribute($name)->getValue();
}
function __call($name, $arguments)
{
$attr = $this->getAttribute($name);
return $attr->getValue($arguments);
}
/**
* 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);
}
/**
* @inheritdoc
*/
public function offsetExists($offset)
{
return isset($this->attributes[$offset]);
}
/**
* @inheritdoc
*/
public function offsetGet($offset)
{
return $this->__get($offset);
}
/**
* @inheritdoc
*/
public function offsetSet($offset, $value)
{
$this->__set($offset, $value);
}
/**
* @inheritdoc
*/
public function offsetUnset($offset)
{
// Nothing to unset
}
/**
* Get a new instance of entity attribute container
* By separating this into a method we allow other developers to create their own subclasses of EntityAttributeContainer for better autocomplete in IDEs.
*
* @return EntityAttributeContainer
*/
protected function createEntityAttributeContainer()
{
return new EntityAttributeContainer($this);
}
/**
* 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
*/
protected 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, AbstractAttribute $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) && 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
*/
if (!$fromDb && $entityAttribute->isRequired() && !isset($data[$attributeName]) && !$entityAttribute->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];
try {
$entityAttribute->setValue($dataValue, $fromDb);
} catch (ValidationException $e) {
$validation[$attributeName] = $e;
}
}
}
private function normalizeData($data)
{
if ($this->isArray($data) || $this->isArrayObject($data)) {
return StdObjectWrapper::toArray($data);
}
return $data;
}
}