programmieren:cakephp:traits:type_aligned_assertions_trait
Type Aligned Assetions Trait
I liked this so I wanted to make it an entry.
We made a trait for testing that aligns any iterable, most notably Entities, Collections and arrays, and its contents to a more comparable array, with dates casted to strings and BackedEnums to their values.
It looks kinda like this:
/** * Aligns a given, possibly multidimensional, iterable and its contents to a more comparable array * * @param iterable $items Any iterable value such as arrays, Collections and Entities * @return array<mixed> The given iterable aligned to a more comparable array */ public function typeAlignIterable(iterable $items): array { if ($items instanceof CollectionInterface || $items instanceof EntityInterface) { $items = $items->toArray(); } return array_map(static function ($item) { if ($item instanceof DateTime || $item instanceof DateTimeImmutable) { return $item->format('Y-m-d H:i:s.u T'); } if ($item instanceof Date) { return $item->format('Y-m-d T'); } if ($item instanceof BackedEnum) { return $item->value; } if (is_iterable($item)) { return self::typeAlignIterable($item); } return $item; }, $items); }
Now we can use this base function to write custom assertions that takes any iterable value, aligns it to a comparable array and then also directly compares it to a given array (that doesn't need to contain weird objects to be correct)
The assertion looks like this:
/** * Asserts if given value, which has its self and its contents aligned to be comparable, equals given expected value * * @param array $expected The expected result in an array * @param iterable|EntityInterface $actual The actual iterable data * @param string $message Optional message * @return void */ public function assertSameTypeAlignedArray( array $expected, iterable|EntityInterface $actual, string $message = '' ): void { $alignedActual = $this->typeAlignedArray($actual); self::assertEquals($expected, $alignedActual, $message); }
programmieren/cakephp/traits/type_aligned_assertions_trait.txt · Last modified: by admin
