Skip to content

Commit 4bfb539

Browse files
author
Aymo Timmerman
committed
Allow anonymizer to retrieve attributes from factories
This allows 2 methods in the factories to be defined. Both return an array. The first method, anonymizableAttributes(), returns an array of keys that the factory definition already has. The anonymizer will use the factory’s definition when anonymizing. This will reduce the necessary amount of code, as it reuses existing code. The second method, anonymizableDefinition, is the same as the method that can be defined on the model. It returns a keyed array with predefined values. This can be used to anonymize using custom data instead of relying on the factories definition. Both method can be used at once
1 parent fdbfd13 commit 4bfb539

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

src/Anonymizer.php

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,39 @@ public function changeData(Model $model): bool
7373
}
7474

7575
$anonymizableAttributes = $model->anonymizableAttributes($this->faker);
76+
$anonymizableAttributesBasedOnFactoryDefinition = [];
77+
$anonymizableAttributesBasedOnCustomDefinition = [];
7678

77-
if (method_exists($model::factory(), 'anonymizableAttributes')) {
78-
$anonymizableAttributes = $model::factory()->anonymizableAttributes($this->faker);
79+
/** @var \Illuminate\Database\Eloquent\Factories\Factory $factory */
80+
$factory = $model::factory();
81+
82+
// Extract attributes, including values, from the factory's definition, if available
83+
if (method_exists($factory, 'anonymizableAttributes')) {
84+
$anonymizableAttributesKeys = $factory->anonymizableAttributes();
85+
$factoryDefinition = $factory->definition();
86+
87+
$keysToLeaveAlone = array_diff_key($factoryDefinition, array_flip($anonymizableAttributesKeys));
88+
89+
$anonymizableAttributesBasedOnFactoryDefinition = array_diff_key(
90+
$factoryDefinition,
91+
array_flip(array_keys($keysToLeaveAlone))
92+
);
93+
}
94+
95+
// Extract attributes and values from the custom definition, if available
96+
if (method_exists($factory, 'anonymizableDefinition')) {
97+
$anonymizableAttributesBasedOnCustomDefinition = $factory->anonymizableDefinition($this->faker);
98+
}
99+
100+
// Merge the list of custom definitions and the factory based definitions to use as the new anonymizable attributes
101+
if (
102+
! empty($anonymizableAttributesBasedOnFactoryDefinition)
103+
|| ! (empty($anonymizableAttributesBasedOnCustomDefinition))
104+
) {
105+
$anonymizableAttributes = array_merge(
106+
$anonymizableAttributesBasedOnFactoryDefinition,
107+
$anonymizableAttributesBasedOnCustomDefinition
108+
);
79109
}
80110

81111
return $model

0 commit comments

Comments
 (0)