diff --git a/src/Repository/CustomTypeConverter.php b/src/Repository/CustomTypeConverter.php index 60a0c54..8fa5b4f 100644 --- a/src/Repository/CustomTypeConverter.php +++ b/src/Repository/CustomTypeConverter.php @@ -36,13 +36,15 @@ abstract class CustomTypeConverter * @param callable $onCreate * @return string */ - public function addOnCreate(callable $onCreate): string + public static function addOnCreate(callable $onCreate): string { $hookKey = null; - while (!array_key_exists((string)$hookKey, self::$onCreate) || $hookKey === null) { + while (array_key_exists((string)$hookKey, self::$onCreate) || $hookKey === null) { $hookKey = Random::generate(12); } + self::$onCreate[$hookKey] = $onCreate; + return $hookKey; } @@ -53,7 +55,7 @@ public function addOnCreate(callable $onCreate): string * @param string $hookKey * @return bool */ - public function removeOnCreate(string $hookKey): bool + public static function removeOnCreate(string $hookKey): bool { if (array_key_exists($hookKey, self::$onCreate)) { unset(self::$onCreate[$hookKey]); diff --git a/tests/Mock/Repository/ConfigurationNotFoundException.php b/tests/Mock/Repository/ConfigurationNotFoundException.php new file mode 100644 index 0000000..81a4509 --- /dev/null +++ b/tests/Mock/Repository/ConfigurationNotFoundException.php @@ -0,0 +1,10 @@ +configuration === null) { + throw new ConfigurationNotFoundException('Configuration not found!'); + } + + + if($encoded === false) { + throw new Exception('Should not be false!'); + } + + return $encoded; + } + + public function deserialize(mixed $value): mixed + { + /** @noinspection JsonEncodingApiUsageInspection */ + $decoded = json_decode($value, true); + + if($this->configuration === null) { + throw new ConfigurationNotFoundException('Configuration not found!'); + } + + return $decoded; + } + + public function getDatabaseType(): string + { + return 'longtext'; + } +} diff --git a/tests/Repository/CustomTypeConverterTest.php b/tests/Repository/CustomTypeConverterTest.php new file mode 100644 index 0000000..310c2da --- /dev/null +++ b/tests/Repository/CustomTypeConverterTest.php @@ -0,0 +1,63 @@ +getProperty('testProperty') + ); + + $exampleArray = ['hello', 'world']; + + $this->assertExceptionThrown( + ConfigurationNotFoundException::class, + function () use ($converter, $exampleArray) { + $converter->serialize($exampleArray); + } + ); + + CustomTypeConverter::addOnCreate( + static function (CustomTypeConverter $converter) { + if($converter instanceof HookExampleConverter) { + $converter->configuration = new stdClass(); + } + } + ); + + //Re-create the converter, so the hook has a chance to get applied: + + /** @var HookExampleConverter $converter */ + $converter = CustomTypeConverter::initialize( + HookExampleConverter::class, $thisReflection->getProperty('testProperty') + ); + + + $this->assertNoExceptionThrown( + function () use ($converter, $exampleArray) { + $converter->serialize($exampleArray); + } + ); + + + } + + +}