-
Notifications
You must be signed in to change notification settings - Fork 518
/
fflib_SObjectDomain.cls
1125 lines (974 loc) · 34.3 KB
/
fflib_SObjectDomain.cls
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c), FinancialForce.com, inc
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the FinancialForce.com, inc nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
/**
* Base class aiding in the implementation of a Domain Model around SObject collections
*
* Domain (software engineering). “a set of common requirements, terminology, and functionality
* for any software program constructed to solve a problem in that field”,
* http://en.wikipedia.org/wiki/Domain_(software_engineering)
*
* Domain Model, “An object model of the domain that incorporates both behavior and data.”,
* “At its worst business logic can be very complex. Rules and logic describe many different "
* "cases and slants of behavior, and it's this complexity that objects were designed to work with...”
* Martin Fowler, EAA Patterns
* http://martinfowler.com/eaaCatalog/domainModel.html
*
**/
public virtual with sharing class fflib_SObjectDomain
extends fflib_SObjects
implements fflib_ISObjectDomain
{
/**
* Provides access to the data represented by this domain class
**/
public List<SObject> Records {
get
{
return getRecords();
}
}
/**
* Provides access to Trigger.oldMap and allowing it to be mocked in unit-tests
**/
@TestVisible
protected Map<Id, SObject> ExistingRecords
{
get
{
if (ExistingRecords == null)
{
if (System.Test.isRunningTest() & Test.Database.hasRecords())
{
// If in test context and records are in the mock database use those instead of Trigger.oldMap
ExistingRecords = Test.Database.oldRecords;
}
else
{
ExistingRecords = Trigger.oldMap;
}
}
return ExistingRecords;
}
private set;
}
/**
* Exposes the configuration for this domain class instance
**/
public Configuration Configuration {get; private set;}
/**
* DEPRECATED, This property has been moved to fflib_SObjects
**/
public static fflib_SObjectDomain.ErrorFactory Errors {get; private set;}
/**
* Useful during unit testing to access mock support for database inserts and updates (testing without DML)
**/
public static TestFactory Test {get; private set;}
/**
* Retains instances of domain classes implementing trigger stateful
**/
private static Map<Type, List<fflib_SObjectDomain>> TriggerStateByClass;
/**
* Retains the trigger tracking configuration used for each domain
**/
private static Map<Type, TriggerEvent> TriggerEventByClass;
static
{
Errors = new fflib_SObjectDomain.ErrorFactory();
Test = new TestFactory();
TriggerStateByClass = new Map<Type, List<fflib_SObjectDomain>>();
TriggerEventByClass = new Map<Type, TriggerEvent>();
}
/**
* Constructs the domain class with the data on which to apply the behaviour implemented within
*
* @param sObjectList A concrete list (e.g. List<Account> vs List<SObject>) of records
**/
public fflib_SObjectDomain(List<SObject> sObjectList)
{
this(sObjectList, sObjectList.getSObjectType());
}
/**
* Constructs the domain class with the data and type on which to apply the behaviour implemented within
*
* @param sObjectList A list (e.g. List<Opportunity>, List<Account>, etc.) of records
* @param sObjectType The Schema.SObjectType of the records contained in the list
*
* @remark Will support List<SObject> but all records in the list will be assumed to be of
* the type specified in sObjectType
**/
public fflib_SObjectDomain(List<SObject> sObjectList, SObjectType sObjectType)
{
// Ensure the domain class has its own copy of the data
super(sObjectList, sObjectType);
// Configure the Domain object instance
Configuration = new Configuration();
}
/**
* Override this to apply defaults to the records, this is called by the handleBeforeInsert method
**/
public virtual void onApplyDefaults() { }
/**
* Override this to apply general validation to be performed during insert or update, called by the handleAfterInsert and handleAfterUpdate methods
**/
public virtual void onValidate() { }
/**
* Override this to apply validation to be performed during insert, called by the handleAfterUpdate method
**/
public virtual void onValidate(Map<Id,SObject> existingRecords) { }
/**
* Override this to perform processing during the before insert phase, this is called by the handleBeforeInsert method
**/
public virtual void onBeforeInsert() { }
/**
* Override this to perform processing during the before update phase, this is called by the handleBeforeUpdate method
**/
public virtual void onBeforeUpdate(Map<Id,SObject> existingRecords) { }
/**
* Override this to perform processing during the before delete phase, this is called by the handleBeforeDelete method
**/
public virtual void onBeforeDelete() { }
/**
* Override this to perform processing during the after insert phase, this is called by the handleAfterInsert method
**/
public virtual void onAfterInsert() { }
/**
* Override this to perform processing during the after update phase, this is called by the handleAfterUpdate method
**/
public virtual void onAfterUpdate(Map<Id,SObject> existingRecords) { }
/**
* Override this to perform processing during the after delete phase, this is called by the handleAfterDelete method
**/
public virtual void onAfterDelete() { }
/**
* Override this to perform processing during the after undelete phase, this is called by the handleAfterDelete method
**/
public virtual void onAfterUndelete() { }
/**
* Base handler for the Apex Trigger event Before Insert, calls the onApplyDefaults method, followed by onBeforeInsert
**/
public virtual void handleBeforeInsert()
{
onApplyDefaults();
onBeforeInsert();
}
/**
* Base handler for the Apex Trigger event Before Update, calls the onBeforeUpdate method
**/
public virtual void handleBeforeUpdate(Map<Id,SObject> existingRecords)
{
onBeforeUpdate(existingRecords);
}
/**
* Base handler for the Apex Trigger event Before Delete, calls the onBeforeDelete method
**/
public virtual void handleBeforeDelete()
{
onBeforeDelete();
}
/**
* Base handler for the Apex Trigger event After Insert, checks object security and calls the onValidate and onAfterInsert methods
*
* @throws DomainException if the current user context is not able to create records
**/
public virtual void handleAfterInsert()
{
if(Configuration.EnforcingTriggerCRUDSecurity && !SObjectDescribe.isCreateable())
throw new DomainException('Permission to create an ' + SObjectDescribe.getName() + ' denied.');
onValidate();
onAfterInsert();
}
/**
* Base handler for the Apex Trigger event After Update, checks object security and calls the onValidate, onValidate(Map<Id,SObject>) and onAfterUpdate methods
*
* @throws DomainException if the current user context is not able to update records
**/
public virtual void handleAfterUpdate(Map<Id,SObject> existingRecords)
{
if(Configuration.EnforcingTriggerCRUDSecurity && !SObjectDescribe.isUpdateable())
throw new DomainException('Permission to update an ' + SObjectDescribe.getName() + ' denied.');
if(Configuration.OldOnUpdateValidateBehaviour)
onValidate();
onValidate(existingRecords);
onAfterUpdate(existingRecords);
}
/**
* Base handler for the Apex Trigger event After Delete, checks object security and calls the onAfterDelete method
*
* @throws DomainException if the current user context is not able to delete records
**/
public virtual void handleAfterDelete()
{
if(Configuration.EnforcingTriggerCRUDSecurity && !SObjectDescribe.isDeletable())
throw new DomainException('Permission to delete an ' + SObjectDescribe.getName() + ' denied.');
onAfterDelete();
}
/**
* Base handler for the Apex Trigger event After Undelete, checks object security and calls the onAfterUndelete method
*
* @throws DomainException if the current user context is not able to delete records
**/
public virtual void handleAfterUndelete()
{
if(Configuration.EnforcingTriggerCRUDSecurity && !SObjectDescribe.isUndeletable())
throw new DomainException('Permission to undelete an ' + SObjectDescribe.getName() + ' denied.');
onAfterUndelete();
}
/**
* Returns the SObjectType this Domain class represents
**/
public SObjectType sObjectType()
{
return getSObjectType();
}
/**
* Detects whether any values in context records have changed for given fields as strings
* Returns list of SObject records that have changes in the specified fields
**/
public List<SObject> getChangedRecords(Set<String> fieldNames)
{
List<SObject> changedRecords = new List<SObject>();
for (SObject newRecord : Records)
{
Id recordId = (Id) newRecord.get('Id');
if (this.ExistingRecords == null || !this.ExistingRecords.containsKey(recordId))
{
continue;
}
SObject oldRecord = this.ExistingRecords.get(recordId);
for (String fieldName : fieldNames)
{
if (oldRecord.get(fieldName) != newRecord.get(fieldName))
{
changedRecords.add(newRecord);
break; // prevents the records from being added multiple times
}
}
}
return changedRecords;
}
/**
* Detects whether any values in context records have changed for given fields as tokens
* Returns list of SObject records that have changes in the specified fields
**/
public List<SObject> getChangedRecords(Set<Schema.SObjectField> fieldTokens)
{
List<SObject> changedRecords = new List<SObject>();
for (SObject newRecord : Records)
{
Id recordId = (Id) newRecord.get('Id');
if (this.ExistingRecords == null || !this.ExistingRecords.containsKey(recordId))
{
continue;
}
SObject oldRecord = this.ExistingRecords.get(recordId);
for (Schema.SObjectField fieldToken : fieldTokens)
{
if (oldRecord.get(fieldToken) != newRecord.get(fieldToken))
{
changedRecords.add(newRecord);
break; // prevents the records from being added multiple times
}
}
}
return changedRecords;
}
/**
* Interface used to aid the triggerHandler in constructing instances of Domain classes
**/
public interface IConstructable
{
fflib_SObjectDomain construct(List<SObject> sObjectList);
}
/**
* Interface used to aid the triggerHandler in constructing instances of Domain classes
**/
public interface IConstructable2 extends IConstructable
{
fflib_SObjectDomain construct(List<SObject> sObjectList, SObjectType sObjectType);
}
/**
* For Domain classes implementing the ITriggerStateful interface returns the instance
* of the domain class being shared between trigger invocations, returns null if
* the Domain class trigger has not yet fired or the given domain class does not implement
* the ITriggerStateful interface. Note this method is sensitive to recursion, meaning
* it will return the applicable domain instance for the level of recursion
**/
public static fflib_SObjectDomain getTriggerInstance(Type domainClass)
{
List<fflib_SObjectDomain> domains = TriggerStateByClass.get(domainClass);
if(domains==null || domains.size()==0)
return null;
return domains[domains.size()-1];
}
/**
* Method constructs the given Domain class with the current Trigger context
* before calling the applicable override methods such as beforeInsert, beforeUpdate etc.
**/
public static void triggerHandler(Type domainClass)
{
// Process the trigger context
if(System.Test.isRunningTest() & Test.Database.hasRecords())
{
// If in test context and records in the mock database delegate initially to the mock database trigger handler
Test.Database.testTriggerHandler(domainClass);
}
else
{
// Process the runtime Apex Trigger context
triggerHandler(domainClass,
Trigger.isBefore,
Trigger.isAfter,
Trigger.isInsert,
Trigger.isUpdate,
Trigger.isDelete,
Trigger.isUnDelete,
Trigger.new,
Trigger.oldMap);
}
}
/**
* Calls the applicable override methods such as beforeInsert, beforeUpdate etc. based on a Trigger context
**/
private static void triggerHandler(Type domainClass, Boolean isBefore, Boolean isAfter, Boolean isInsert, Boolean isUpdate, Boolean isDelete, Boolean isUndelete, List<SObject> newRecords, Map<Id, SObject> oldRecordsMap)
{
// After phase of trigger will reuse prior instance of domain class if ITriggerStateful implemented
fflib_SObjectDomain domainObject = isBefore ? null : popTriggerInstance(domainClass, isDelete ? oldRecordsMap.values() : newRecords);
if(domainObject==null)
{
// Construct the domain class constructor class
String domainClassName = domainClass.getName();
Type constructableClass = domainClassName.endsWith('Constructor') ? Type.forName(domainClassName) : Type.forName(domainClassName+'.Constructor');
IConstructable domainConstructor = (IConstructable) constructableClass.newInstance();
// Construct the domain class with the approprite record set
if(isInsert) domainObject = domainConstructor.construct(newRecords);
else if(isUpdate) domainObject = domainConstructor.construct(newRecords);
else if(isDelete) domainObject = domainConstructor.construct(oldRecordsMap.values());
else if(isUndelete) domainObject = domainConstructor.construct(newRecords);
// Should this instance be reused on the next trigger invocation?
if(domainObject.Configuration.TriggerStateEnabled)
// Push this instance onto the stack to be popped during the after phase
pushTriggerInstance(domainClass, domainObject);
}
// has this event been disabled?
if(!getTriggerEvent(domainClass).isEnabled(isBefore, isAfter, isInsert, isUpdate, isDelete, isUndelete))
{
return;
}
// Invoke the applicable handler
if(isBefore)
{
if(isInsert) domainObject.handleBeforeInsert();
else if(isUpdate) domainObject.handleBeforeUpdate(oldRecordsMap);
else if(isDelete) domainObject.handleBeforeDelete();
}
else
{
if(isInsert) domainObject.handleAfterInsert();
else if(isUpdate) domainObject.handleAfterUpdate(oldRecordsMap);
else if(isDelete) domainObject.handleAfterDelete();
else if(isUndelete) domainObject.handleAfterUndelete();
}
}
/**
* Pushes to the stack of domain classes per type a domain object instance
**/
private static void pushTriggerInstance(Type domainClass, fflib_SObjectDomain domain)
{
List<fflib_SObjectDomain> domains = TriggerStateByClass.get(domainClass);
if(domains==null)
TriggerStateByClass.put(domainClass, domains = new List<fflib_SObjectDomain>());
domains.add(domain);
}
/**
* Pops from the stack of domain classes per type a domain object instance and updates the record set
**/
private static fflib_SObjectDomain popTriggerInstance(Type domainClass, List<SObject> records)
{
List<fflib_SObjectDomain> domains = TriggerStateByClass.get(domainClass);
if(domains==null || domains.size()==0)
return null;
fflib_SObjectDomain domain = domains.remove(domains.size()-1);
domain.setObjects(records);
return domain;
}
public static TriggerEvent getTriggerEvent(Type domainClass)
{
if(!TriggerEventByClass.containsKey(domainClass))
{
TriggerEventByClass.put(domainClass, new TriggerEvent());
}
return TriggerEventByClass.get(domainClass);
}
public class TriggerEvent
{
public boolean BeforeInsertEnabled {get; private set;}
public boolean BeforeUpdateEnabled {get; private set;}
public boolean BeforeDeleteEnabled {get; private set;}
public boolean AfterInsertEnabled {get; private set;}
public boolean AfterUpdateEnabled {get; private set;}
public boolean AfterDeleteEnabled {get; private set;}
public boolean AfterUndeleteEnabled {get; private set;}
public TriggerEvent()
{
this.enableAll();
}
// befores
public TriggerEvent enableBeforeInsert() {BeforeInsertEnabled = true; return this;}
public TriggerEvent enableBeforeUpdate() {BeforeUpdateEnabled = true; return this;}
public TriggerEvent enableBeforeDelete() {BeforeDeleteEnabled = true; return this;}
public TriggerEvent disableBeforeInsert() {BeforeInsertEnabled = false; return this;}
public TriggerEvent disableBeforeUpdate() {BeforeUpdateEnabled = false; return this;}
public TriggerEvent disableBeforeDelete() {BeforeDeleteEnabled = false; return this;}
// afters
public TriggerEvent enableAfterInsert() {AfterInsertEnabled = true; return this;}
public TriggerEvent enableAfterUpdate() {AfterUpdateEnabled = true; return this;}
public TriggerEvent enableAfterDelete() {AfterDeleteEnabled = true; return this;}
public TriggerEvent enableAfterUndelete() {AfterUndeleteEnabled = true; return this;}
public TriggerEvent disableAfterInsert() {AfterInsertEnabled = false; return this;}
public TriggerEvent disableAfterUpdate() {AfterUpdateEnabled = false; return this;}
public TriggerEvent disableAfterDelete() {AfterDeleteEnabled = false; return this;}
public TriggerEvent disableAfterUndelete(){AfterUndeleteEnabled = false; return this;}
public TriggerEvent enableAll()
{
return this.enableAllBefore().enableAllAfter();
}
public TriggerEvent disableAll()
{
return this.disableAllBefore().disableAllAfter();
}
public TriggerEvent enableAllBefore()
{
return this.enableBeforeInsert().enableBeforeUpdate().enableBeforeDelete();
}
public TriggerEvent disableAllBefore()
{
return this.disableBeforeInsert().disableBeforeUpdate().disableBeforeDelete();
}
public TriggerEvent enableAllAfter()
{
return this.enableAfterInsert().enableAfterUpdate().enableAfterDelete().enableAfterUndelete();
}
public TriggerEvent disableAllAfter()
{
return this.disableAfterInsert().disableAfterUpdate().disableAfterDelete().disableAfterUndelete();
}
public boolean isEnabled(Boolean isBefore, Boolean isAfter, Boolean isInsert, Boolean isUpdate, Boolean isDelete, Boolean isUndelete)
{
if(isBefore)
{
if(isInsert) return BeforeInsertEnabled;
else if(isUpdate) return BeforeUpdateEnabled;
else if(isDelete) return BeforeDeleteEnabled;
}
else if(isAfter)
{
if(isInsert) return AfterInsertEnabled;
else if(isUpdate) return AfterUpdateEnabled;
else if(isDelete) return AfterDeleteEnabled;
else if(isUndelete) return AfterUndeleteEnabled;
}
return true; // shouldnt ever get here!
}
}
/**
* Fluent style Configuration system for Domain class creation
**/
public class Configuration
{
/**
* Backwards compatibility mode for handleAfterUpdate routing to onValidate()
**/
public Boolean OldOnUpdateValidateBehaviour {get; private set;}
/**
* True if the base class is checking the users CRUD requirements before invoking trigger methods
**/
public Boolean EnforcingTriggerCRUDSecurity {get; private set;}
/**
* Enables reuse of the same Domain instance between before and after trigger phases (subject to recursive scenarios)
**/
public Boolean TriggerStateEnabled {get; private set;}
/**
* Default configuration
**/
public Configuration()
{
EnforcingTriggerCRUDSecurity = true; // Default is true for backwards compatability
TriggerStateEnabled = false;
OldOnUpdateValidateBehaviour = false; // Breaking change, but felt to better practice
}
/**
* See associated property
**/
public Configuration enableTriggerState()
{
TriggerStateEnabled = true;
return this;
}
/**
* See associated property
**/
public Configuration disableTriggerState()
{
TriggerStateEnabled = false;
return this;
}
/**
* See associated property
**/
public Configuration enforceTriggerCRUDSecurity()
{
EnforcingTriggerCRUDSecurity = true;
return this;
}
/**
* See associated property
**/
public Configuration disableTriggerCRUDSecurity()
{
EnforcingTriggerCRUDSecurity = false;
return this;
}
/**
* See associated property
**/
public Configuration enableOldOnUpdateValidateBehaviour()
{
OldOnUpdateValidateBehaviour = true;
return this;
}
/**
* See associated property
**/
public Configuration disableOldOnUpdateValidateBehaviour()
{
OldOnUpdateValidateBehaviour = false;
return this;
}
}
/**
* General exception class for the domain layer
**/
public class DomainException extends Exception
{
}
/**
* Ensures logging of errors in the Domain context for later assertions in tests
**/
public override String error(String message, SObject record)
{
return fflib_SObjectDomain.Errors.error(this, message, record);
}
/**
* Ensures logging of errors in the Domain context for later assertions in tests
**/
public override String error(String message, SObject record, SObjectField field)
{
return fflib_SObjectDomain.Errors.error(this, message, record, field);
}
/**
* DEPRECATED, This class has been moved to fflib_SObjects
**/
public class ErrorFactory
{
private List<Error> errorList = new List<Error>();
private ErrorFactory()
{
}
public String error(String message, SObject record)
{
return error(null, message, record);
}
private String error(fflib_SObjectDomain domain, String message, SObject record)
{
ObjectError objectError = new ObjectError();
objectError.domain = domain;
objectError.message = message;
objectError.record = record;
errorList.add(objectError);
return message;
}
public String error(String message, SObject record, SObjectField field)
{
return error(null, message, record, field);
}
private String error(fflib_SObjectDomain domain, String message, SObject record, SObjectField field)
{
FieldError fieldError = new FieldError();
fieldError.domain = domain;
fieldError.message = message;
fieldError.record = record;
fieldError.field = field;
errorList.add(fieldError);
return message;
}
public List<Error> getAll()
{
return errorList.clone();
}
public void clearAll()
{
errorList.clear();
}
}
/**
* DEPRECATED, This class has been moved to fflib_SObjects
**/
public virtual class FieldError extends ObjectError
{
public SObjectField field;
public FieldError()
{
}
}
/**
* DEPRECATED, This class has been moved to fflib_SObjects
**/
public virtual class ObjectError extends Error
{
public SObject record;
public ObjectError()
{
}
}
/**
* DEPRECATED, This class has been moved to fflib_SObjects
**/
public abstract class Error
{
public String message;
public fflib_SObjectDomain domain;
}
/**
* Provides test context mocking facilities to unit tests testing domain classes
**/
public class TestFactory
{
public MockDatabase Database = new MockDatabase();
private TestFactory()
{
}
}
/**
* Class used during Unit testing of Domain classes, can be used (not exclusively) to speed up test execution and focus testing
**/
public class MockDatabase
{
private Boolean isInsert = false;
private Boolean isUpdate = false;
private Boolean isDelete = false;
private Boolean isUndelete = false;
private List<SObject> records = new List<SObject>();
private Map<Id, SObject> oldRecords = new Map<Id, SObject>();
private MockDatabase()
{
}
private void testTriggerHandler(Type domainClass)
{
// Mock Before
triggerHandler(domainClass, true, false, isInsert, isUpdate, isDelete, isUndelete, records, oldRecords);
// Mock After
triggerHandler(domainClass, false, true, isInsert, isUpdate, isDelete, isUndelete, records, oldRecords);
}
public void onInsert(List<SObject> records)
{
this.isInsert = true;
this.isUpdate = false;
this.isDelete = false;
this.isUndelete = false;
this.records = records;
}
public void onUpdate(List<SObject> records, Map<Id, SObject> oldRecords)
{
this.isInsert = false;
this.isUpdate = true;
this.isDelete = false;
this.records = records;
this.isUndelete = false;
this.oldRecords = oldRecords;
}
public void onDelete(Map<Id, SObject> records)
{
this.isInsert = false;
this.isUpdate = false;
this.isDelete = true;
this.isUndelete = false;
this.oldRecords = records;
}
public void onUndelete(List<SObject> records)
{
this.isInsert = false;
this.isUpdate = false;
this.isDelete = false;
this.isUndelete = true;
this.records = records;
}
public Boolean hasRecords()
{
return records!=null && records.size()>0 || oldRecords!=null && oldRecords.size()>0;
}
}
/**
* Test domain class (ideally this would be in the test class, however Type.newInstance does not see such classes)
**/
public with sharing class TestSObjectDomain extends fflib_SObjectDomain
{
private String someState;
public TestSObjectDomain(List<Opportunity> sObjectList)
{
// Domain classes are initialised with lists to enforce bulkification throughout
super(sObjectList);
}
public TestSObjectDomain(List<Opportunity> sObjectList, SObjectType sObjectType)
{
// Domain classes are initialised with lists to enforce bulkification throughout
super(sObjectList, sObjectType);
}
public override void onApplyDefaults()
{
// Not required in production code
super.onApplyDefaults();
// Apply defaults to Testfflib_SObjectDomain
for(Opportunity opportunity : (List<Opportunity>) Records)
{
opportunity.CloseDate = System.today().addDays(30);
}
}
public override void onValidate()
{
// Not required in production code
super.onValidate();
// Validate Testfflib_SObjectDomain
for(Opportunity opp : (List<Opportunity>) Records)
{
if(opp.Type!=null && opp.Type.startsWith('Existing') && opp.AccountId == null)
{
opp.AccountId.addError( error('You must provide an Account for Opportunities for existing Customers.', opp, Opportunity.AccountId) );
}
}
}
public override void onValidate(Map<Id,SObject> existingRecords)
{
// Not required in production code
super.onValidate(existingRecords);
// Validate changes to Testfflib_SObjectDomain
for(Opportunity opp : (List<Opportunity>) Records)
{
Opportunity existingOpp = (Opportunity) existingRecords.get(opp.Id);
if(opp.Type != existingOpp.Type)
{
opp.Type.addError( error('You cannot change the Opportunity type once it has been created.', opp, Opportunity.Type) );
}
}
}
public override void onBeforeDelete()
{
// Not required in production code
super.onBeforeDelete();
// Validate changes to Testfflib_SObjectDomain
for(Opportunity opp : (List<Opportunity>) Records)
{
opp.addError( error('You cannot delete this Opportunity.', opp) );
}
}
public override void onAfterUndelete()
{
// Not required in production code
super.onAfterUndelete();
}
public override void onBeforeInsert()
{
// Assert this variable is null in the after insert (since this domain class is stateless)
someState = 'This should not survice the trigger after phase';
}
public override void onAfterInsert()
{
// This is a stateless domain class, so should not retain anything betweet before and after
System.assertEquals(null, someState);
}
}
/**
* Typically an inner class to the domain class, supported here for test purposes
**/
public class TestSObjectDomainConstructor implements fflib_SObjectDomain.IConstructable
{
public fflib_SObjectDomain construct(List<SObject> sObjectList)
{
return new TestSObjectDomain(sObjectList);
}
}
/**
* Test domain class (ideally this would be in the test class, however Type.newInstance does not see such classes)
**/
public with sharing class TestSObjectStatefulDomain
extends fflib_SObjectDomain
{
public String someState;
public TestSObjectStatefulDomain(List<Opportunity> sObjectList)
{
super(sObjectList);
// Ensure this instance is re-used in the after trigger phase (subject to recursive scenarios)
Configuration.enableTriggerState();
}
public override void onBeforeInsert()
{
// This must always be null, as we do not reuse domain instances within recursive scenarios (different record sets)
System.assertEquals(null, someState);
// Process records
List<Opportunity> newOpps = new List<Opportunity>();
for(Opportunity opp : (List<Opportunity>) Records)
{
// Set some state sensitive to the incoming records
someState = 'Error on Record ' + opp.Name;
// Create a new Opportunity record to trigger recursive code path?
if(opp.Name.equals('Test Recursive 1'))
newOpps.add(new Opportunity ( Name = 'Test Recursive 2', Type = 'Existing Account' ));
}
// If testing recursiving emulate an insert
if(newOpps.size()>0)
{
// This will force recursion and thus validate via the above assert results in a new domain instance
fflib_SObjectDomain.Test.Database.onInsert(newOpps);
fflib_SObjectDomain.triggerHandler(fflib_SObjectDomain.TestSObjectStatefulDomainConstructor.class);
}
}
public override void onAfterInsert()
{
// Use the state set in the before insert (since this is a stateful domain class)
if(someState!=null)
for(Opportunity opp : (List<Opportunity>) Records)
opp.addError(error(someState, opp));
}
}