|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Ensi\LaravelTestFactories; |
| 4 | + |
| 5 | +use Illuminate\Database\Eloquent\Factories\Sequence; |
| 6 | + |
| 7 | +trait WithSetPkTrait |
| 8 | +{ |
| 9 | + protected bool $hasValue = false; |
| 10 | + protected array $pkValues = []; |
| 11 | + |
| 12 | + protected function stateSetPk(mixed $state, array $keys, bool $isSequence = false): static |
| 13 | + { |
| 14 | + if ($isSequence) { |
| 15 | + $newSequence = new Sequence(...$state); |
| 16 | + $variables = []; |
| 17 | + |
| 18 | + foreach ($state as $sequenceState) { |
| 19 | + $variables[] = $this->getVariables($sequenceState, $keys); |
| 20 | + } |
| 21 | + |
| 22 | + if ($this->hasValue) { |
| 23 | + return $this->getSequenceState($variables, $newSequence)->state($newSequence); |
| 24 | + } |
| 25 | + |
| 26 | + return parent::state($newSequence); |
| 27 | + } |
| 28 | + |
| 29 | + if (is_array($state)) { |
| 30 | + $variables = $this->getVariables($state, $keys); |
| 31 | + |
| 32 | + if ($this->hasValue) { |
| 33 | + return $this->state(function () use ($variables) { |
| 34 | + return $this->generatePk(...$variables); |
| 35 | + }) |
| 36 | + ->state($state); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + return parent::state($state); |
| 41 | + } |
| 42 | + |
| 43 | + protected function getVariables(mixed &$state, array $keys): array |
| 44 | + { |
| 45 | + $variables = []; |
| 46 | + foreach ($keys as $key) { |
| 47 | + if (array_key_exists($key, $state)) { |
| 48 | + $variables[] = $state[$key]; |
| 49 | + unset($state[$key]); |
| 50 | + $this->hasValue = true; |
| 51 | + } else { |
| 52 | + $variables[] = null; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return $variables; |
| 57 | + } |
| 58 | + |
| 59 | + protected function getSequenceState(array $variables, Sequence $sequence): self |
| 60 | + { |
| 61 | + return $this->state(function () use ($variables, $sequence) { |
| 62 | + $values = $variables[$sequence->index % $sequence->count] ?? [null, null]; |
| 63 | + |
| 64 | + $isNewSequence = true; |
| 65 | + foreach ($this->pkValues as $sequenceValues) { |
| 66 | + // Skip all sequences that are applied after current one |
| 67 | + if ($sequenceValues == $variables) { |
| 68 | + $isNewSequence = false; |
| 69 | + |
| 70 | + break; |
| 71 | + } |
| 72 | + |
| 73 | + // Apply previously created sequence to current one |
| 74 | + foreach ($sequenceValues[$sequence->index % count($sequenceValues)] as $pkKey => $pkValue) { |
| 75 | + if ($values[$pkKey]) { |
| 76 | + continue; |
| 77 | + } |
| 78 | + |
| 79 | + $values[$pkKey] = $pkValue; |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + if ($isNewSequence) { |
| 84 | + $this->pkValues[] = $variables; |
| 85 | + } |
| 86 | + |
| 87 | + return $this->generatePk(...$values); |
| 88 | + }); |
| 89 | + } |
| 90 | +} |
0 commit comments