|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Nuxtifyts\PhpDto\Concerns; |
| 4 | + |
| 5 | +use Nuxtifyts\PhpDto\Configuration\DataConfiguration; |
| 6 | +use Nuxtifyts\PhpDto\Contexts\ClassContext; |
| 7 | +use Nuxtifyts\PhpDto\Exceptions\DataCreationException; |
| 8 | +use Nuxtifyts\PhpDto\Exceptions\DataValidationException; |
| 9 | + |
| 10 | +use Throwable; |
| 11 | +use Exception; |
| 12 | + |
| 13 | +trait ValidateableData |
| 14 | +{ |
| 15 | + /** |
| 16 | + * @throws DataValidationException |
| 17 | + */ |
| 18 | + public static function validate(mixed $data): void |
| 19 | + { |
| 20 | + try { |
| 21 | + $validationConfig = DataConfiguration::getInstance()->validation; |
| 22 | + |
| 23 | + $validationRules = $validationConfig->validationRulesRefererClass::createInstance() |
| 24 | + ->getRulesFromClassContext(ClassContext::getInstance(static::class)); |
| 25 | + |
| 26 | + $validationConfig |
| 27 | + ->validatorClass::createInstance($validationRules) |
| 28 | + ->validate($data); |
| 29 | + } catch (Throwable $t) { |
| 30 | + throw DataValidationException::invalidData($t->getMessage(), previous: $t); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * @param array<string, mixed> $data |
| 36 | + * |
| 37 | + * @throws DataValidationException |
| 38 | + */ |
| 39 | + public static function validateAndCreate(array $data): static |
| 40 | + { |
| 41 | + try { |
| 42 | + /** @var ClassContext<static> $context */ |
| 43 | + $context = ClassContext::getInstance(static::class); |
| 44 | + |
| 45 | + $value = static::normalizeValue($args, static::class, $context->normalizers) |
| 46 | + ?: static::normalizeValue($args[0] ?? [], static::class, $context->normalizers); |
| 47 | + |
| 48 | + if ($value === false) { |
| 49 | + throw DataCreationException::invalidParamsPassed(static::class); |
| 50 | + } |
| 51 | + |
| 52 | + // Add Validate Data pipe |
| 53 | + } catch (Throwable $t) { |
| 54 | + throw DataValidationException::invalidData($t->getMessage(), previous: $t); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public function isValid(): bool |
| 59 | + { |
| 60 | + try { |
| 61 | + $this::validate($this->toArray()); |
| 62 | + |
| 63 | + return true; |
| 64 | + } catch (Exception) { |
| 65 | + return false; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * @param ?array<array-key, mixed> $data |
| 71 | + * |
| 72 | + * @return array<string, mixed> |
| 73 | + */ |
| 74 | + public static function validationRules(?array $data = null): array |
| 75 | + { |
| 76 | + return []; |
| 77 | + } |
| 78 | +} |
0 commit comments