66
77trait AnonymizesAttributes
88{
9+ /**
10+ * Whether anonymization is enabled for the current instance.
11+ */
12+ protected bool $ anonymizeEnabled = true ;
13+
914 /**
1015 * The anonymized attributes for the current instance and seed.
1116 */
@@ -16,6 +21,27 @@ trait AnonymizesAttributes
1621 */
1722 protected string $ anonymizedAttributeCacheSeed ;
1823
24+ /**
25+ * Execute a callback without anonymization.
26+ *
27+ * @template TReturn
28+ *
29+ * @param callable($this): TReturn $callback
30+ * @return TReturn
31+ */
32+ public function withoutAnonymization (callable $ callback ): mixed
33+ {
34+ $ previous = $ this ->anonymizeEnabled ;
35+
36+ $ this ->anonymizeEnabled = false ;
37+
38+ try {
39+ return $ callback ($ this );
40+ } finally {
41+ $ this ->anonymizeEnabled = $ previous ;
42+ }
43+ }
44+
1945 /**
2046 * Get the seed for the anonymizable instance.
2147 */
@@ -48,17 +74,19 @@ protected function addAnonymizedAttributesToArray(array $attributes): array
4874 */
4975 protected function getCachedAnonymizedAttributes (): array
5076 {
51- $ seed = $ this ->getAnonymizableSeed ();
77+ return $ this ->withoutAnonymization (function (): array {
78+ $ seed = $ this ->getAnonymizableSeed ();
5279
53- if (! isset ($ this ->anonymizedAttributeCache ) || $ this ->anonymizedAttributeCacheSeed !== $ seed ) {
54- $ this ->anonymizedAttributeCache = $ this ->getAnonymizedAttributes (
55- static ::getAnonymizeManager ()->faker ($ seed )
56- );
80+ if (! isset ($ this ->anonymizedAttributeCache ) || $ this ->anonymizedAttributeCacheSeed !== $ seed ) {
81+ $ this ->anonymizedAttributeCache = $ this ->getAnonymizedAttributes (
82+ static ::getAnonymizeManager ()->faker ($ seed )
83+ );
5784
58- $ this ->anonymizedAttributeCacheSeed = $ seed ;
59- }
85+ $ this ->anonymizedAttributeCacheSeed = $ seed ;
86+ }
6087
61- return $ this ->anonymizedAttributeCache ;
88+ return $ this ->anonymizedAttributeCache ;
89+ });
6290 }
6391
6492 /**
0 commit comments