forked from RhubarbPHP/Module.Stem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel.php
More file actions
832 lines (685 loc) · 22.9 KB
/
Copy pathModel.php
File metadata and controls
832 lines (685 loc) · 22.9 KB
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
<?php
/*
* Copyright 2015 RhubarbPHP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Rhubarb\Stem\Models;
require_once __DIR__ . '/../Schema/SolutionSchema.php';
require_once __DIR__ . '/../Schema/ModelSchema.php';
use Rhubarb\Crown\Events\EventEmitter;
use Rhubarb\Crown\Modelling\ModelState;
use Rhubarb\Stem\Collections\Collection;
use Rhubarb\Stem\Decorators\DataDecorator;
use Rhubarb\Stem\Exceptions\DeleteModelException;
use Rhubarb\Stem\Exceptions\ModelConsistencyValidationException;
use Rhubarb\Stem\Exceptions\RecordNotFoundException;
use Rhubarb\Stem\Filters\Filter;
use Rhubarb\Stem\Repositories\Repository;
use Rhubarb\Stem\Schema\ModelSchema;
use Rhubarb\Stem\Schema\SolutionSchema;
/**
* The standard active record implementation in the Core
*
* This class serves as a base class for model objects
*
* @property string UniqueIdentifierColumnName
* @property string UniqueIdentifier
*/
abstract class Model extends ModelState
{
use EventEmitter {
RaiseEvent as TraitRaiseEvent;
}
private $eventsToRaiseAfterSave = [];
public final function __construct($uniqueIdentifier = null)
{
$this->modelName = SolutionSchema::getModelNameFromClass(get_class($this));
if ($this->modelName === null) {
// If our model hasn't been registered with the SolutionSchema - we can still use it
// However we will assume that the model name would have been just the last part of the
// full class name.
$this->modelName = basename(str_replace("\\", "/", get_class($this)));
}
$schema = $this->getSchema();
$this->uniqueIdentifierColumnName = $schema->uniqueIdentifierColumnName;
if (!isset(self::$modelDataTransforms[$this->modelName])) {
// Ensure we have our model transforms in place.
self::$modelDataTransforms[$this->modelName] = [];
$schema = $this->getSchema();
$columns = $schema->getColumns();
foreach ($columns as $column) {
self::$modelDataTransforms[$this->modelName][$column->columnName] =
[
$column->getTransformFromModelData(),
$column->getTransformIntoModelData()
];
}
}
if ($uniqueIdentifier !== null) {
$repository = $this->getRepository();
$repository->hydrateObject($this, $uniqueIdentifier);
} else {
$this->setDefaultValues();
}
parent::__construct();
}
public function __clone()
{
$this->setUniqueIdentifier(null);
}
/**
* Gets the most appropriate decorator for this model.
*
* @return DataDecorator
*/
public function getDecorator()
{
return DataDecorator::getDecoratorForModel($this);
}
protected function setDefaultValues()
{
$columns = $this->getSchema()->getColumns();
foreach ($columns as $column) {
if ($column->columnName == $this->UniqueIdentifierColumnName) {
continue;
}
if ($column->defaultValue !== null) {
$this[$column->columnName] = $column->defaultValue;
}
}
}
public function importRawData($data)
{
$wasNewRecord = $this->isNewRecord();
parent::importRawData($data);
$this->captureUniqueIdentifier();
if ($wasNewRecord && !$this->isNewRecord()) {
$this->onLoaded();
}
}
private function captureUniqueIdentifier()
{
$this->uniqueIdentifier = $this[$this->uniqueIdentifierColumnName];
}
function __toString()
{
return $this->getLabel();
}
/**
* Override this to perform actions when a record is loaded.
*/
protected function onLoaded()
{
}
/**
* Requests that the model data be re-fetched from the repository
*/
public function reload()
{
$this->propertyCache = [];
$repository = $this->getRepository();
$repository->reHydrateObject($this, $this->uniqueIdentifier);
}
/**
* Call this function to raise an event.
*
* In addition to $event you can pass any number of other events which are passed through
* to the event handling delegate.
*
* @param string $event The name of the event
* @return mixed|null
*/
protected function raiseEvent($event)
{
$args = func_get_args();
call_user_func_array([$this, "TraitRaiseEvent"], $args);
array_splice($args, 1, 0, [$this]);
// In addition to the standard object level event dispatch we raise a class level dispatch
// This allows global listeners like the solution schema to co-ordinate inter model activities
call_user_func_array("Rhubarb\Stem\Models\ModelEventManager::dispatchModelEvent", $args);
}
/**
* Call this function to raise an event after the model is saved.
*
* In addition to $event you can pass any number of other events which are passed through
* to the event handling delegate.
*
* @param string $event The name of the event
* @return mixed|null
*/
protected function raiseEventAfterSave($event)
{
$args = func_get_args();
$this->eventsToRaiseAfterSave[] = $args;
}
/**
*/
public function ensureRelationshipsArePopulated()
{
$className = get_class($this);
if (!isset(self::$relationships[$this->modelName])) {
self::$relationships[$this->modelName] = SolutionSchema::getAllRelationshipsForModel($this->modelName);
return $className;
}
}
protected function getPublicPropertyList()
{
$properties = [$this->uniqueIdentifierColumnName];
$schema = $this->getSchema();
if ($schema->labelColumnName != "") {
$properties[] = $schema->labelColumnName;
}
return $properties;
}
/**
* For performance the unique identifier is captured here.
*
* @var null
*/
protected $uniqueIdentifier = null;
/**
* For performance the unique identifier column name is captured here.
*
* @var null
*/
protected $uniqueIdentifierColumnName = null;
/**
* Stores the name of the model.
*
* Should only be set in the constructor of a model.
*
* @var string
*/
protected $modelName = "";
/**
* The cached repository for all objects type
*
* @var Repository[]
*/
private static $repositories = array();
/**
* A cached collection of relationships
*
* @var \Rhubarb\Stem\Schema\Relationships\Relationship[]
*/
private static $relationships = array();
/**
* A cached collection of any properties that require it.
*
* @var array
*/
private $propertyCache = [];
private static $modelDataTransforms = [];
/**
* Contains an array of relationship names that should be automatically hydrated when loading this model.
*
* Designed to be set by the child class in it's constructor.
*
* Auto hydrating relationships allows for faster sorting and filtering on collections where the sort or
* filter is on a related model column. However it does result in larger data sets being stored in memory
* so it is worth performing bench marks to be sure the auto hydration is in fact having a positive rather
* than negative impact.
*
* NOT YET IMPLEMENTED
*
* @var array
*/
protected $autoHydratedRelationships = [];
/**
* Returns the cached repository and generates one if it doesn't exist.
*
* @see DataObject::CreateRepository()
* @return \Rhubarb\Stem\Repositories\Repository
*/
public final function getRepository()
{
if (!isset(self::$repositories[$this->modelName])) {
self::$repositories[$this->modelName] = $this->createRepository();
}
return self::$repositories[$this->modelName];
}
/**
* Removes all repositories from all models.
*
* Generally only used in unit testing to allow the default repository to be changed.
*/
public static function deleteRepositories()
{
self::$repositories = [];
}
/**
* Creates the repository appropriate for this object type.
*
* To be overridden when necessary.
*
* @throws \Rhubarb\Stem\Exceptions\ModelException
* @return \Rhubarb\Stem\Repositories\Repository
*/
protected function createRepository()
{
return Repository::getNewDefaultRepository($this);
}
/**
* Removes the cache of objects from the repository representing this model type.
*/
public static function clearObjectCache()
{
$object = SolutionSchema::getModel(get_called_class());
$repository = $object->getRepository();
$repository->clearObjectCache();
}
/**
* Blitzes the repositories.
*
* After this call all cached data for model objects will be lost and repositories will be recreated when
* next required.
*/
public static function clearAllRepositories()
{
self::$repositories = [];
}
public function clearPropertyCache()
{
$this->propertyCache = [];
}
/**
* Finds the first model matching the given filters.
*
* @param Filter $filter
* @throws RecordNotFoundException
* @return Model
*/
public static function findFirst(Filter $filter = null)
{
$results = self::find($filter);
if (sizeof($results) == 0) {
throw new RecordNotFoundException(get_called_class(), 0);
}
return $results[0];
}
/**
* Finds the last model matching the given filters.
*
* @param Filter $filter
* @throws RecordNotFoundException
* @return Model
*/
public static function findLast(Filter $filter = null)
{
$results = self::find($filter);
$modelClass = get_called_class();
$model = new $modelClass();
$results->addSort($model->getUniqueIdentifierColumnName(), false);
if (sizeof($results) == 0) {
throw new RecordNotFoundException(get_called_class(), 0);
}
return $results[0];
}
/**
* Returns the Collection of models matching the given filter.
*
* @param Filter $filter
* @return Collection
*/
public static function find(Filter $filter = null)
{
$modelClass = get_called_class();
$collections = new Collection($modelClass);
if ($filter !== null) {
$collections->filter($filter);
}
return $collections;
}
/**
* Returns the schema for this data object.
*
* @return \Rhubarb\Stem\Schema\ModelSchema
*/
abstract protected function createSchema();
protected function extendSchema(ModelSchema $schema)
{
}
public final function generateSchema()
{
$schema = $this->createSchema();
$this->extendSchema($schema);
return $schema;
}
/**
* Returns a cached instance of the model schema.
*
* @return \Rhubarb\Stem\Schema\ModelSchema
*/
public final function getSchema()
{
return $this->getRepository()->getSchema();
}
/**
* Get's the label for this model object.
*
* Uses the labelColumnName provided by the model schema.
*/
public function getLabel()
{
$schema = $this->getSchema();
if ($schema->labelColumnName == "") {
return "";
}
return $this[$schema->labelColumnName];
}
/**
* Gets the name of the label column.
*
* @return string
*/
public function getLabelColumnName()
{
$schema = $this->getSchema();
return $schema->labelColumnName;
}
/**
* Persists the model data associated with this data object with the relevant repository.
*
* Calls beforeSave() and afterSave() as appropriate.
*/
public final function save($forceSaveRegardlessOfState = false)
{
try {
$this->isConsistent();
} catch (ModelConsistencyValidationException $er) {
// If the model isn't consistent we don't let it get into the database.
throw $er;
}
if (!$forceSaveRegardlessOfState && !$this->isNewRecord() && !$this->hasChanged()) {
return $this->uniqueIdentifier;
}
$this->beforeSave();
$this->raiseEvent("BeforeSave");
$repository = $this->getRepository();
$repository->saveObject($this);
$this->raiseAfterSaveEvents();
$this->afterSave();
$this->raiseEvent("AfterSave");
$this->takeChangeSnapshot();
return $this->uniqueIdentifier;
}
private function raiseAfterSaveEvents()
{
foreach ($this->eventsToRaiseAfterSave as $eventArgs) {
call_user_func_array(array($this, "raiseEvent"), $eventArgs);
}
$this->eventsToRaiseAfterSave = [];
}
/**
* Override this to make changes just before the model is committed to the repository during a save operation
*/
protected function beforeSave()
{
}
/**
* Override this to make changes just after the model has been committed to the repository during a save operation
*/
protected function afterSave()
{
}
public function delete()
{
if ($this->isNewRecord()) {
throw new DeleteModelException("New models can't be deleted.");
}
$this->beforeDelete();
$this->raiseEvent("BeforeDelete");
$repository = $this->getRepository();
$repository->deleteObject($this);
$this->afterDelete();
$this->raiseEvent("AfterDelete");
}
/**
* Override this to make changes just before the model is deleted from the repository during a delete operation
*/
protected function beforeDelete()
{
}
/**
* Override this to make changes just after the model has been deleted from the repository during a delete operation
*/
protected function afterDelete()
{
}
/**
* Get's the name of the unique identifier column for this object.
*
* This consults the schema to determine this so don't over use this method.
* Potentially we might cache the result of createSchema() to ensure this isn't a performance
* burden.
*
* @return string
*/
public function getUniqueIdentifierColumnName()
{
return $this->uniqueIdentifierColumnName;
}
/**
* Get's the unique identifier for this record or null if it doesn't have one.
*
* @return null
*/
public function getUniqueIdentifier()
{
return $this->uniqueIdentifier;
}
/**
* Returns the name of the model.
*
* Normally the alias provided in the solution scheme, unless the model is unregistered in which case
* it will be the last part of the class name.
*
* @return string
*/
public function getModelName()
{
return $this->modelName;
}
/**
* Set's the unique identifier for this object.
*
* This method is provided for the repositories to update newly created objects with their
* unique identifier and should not be used in any other circumstances unless you really know
* what you're doing!
*
* @param $value
*/
public function setUniqueIdentifier($value)
{
$this[$this->uniqueIdentifierColumnName] = $value;
}
/**
* Returns true if the record is new, by virtue of not having a unique identifier.
*
* @return bool
*/
public function isNewRecord()
{
$identifier = $this->uniqueIdentifier;
return ($identifier === null);
}
public function __set($propertyName, $value)
{
if ($propertyName == $this->uniqueIdentifierColumnName) {
$this->uniqueIdentifier = $value;
}
if (isset(self::$modelDataTransforms[$this->modelName][$propertyName][1])) {
$closure = self::$modelDataTransforms[$this->modelName][$propertyName][1];
$value = $closure($value);
}
if (strpos($propertyName, ".") !== false) {
$parts = explode(".", $propertyName);
$firstStep = $this[$parts[0]];
if ($firstStep === null || !($firstStep instanceof Model)) {
// If the next item in the chain is not model object we can't ask it to
// set it's value.
return;
}
$firstStep[$parts[1]] = $value;
} else {
parent::__set($propertyName, $value);
if (isset($this->propertyCache[$propertyName])) {
$this->propertyCache[$propertyName] = $propertyName;
}
}
}
public function __isset($propertyName)
{
if (parent::__isset($propertyName)) {
return true;
}
$schema = $this->getSchema();
$columns = $schema->getColumns();
// Check for schema columns
if (isset($columns[$propertyName])) {
return true;
}
// Check for dot operator
if (strpos($propertyName, ".") !== false) {
$parts = explode(".", $propertyName);
$firstStep = $this[$parts[0]];
if ($firstStep === null || !($firstStep instanceof Model)) {
// If the next item in the chain is not model object we can't ask it to
// set it's value.
return false;
}
if (isset($firstStep[$parts[1]])) {
return true;
}
}
// Check for relationships
$className = get_class($this);
if (!isset(self::$relationships[$className])) {
self::$relationships[$className] = SolutionSchema::getAllRelationshipsForModel($this->modelName);
}
if (isset(self::$relationships[$className][$propertyName])) {
return true;
}
return false;
}
public function __get($propertyName)
{
// Should any type of magical getter below require that the value is cached for performance
// this boolean will be set to true. At the end of the function we pick up on this and do the
// caching - instead of having the caching line repeated all over the place.
$addToPropertyCache = false;
$value = parent::__get($propertyName);
if ($value === null) {
if (isset($this->propertyCache[$propertyName])) {
return $this->propertyCache[$propertyName];
}
// Handle the dot operator by passing control to the next object in the chain.
if (strpos($propertyName, ".") !== false) {
$parts = explode(".", $propertyName, 2);
$firstStep = $this[$parts[0]];
if ($firstStep === null || !($firstStep instanceof Model)) {
// If the next item in the chain is not model object we can't ask it to return
// a value can we!
return null;
}
return $firstStep[$parts[1]];
}
$this->ensureRelationshipsArePopulated();
if (isset(self::$relationships[$this->modelName][$propertyName])) {
$relationship = self::$relationships[$this->modelName][$propertyName];
$value = $relationship->fetchFor($this);
if ($value instanceof Model) {
$addToPropertyCache = true;
}
}
}
if ($addToPropertyCache) {
$this->propertyCache[$propertyName] = $value;
}
if (isset(self::$modelDataTransforms[$this->modelName][$propertyName][0])) {
$closure = self::$modelDataTransforms[$this->modelName][$propertyName][0];
$value = $closure($value);
}
return $value;
}
/**
* Returns the schema Column object for the matching column reference.
*
* A column reference might be a column name or a Relationship.ColumnName expressions.
*
* @param $columnReference
* @return null|\Rhubarb\Stem\Schema\Columns\Column
*/
public function getColumnSchemaForColumnReference($columnReference)
{
if (strpos($columnReference, ".") !== false) {
$parts = explode(".", $columnReference);
$relationshipName = $parts[0];
$this->ensureRelationshipsArePopulated();
if (isset(self::$relationships[$this->modelName][$relationshipName])) {
$relationship = self::$relationships[$this->modelName][$relationshipName];
$relatedModel = SolutionSchema::getModel($relationship->getTargetModelName());
return $relatedModel->getColumnSchemaForColumnReference($parts[1]);
}
}
$schema = $this->getSchema();
$columns = $schema->getColumns();
if (isset($columns[$columnReference])) {
return $columns[$columnReference];
}
return null;
}
/**
* Override to apply validation rules.
*
* Return a dictionary of key value pairs, the value being the validation message
* and the key being a reference to the test undertaken (normally the column being
* tested)
*
* Return an empty array if all is well.
*
* @return string[]
*/
protected function getConsistencyValidationErrors()
{
return [];
}
/**
* Returns true of the data in the model is consistent with the entity we are trying to model.
*
* To implement your validation rules overide the getConsistencyValidationErrors()
*
* @param bool $throwException Set to false to stop an exception being thrown if the models is inconsistent
* @throws \Exception
* @throws \Rhubarb\Stem\Exceptions\ModelConsistencyValidationException
* @return bool
*/
public final function isConsistent($throwException = true)
{
$errors = $this->getConsistencyValidationErrors();
if (sizeof($errors) == 0) {
return true;
}
if ($throwException) {
throw new ModelConsistencyValidationException($errors);
}
return false;
}
/**
* Override this method to check for/create specific initial records
*/
public static function checkRecords($oldVersion, $newVersion)
{
}
}