-
Notifications
You must be signed in to change notification settings - Fork 0
/
VersatileAcl.php
1001 lines (828 loc) · 43.4 KB
/
VersatileAcl.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
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
<?php
declare(strict_types=1);
namespace VersatileAcl;
use DateTime;
use ReflectionMethod;
use InvalidArgumentException;
use VersatileAcl\Interfaces\{
PermissionInterface, PermissionableEntitiesCollectionInterface,
PermissionableEntityInterface, PermissionsCollectionInterface
};
use RuntimeException;
use VersatileAcl\Exceptions\ParentCannotBeChildException;
use function array_key_exists;
use function array_shift;
use function func_get_args;
use function gettype;
use function is_object;
use function is_subclass_of;
use function method_exists;
use function str_repeat;
use function str_replace;
use function trim;
use function var_export;
/**
* A class for managing entities and permissions for access controlling resources in applications using this package
*
* @author rotimi
*
* @psalm-suppress RedundantCondition
*
*/
class VersatileAcl {
/**
*
* @var string name of the class that implements PermissionableEntityInterface that will be used to create new entities
*
*/
protected string $permissionableEntityInterfaceClassName;
/**
*
* @var string name of the class that implements PermissionInterface that will be used to create new permissions
*
*/
protected string $permissionInterfaceClassName;
/**
*
* @var string name of the class that implements PermissionableEntitiesCollectionInterface that will be used to create new entity collections
*
*/
protected string $permissionableEntitiesCollectionInterfaceClassName;
/**
*
* @var string name of the class that implements PermissionsCollectionInterface that will be used to create new permission collections
*
*/
protected string $permissionsCollectionInterfaceClassName;
/**
*
* @var PermissionableEntitiesCollectionInterface|null collection of entities for each instance of this class
*/
protected ?PermissionableEntitiesCollectionInterface $entitiesCollection;
/**
*
* @var string tracks activities performed in methods in this class
*/
protected string $auditTrail = '';
/**
*
* @var bool true for activities performed in methods in this class to be tracked by concatenating descriptive messages to $this->auditTrail, false for no tracking
*/
protected bool $auditActivities = false;
/**
* An integer to be used within $this->logActivity(..) to control the number of tabs to prepend to its return value
*
*/
protected int $numTabsForIndentingAudit = 0;
/**
* True means that $this->logActivity(string $description, string $shortDescription='')
* should use the first parameter for auditing, false means that it should use the second
* parameter if not empty (else it will use the first parameter).
*
* If $this->auditActivities === false, then the value of this property is irrelevant.
*
*/
protected bool $performVerboseAudit = true;
public function __construct(
string $permissionableEntityInterfaceClassName = GenericPermissionableEntity::class,
string $permissionInterfaceClassName = GenericPermission::class,
string $permissionableEntitiesCollectionInterfaceClassName = GenericPermissionableEntitiesCollection::class,
string $permissionsCollectionInterfaceClassName = GenericPermissionsCollection::class
) {
if(!is_subclass_of($permissionableEntityInterfaceClassName, PermissionableEntityInterface::class)) {
$this->throwInvalidArgExceptionDueToWrongClassName(
static::class, __FUNCTION__, $permissionableEntityInterfaceClassName, PermissionableEntityInterface::class, 'first'
);
}
if(!is_subclass_of($permissionInterfaceClassName, PermissionInterface::class)) {
$this->throwInvalidArgExceptionDueToWrongClassName(
static::class, __FUNCTION__, $permissionInterfaceClassName, PermissionInterface::class, 'second'
);
}
if(!is_subclass_of($permissionableEntitiesCollectionInterfaceClassName, PermissionableEntitiesCollectionInterface::class)) {
$this->throwInvalidArgExceptionDueToWrongClassName(
static::class, __FUNCTION__, $permissionableEntitiesCollectionInterfaceClassName, PermissionableEntitiesCollectionInterface::class, 'third'
);
}
if(!is_subclass_of($permissionsCollectionInterfaceClassName, PermissionsCollectionInterface::class)) {
$this->throwInvalidArgExceptionDueToWrongClassName(
static::class, __FUNCTION__, $permissionsCollectionInterfaceClassName, PermissionsCollectionInterface::class, 'fourth'
);
}
$this->permissionInterfaceClassName = $permissionInterfaceClassName;
$this->permissionableEntityInterfaceClassName = $permissionableEntityInterfaceClassName;
$this->permissionsCollectionInterfaceClassName = $permissionsCollectionInterfaceClassName;
$this->permissionableEntitiesCollectionInterfaceClassName = $permissionableEntitiesCollectionInterfaceClassName;
$this->entitiesCollection = $this->createEntityCollection();
}
/**
* Adds an entity to an instance of this class if it doesn't already exist.
*
* @param string $entityId ID of the entity to be added. It is treated in a case-insensitive manner, meaning that 'ALice' and 'alicE' both refer to the same entity
*/
public function addEntity(string $entityId): self {
$this->auditActivities
&& ++$this->numTabsForIndentingAudit // increment on first call to logActivity within a method
&& $this->logActivity(
"Entered " . __METHOD__ . "('{$entityId}') trying to create and add a new entity whose ID will be `{$entityId}`",
"Entered " . __METHOD__ . "('{$entityId}')"
);
$entity = $this->createEntity($entityId);
$this->auditActivities && $this->logActivity("Entity created", "Entity created");
if(!($this->entitiesCollection instanceof PermissionableEntitiesCollectionInterface)) {
$this->entitiesCollection = $this->createEntityCollection();
$this->auditActivities
&& $this->logActivity(
"Initialized " . static::class
. '::entitiesCollection to a new empty instance of '
. $this->entitiesCollection::class,
"Initialized " . static::class . '::entitiesCollection'
);
}
if(!$this->entitiesCollection->has($entity)) {
$this->entitiesCollection->add($entity);
$this->auditActivities
&& $this->logActivity(
"Successfully added the following entity:" .PHP_EOL . trim(''.$entity),
"Successfully added the entity whose ID is `{$entityId}`"
);
} else {
$this->auditActivities
&& $this->logActivity(
"An entity with the specified entity ID `{$entityId}` already exists in the entities collection, no need to add",
"An entity with the specified entity ID `{$entityId}` already exists"
);
}
$this->auditActivities
&& $this->logActivity("Exiting " . __METHOD__ . "('{$entityId}')")
&& $this->numTabsForIndentingAudit--; // decrement on last call to logActivity within a method
return $this;
}
/**
* Removes an entity from an instance of this class if it exists.
*
* @param string $entityId ID of the entity to be removed. It is treated in a case-insensitive manner, meaning that 'ALice' and 'alicE' both refer to the same entity
*
* @return PermissionableEntityInterface|null the removed entity object or NULL if no such entity exists
*
*/
public function removeEntity(string $entityId): ?PermissionableEntityInterface {
$this->auditActivities
&& ++$this->numTabsForIndentingAudit // increment on first call to logActivity within a method
&& $this->logActivity(
"Entered " . __METHOD__ . "('{$entityId}') trying to remove the entity whose ID is `{$entityId}`",
"Entered " . __METHOD__ . "('{$entityId}')"
);
$entity = $this->getEntity($entityId);
if($entity !== null) {
($this->entitiesCollection !== null) && $this->entitiesCollection->remove($entity);
$this->auditActivities
&& $this->logActivity("Successfully removed the entity whose ID is `{$entityId}`.");
} else {
$this->auditActivities
&& $this->logActivity("The entity whose ID is `{$entityId}` does not exist, no need for removal.");
}
$this->auditActivities
&& $this->logActivity(
"Exiting " . __METHOD__ . "('{$entityId}')" . $this->formatReturnValueForAudit($entity),
"Exiting " . __METHOD__ . "('{$entityId}')"
)
&& $this->numTabsForIndentingAudit--; // decrement on last call to logActivity within a method
return $entity;
}
/**
* Add an entity with an ID value of $parentEntityId as a parent entity to
* another entity with an ID value of $entityId in an instance of this class.
* If an entity with an ID value of $entityId does not exist in the instance
* of this class upon which this method is called, the entity will be created
* and added first before the parent entity is added to it.
*
* @param string $entityId ID of the entity to which a parent entity is to be added. It is treated in a case-insensitive manner, meaning that 'ALice' and 'alicE' both refer to the same entity
* @param string $parentEntityId ID of the parent entity to be added. It is treated in a case-insensitive manner, meaning that 'ALice' and 'alicE' both refer to the same entity
*
*
* @throws RuntimeException
* @throws ParentCannotBeChildException
*/
public function addParentEntity(string $entityId, string $parentEntityId): self {
$this->auditActivities
&& ++$this->numTabsForIndentingAudit // increment on first call to logActivity within a method
&& $this->logActivity(
"Entered " . __METHOD__ . "('{$entityId}', '{$parentEntityId}')"
. " trying to add a new parent entity whose ID will be `{$parentEntityId}` to "
. " the entity whose ID is `{$entityId}`",
"Entered " . __METHOD__ . "('{$entityId}', '{$parentEntityId}')"
);
$existingEntity = $this->getEntity($entityId);
if($existingEntity === null) {
$this->auditActivities
&& $this->logActivity("The entity whose ID is `{$entityId}` is not yet created, trying to create it now");
$this->addEntity($entityId);
$existingEntity = $this->getEntity($entityId);
}
if($existingEntity instanceof PermissionableEntityInterface) {
$existingEntity->addParent($this->createEntity($parentEntityId));
$this->auditActivities
&& $this->logActivity("Parent entity whose ID is `{$parentEntityId}` has been added to the entity whose ID is `{$entityId}`");
} else {
// We should never really get here in most cases.
// Something weird happened, we could not create or retrieve
// the entity to which a parent is to be added
$class = static::class;
$function = __FUNCTION__;
$msg = "Error [{$class}::{$function}(...)]:"
. " Could not create or retrieve the entity with an ID of `{$entityId}`"
. " to which the parent entity with an ID of `{$parentEntityId}` is to be added.";
throw new RuntimeException($msg);
}
$this->auditActivities
&& $this->logActivity(
"Exiting " . __METHOD__ . "('{$entityId}', '{$parentEntityId}')"
)
&& $this->numTabsForIndentingAudit--; // decrement on last call to logActivity within a method
return $this;
}
/**
* Remove and return an entity with an ID value of $parentEntityId that is a parent entity
* to another entity with an ID value of $entityId, if the instance of this class
* upon which this method is being called contains an entity with an ID value of $entityId,
* else return NULL
*
* @param string $entityId ID of entity from which a parent entity with ID value of $parentEntityId is to be removed
* @param string $parentEntityId ID of the parent entity to be removed from the specified entity with the ID value of $entityId
*
*/
public function removeParentEntity(string $entityId, string $parentEntityId): ?PermissionableEntityInterface {
$this->auditActivities
&& ++$this->numTabsForIndentingAudit // increment on first call to logActivity within a method
&& $this->logActivity(
"Entered " . __METHOD__ . "('{$entityId}', '{$parentEntityId}')"
. " trying to remove the parent entity whose ID is `{$parentEntityId}` from "
. " the entity whose ID is `{$entityId}`",
"Entered " . __METHOD__ . "('{$entityId}', '{$parentEntityId}')"
);
$removedParentEntity = null;
$existingEntity = $this->getEntity($entityId);
if($existingEntity instanceof PermissionableEntityInterface) {
$keyForParentEntity = $existingEntity->getDirectParents()->getKey($this->createEntity($parentEntityId));
$removedParentEntity = $existingEntity->getDirectParents()->get(($keyForParentEntity === null)? '' : ''.$keyForParentEntity); // get the parent entity object
$keyForParentEntity !== null
&& $existingEntity->getDirectParents()->removeByKey($keyForParentEntity); // remove the parent
$this->auditActivities
&& $this->logActivity("Parent entity has been successfully removed.");
} else {
$this->auditActivities
&& $this->logActivity("The entity whose ID is `{$entityId}` doesn't exist, no need trying to remove a parent entity.");
}
$this->auditActivities
&& $this->logActivity(
"Exiting " . __METHOD__ . "('{$entityId}', '{$parentEntityId}')"
. $this->formatReturnValueForAudit($removedParentEntity),
"Exiting " . __METHOD__ . "('{$entityId}', '{$parentEntityId}')"
)
&& $this->numTabsForIndentingAudit--; // decrement on last call to logActivity within a method
return $removedParentEntity;
}
/**
* Gets and returns an entity with specified Id from an instance of this class
* or returns NULL if an entity with specified Id doesn't already exist in the
* instance of this class this method is being invoked on.
*
*/
public function getEntity(string $entityId): ?PermissionableEntityInterface {
$this->auditActivities
&& ++$this->numTabsForIndentingAudit // increment on first call to logActivity within a method
&& $this->logActivity(
"Entered " . __METHOD__ . "('{$entityId}') trying to retrieve the entity whose ID is `{$entityId}`",
"Entered " . __METHOD__ . "('{$entityId}')"
);
$entityToReturn = null;
if($this->entitiesCollection instanceof PermissionableEntitiesCollectionInterface) {
$entityToReturn = $this->entitiesCollection->find($entityId);
$this->auditActivities
&& $this->logActivity(
"Retrieved the following item: "
. (
($entityToReturn instanceof PermissionableEntityInterface)
? trim(((string)$entityToReturn))
: trim(var_export($entityToReturn, true))
),
(
($entityToReturn instanceof PermissionableEntityInterface)
? "Successfully retrieved the desired entity." // avoid dumping the string representation of the entity for non-verbose audit
: "Retrieved the following item: " . trim(var_export($entityToReturn, true))
)
);
}
$this->auditActivities
&& $this->logActivity(
"Exiting " . __METHOD__ . "('{$entityId}')"
. $this->formatReturnValueForAudit($entityToReturn),
"Exiting " . __METHOD__ . "('{$entityId}')"
)
&& $this->numTabsForIndentingAudit--; // decrement on last call to logActivity within a method
return $entityToReturn;
}
/**
* Returns a collection of all entities added to an instance of this class via $this->addEntity(string $entityId) or null if the collection has not yet been initialized
*
* @return PermissionableEntitiesCollectionInterface|null a collection of all entities added to an instance of this class via $this->addEntity(string $entityId) or null if the collection has not yet been initialized
*/
public function getAllEntities() : ?PermissionableEntitiesCollectionInterface {
return $this->entitiesCollection;
}
/**
* Add a permission to an entity with the ID value of $entityId.
* This entity will be created and added to the instance of this class upon
* which this method is being invoked if the entity does not exist.
*
* @param string $entityId the ID of the entity to which the permission is to be added
* @param callable|null $additionalAssertions
* @noinspection PhpUnhandledExceptionInspection
* @see PermissionInterface::__construct($action, $resource, $allowActionOnResource, $additionalAssertions, ...$argsForCallback)
* for definitions of all but the first parameter
*
* @noinspection PhpDocMissingThrowsInspection
*/
public function addPermission(
string $entityId,
string $action,
string $resource,
bool $allowActionOnResource = true,
callable $additionalAssertions = null,
mixed ...$argsForCallback
): self {
$this->auditActivities
&& ++$this->numTabsForIndentingAudit // increment on first call to logActivity within a method
&& $this->logActivity(
"Entered " . __METHOD__ . "(...) to try to add a permission to "
. " the entity whose ID is `{$entityId}`. Method Parameters: "
. PHP_EOL
.
trim(
var_export(
$this->getMethodParameterNamesAndVals(
__FUNCTION__,
[
$entityId, $action, $resource,
$allowActionOnResource,
$additionalAssertions,
$argsForCallback
]
),
true
)
),
"Entered " . __METHOD__ . "(...)"
);
$existingEntity = $this->getEntity($entityId);
if($existingEntity === null) {
$this->auditActivities
&& $this->logActivity("The entity whose ID is `{$entityId}` has not yet been created, trying to create it now");
$this->addEntity($entityId);
$existingEntity = $this->getEntity($entityId);
}
if($existingEntity instanceof PermissionableEntityInterface) {
$existingEntity->addPermission(
$this->createPermission($action, $resource, $allowActionOnResource, $additionalAssertions, ...$argsForCallback)
);
$this->auditActivities
&& $this->logActivity(
"Permission with the parameters below has been added to the entity whose ID is `{$entityId}`:"
. PHP_EOL . "action: `{$action}`"
. PHP_EOL . "resource: `{$resource}`"
. PHP_EOL . "allowActionOnResource: " . var_export($allowActionOnResource, true)
. PHP_EOL . "additionalAssertions: " . var_export($additionalAssertions, true)
. PHP_EOL . "argsForCallback: " . var_export($argsForCallback, true)
);
} else {
$funcArgs = func_get_args();
array_shift($funcArgs);
// We should never really get here in most cases. Something weird happened,
// we could not create or retrieve the entity to which a parent is to be added
$class = static::class;
$function = __FUNCTION__;
$msg = "Error [{$class}::{$function}(...)]:"
. " Could not create or retrieve the entity with an ID of `{$entityId}`"
. " to which the following permission is to be added:"
. PHP_EOL
. PHP_EOL . "action: `{$action}`"
. PHP_EOL . "resource: `{$resource}`"
. PHP_EOL . "allowActionOnResource: " . var_export($allowActionOnResource, true)
. PHP_EOL . "additionalAssertions: " . var_export($additionalAssertions, true)
. PHP_EOL . "argsForCallback: " . var_export($argsForCallback, true);
throw new RuntimeException($msg);
}
$this->auditActivities
&& $this->logActivity(
"Exiting " . __METHOD__ . "(...)"
)
&& $this->numTabsForIndentingAudit--; // decrement on last call to logActivity within a method
return $this;
}
/**
* Remove a permission from the entity with an ID value of $entityId and return the removed permission
* or return null if either the entity and / or permission do not exist.
*
* @param callable|null $additionalAssertions
*
* @noinspection PhpUnhandledExceptionInspection
* @see PermissionInterface::__construct($action, $resource, $allowActionOnResource, $additionalAssertions, $argsForCallback)
* for definitions of all but the first parameter
*
* @noinspection PhpDocMissingThrowsInspection
*/
public function removePermission(
string $entityId,
string $action,
string $resource,
bool $allowActionOnResource = true,
callable $additionalAssertions = null,
mixed ...$argsForCallback
): ?PermissionInterface {
$this->auditActivities
&& ++$this->numTabsForIndentingAudit // increment on first call to logActivity within a method
&& $this->logActivity(
"Entered " . __METHOD__ . "(...) to try to remove a permission from "
. " the entity whose ID is `{$entityId}`. Method Parameters: "
. PHP_EOL
.
trim(
var_export(
$this->getMethodParameterNamesAndVals(
__FUNCTION__,
[
$entityId, $action, $resource,
$allowActionOnResource,
$additionalAssertions,
$argsForCallback
]
),
true
)
),
"Entered " . __METHOD__ . "(...)"
);
$removedPermission = null;
$existingEntity = $this->getEntity($entityId);
if($existingEntity instanceof PermissionableEntityInterface) {
$keyForPermission =
$existingEntity->getDirectPermissions()
->getKey(
$this->createPermission(
$action, $resource,
$allowActionOnResource,
$additionalAssertions,
...$argsForCallback
)
);
$removedPermission = $existingEntity->getDirectPermissions()->get(($keyForPermission === null) ? '' : ''.$keyForPermission); // get the permission object
$keyForPermission !== null
&& $existingEntity->getDirectPermissions()->removeByKey($keyForPermission); // remove the permission
$this->auditActivities
&& $this->logActivity(
"Permission with the parameters below has been removed from the entity whose ID is `{$entityId}`:"
. PHP_EOL . "action: `{$action}`"
. PHP_EOL . "resource: `{$resource}`"
. PHP_EOL . "allowActionOnResource: " . var_export($allowActionOnResource, true)
. PHP_EOL . "additionalAssertions: " . var_export($additionalAssertions, true)
. PHP_EOL . "argsForCallback: " . var_export($argsForCallback, true)
);
} else {
$this->auditActivities
&& $this->logActivity("The entity whose ID is `{$entityId}` doesn't exist, no need trying to remove the specified permission.");
}
$this->auditActivities
&& $this->logActivity(
"Exiting " . __METHOD__ . "(....)"
. $this->formatReturnValueForAudit($removedPermission),
"Exiting " . __METHOD__ . "(....)"
)
&& $this->numTabsForIndentingAudit--; // decrement on last call to logActivity within a method
return $removedPermission;
}
/**
* Check if the specified action $action can be performed on the specified
* resource $resource based on the existing permissions associated with
* either the specified entity with an ID of $entityId or all entities
* associated with the instance of this class this method is being invoked
* on if $entityId === ''
*
* @param string $entityId ID of the entity whose permissions will be searched.
* Pass an empty string to search the permissions for
* all entities added to the instance of this class
* this method is being invoked on.
* @param string $action See the see section above
* @param string $resource See the see section above
* @param callable|null $additionalAssertions See the see section above
* @param mixed $argsForCallback See the see section above
*
* @see PermissionInterface::isAllowed($action, $resource, $additionalAssertions, ...$argsForCallback)
* for definitions of all but the first parameter
*
* @noinspection PhpUnhandledExceptionInspection
* @noinspection PhpDocMissingThrowsInspection
*/
public function isAllowed(string $entityId, string $action, string $resource, callable $additionalAssertions = null, mixed ...$argsForCallback): bool {
$this->auditActivities
&& ++$this->numTabsForIndentingAudit // increment on first call to logActivity within a method
&& $this->logActivity(
"Entered " . __METHOD__ . "(...) to check if the entity `{$entityId}`"
. " is allowed to perform the specified action `{$action}` on the"
. " specified resource `{$resource}`. "
. PHP_EOL . 'Supplied Method Parameters:'
. PHP_EOL
.
trim(
var_export(
$this->getMethodParameterNamesAndVals(
__FUNCTION__,
[
$entityId,
$action, $resource,
$additionalAssertions,
$argsForCallback
]
),
true
)
),
"Entered " . __METHOD__ . "(...)"
);
$isAllowed = false;
if( $entityId === '' ) {
$this->auditActivities
&& $this->logActivity(
"An empty string was supplied as the entity ID, so we"
. " are searching through permissions for all existing"
. " entities until we get the first match"
);
if($this->entitiesCollection instanceof PermissionableEntitiesCollectionInterface) {
// loop through all entities
/** @var PermissionableEntityInterface $currentEntity */
foreach ($this->entitiesCollection as $currentEntity) {
$this->auditActivities
&& $this->logActivity(
"Currently searching through the permissions for the entity whose ID is `{$currentEntity->getId()}`"
);
// Get all permissions including inherited ones and check if
// permission test evaluates to true for any of the permissions.
if(
$currentEntity->getAllPermissions(true, $this->createPermissionCollection())
->isAllowed($action, $resource, $additionalAssertions, ...$argsForCallback)
) {
$this->auditActivities
&& $this->logActivity(
"Found a permission belonging to the entity"
. " whose ID is `{$currentEntity->getId()}`"
. " that allows the specified action `{$action}`"
. " to be performed on the specified resource `{$resource}`."
);
$isAllowed = true;
break;
}
}
} // if($this->entitiesCollection instanceof PermissionableEntitiesCollectionInterface)
if(!$isAllowed) {
$this->auditActivities
&& $this->logActivity(
"Did not find any permission belonging to any entity"
. " that allows the specified action `{$action}`"
. " to be performed on the specified resource `{$resource}`."
. PHP_EOL . PHP_EOL . "Either no entity"
. " has such a permission or an entity has a permission that explicitly"
. " denies the specified action `{$action}` from being performed"
. " on the specified resource `{$resource}`"
);
}
} else {
$this->auditActivities
&& $this->logActivity(
"Trying to retrieve the entity object associated with specified entity ID `{$entityId}`"
);
// get specified entity if it exists and check through its permissions
// including inherited ones, to if the permission test evaluates to
// true for any of the permissions
$specifiedEntity = $this->getEntity($entityId);
if($specifiedEntity instanceof PermissionableEntityInterface) {
$this->auditActivities
&& $this->logActivity(
"Successfully retrieved the entity object associated with specified entity ID `{$entityId}`."
);
$this->auditActivities
&& $this->logActivity(
"Searching through the permissions for the entity whose ID is `{$entityId}`"
);
$isAllowed = $specifiedEntity->getAllPermissions(true, $this->createPermissionCollection())
->isAllowed($action, $resource, $additionalAssertions, ...$argsForCallback);
if($isAllowed) {
$this->auditActivities
&& $this->logActivity(
"Found a permission belonging to the entity"
. " whose ID is `{$entityId}`"
. " that allows the specified action `{$action}`"
. " to be performed on the specified resource `{$resource}`."
);
} else {
$this->auditActivities
&& $this->logActivity(
"Did not find any permission belonging to the entity"
. " whose ID is `{$entityId}`"
. " that allows the specified action `{$action}`"
. " to be performed on the specified resource `{$resource}`."
. PHP_EOL . PHP_EOL . "Either the entity whose ID is `{$entityId}`"
. " has no such permission or has a permission that explicitly"
. " denies the specified action `{$action}` from being performed"
. " on the specified resource `{$resource}`"
);
}
} else {
$this->auditActivities
&& $this->logActivity(
"Could not retrieve the entity object associated with specified entity ID `{$entityId}`."
);
}
}
$this->auditActivities
&& $this->logActivity(
"Exiting " . __METHOD__ . "(....)"
.$this->formatReturnValueForAudit($isAllowed),
"Exiting " . __METHOD__ . "(....)"
)
&& $this->numTabsForIndentingAudit--; // decrement on last call to logActivity within a method
return $isAllowed;
}
/**
* @psalm-suppress MoreSpecificReturnType
*/
public function createEntityCollection(): PermissionableEntitiesCollectionInterface {
$collectionClassName = $this->permissionableEntitiesCollectionInterfaceClassName;
/** @psalm-suppress LessSpecificReturnStatement */
return new $collectionClassName();
}
/**
* @psalm-suppress MoreSpecificReturnType
*/
public function createPermissionCollection(): PermissionsCollectionInterface {
$collectionClassName = $this->permissionsCollectionInterfaceClassName;
/** @psalm-suppress LessSpecificReturnStatement */
return new $collectionClassName();
}
/**
* @param string $entityId the ID of the entity to be created
*
* @return PermissionableEntityInterface the created entity object
*
* @psalm-suppress MoreSpecificReturnType
*/
public function createEntity(string $entityId): PermissionableEntityInterface {
$entityClassName = $this->permissionableEntityInterfaceClassName;
/** @psalm-suppress LessSpecificReturnStatement */
return new $entityClassName($entityId, $this->createPermissionCollection(), $this->createEntityCollection());
}
/**
* @see PermissionInterface::__construct($action, $resource, $allowActionOnResource, $additionalAssertions, ...$argsForCallback)
* for definitions of all the parameters of this method
*
* @param callable|null $additionalAssertions
*
* @psalm-suppress MoreSpecificReturnType
*/
public function createPermission(
string $action, string $resource, bool $allowActionOnResource = true, callable $additionalAssertions = null, mixed ...$argsForCallback
): PermissionInterface {
$permissionClassName = $this->permissionInterfaceClassName;
/** @psalm-suppress LessSpecificReturnStatement */
return new $permissionClassName($action, $resource, $allowActionOnResource, $additionalAssertions, ...$argsForCallback);
}
/**
* Empties the contents of the Audit Trail containing the trace of all logged internal activities
*
*/
public function clearAuditTrail(): self {
$this->auditTrail = '';
return $this;
}
/**
* Returns a string containing a trace of all logged internal activities
*
*/
public function getAuditTrail(): string {
return $this->auditTrail;
}
/**
* Enables or disables the logging of internal activities performed in the public methods of this class
*
* @param bool $canAudit true to start logging internal activities, false to stop logging internal activities
*/
public function enableAuditTrail(bool $canAudit=true): self {
$this->auditActivities = $canAudit;
return $this;
}
/**
* Sets a boolean value for $this->performVerboseAudit.
*
* True means that $this->logActivity(string $description, string $shortDescription='')
* should use the first parameter for auditing, false means that it should use the second
* parameter if not empty (else it will use the first parameter).
*
*
*/
public function enableVerboseAudit(bool $performVerboseAudit=true): self {
$this->performVerboseAudit = $performVerboseAudit;
return $this;
}
////////////////////////////////////////////////////////////////////////////
//////////////////// non-public methods ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
protected function logActivity(string $description, string $shortDescription=''): self {
if($this->auditActivities) {
$useShortDescr = $shortDescription !== '' && (!$this->performVerboseAudit);
$this->auditTrail .=
(($this->numTabsForIndentingAudit <= 1) ? '' : str_repeat("\t", $this->numTabsForIndentingAudit))
. '[' . (new DateTime())->format('Y-m-d H:i:s') . ']: '
.
(
($this->numTabsForIndentingAudit <= 1)
?
(
$useShortDescr
? $shortDescription
: $description
)
:
(
$useShortDescr
? str_replace(PHP_EOL, PHP_EOL . str_repeat("\t", $this->numTabsForIndentingAudit), $shortDescription)
: str_replace(PHP_EOL, PHP_EOL . str_repeat("\t", $this->numTabsForIndentingAudit), $description)
)
)
. PHP_EOL .PHP_EOL .PHP_EOL;
}
return $this;
}
/**
* @return never
*/
protected function throwInvalidArgExceptionDueToWrongClassName(
string $class, string $function, string $wrongClassName,
string $expectedInterfaceName, string $positionthParameter
): void {
$msg = "Error [{$class}::{$function}(...)]:"
. " You must specify the fully qualified name of a class that implements `{$expectedInterfaceName}` "
. " as the {$positionthParameter} parameter to {$class}::{$function}(...)."
. PHP_EOL . " You supplied a wrong value of: `{$wrongClassName}` ";
throw new InvalidArgumentException($msg);
}
/**
* Returns an associative array whose keys are the names of the parameters for the specified method ($methodName) and the values are the values in $paramVals
*
* @param string $methodName name of a method in this class
* @param array<string|int, mixed> $paramVals an array of values supplied as arguments to the method named by $methodName
*
* @return array an associative array whose keys are the names of the parameters for the specified method ($methodName) and the values are the values in $paramVals
* @noinspection PhpRedundantVariableDocTypeInspection
* @throws \ReflectionException if $methodName is not the name of an actual method in this class
* @noinspection PhpFullyQualifiedNameUsageInspection
*/
protected function getMethodParameterNamesAndVals(string $methodName, array $paramVals): array {
$paramPosToNameMap = [];
if(method_exists($this, $methodName)) {
$refMethodObj = new ReflectionMethod($this, $methodName);
$parameters = $refMethodObj->getParameters();
foreach ($parameters as $parameter) {
$pos = $parameter->getPosition();
if(array_key_exists($pos, $paramVals)) {
/** @psalm-suppress MixedAssignment */
$paramPosToNameMap[$parameter->getName()] = $paramVals[$pos];
}
}
}
return $paramPosToNameMap;
}
/**
* Helper method to describe the value in $returnVal
*
* @return string description of the value in $returnVal
*/
protected function formatReturnValueForAudit(mixed $returnVal): string {
$returnType = gettype($returnVal);
$formattedSentence =
" with a return type of `$returnType` and actual return value of "
. trim(var_export($returnVal, true));
if(is_object($returnVal)) {
$formattedSentence =
" with a return type of `object` that is an instance of"
. " `" . $returnVal::class . "` with the following"
. " string representation: "
. PHP_EOL
.
(
(method_exists($returnVal, '__toString'))
? trim(((string)$returnVal))
: trim(var_export($returnVal, true))
);
}
return $formattedSentence;
}