|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Fleetbase\FleetOps\Rules; |
| 4 | + |
| 5 | +use Fleetbase\FleetOps\Models\Vehicle; |
| 6 | +use Illuminate\Contracts\Validation\Rule; |
| 7 | +use Illuminate\Support\Str; |
| 8 | + |
| 9 | +class ResolvableVehicle implements Rule |
| 10 | +{ |
| 11 | + /** |
| 12 | + * The resolved vehicle instance, if found. |
| 13 | + */ |
| 14 | + protected ?Vehicle $resolved = null; |
| 15 | + |
| 16 | + /** |
| 17 | + * Determine if the validation rule passes. |
| 18 | + * |
| 19 | + * Accepts: |
| 20 | + * - A public_id string (e.g. "vehicle_abc123") |
| 21 | + * - A UUID string (e.g. "550e8400-e29b-41d4-a716-446655440000") |
| 22 | + * - An array/object containing an "id", "public_id", or "uuid" key |
| 23 | + * |
| 24 | + * @param string $attribute |
| 25 | + * |
| 26 | + * @return bool |
| 27 | + */ |
| 28 | + public function passes($attribute, $value) |
| 29 | + { |
| 30 | + $identifier = $this->extractIdentifier($value); |
| 31 | + |
| 32 | + if (empty($identifier)) { |
| 33 | + return true; // nullable — let the nullable rule handle empty values |
| 34 | + } |
| 35 | + |
| 36 | + if (Str::isUuid($identifier)) { |
| 37 | + $this->resolved = Vehicle::where('uuid', $identifier)->first(); |
| 38 | + } else { |
| 39 | + $this->resolved = Vehicle::where('public_id', $identifier)->first(); |
| 40 | + } |
| 41 | + |
| 42 | + return $this->resolved !== null; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Get the validation error message. |
| 47 | + * |
| 48 | + * @return string |
| 49 | + */ |
| 50 | + public function message() |
| 51 | + { |
| 52 | + return 'The :attribute must be a valid vehicle public ID, UUID, or vehicle object.'; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Extract a string identifier from the given value. |
| 57 | + * |
| 58 | + * Handles a plain string, an associative array, or a stdClass object. |
| 59 | + */ |
| 60 | + protected function extractIdentifier($value): ?string |
| 61 | + { |
| 62 | + if (is_string($value)) { |
| 63 | + return $value; |
| 64 | + } |
| 65 | + |
| 66 | + if (is_array($value)) { |
| 67 | + return data_get($value, 'id') |
| 68 | + ?? data_get($value, 'public_id') |
| 69 | + ?? data_get($value, 'uuid') |
| 70 | + ?? null; |
| 71 | + } |
| 72 | + |
| 73 | + if (is_object($value)) { |
| 74 | + return data_get($value, 'id') |
| 75 | + ?? data_get($value, 'public_id') |
| 76 | + ?? data_get($value, 'uuid') |
| 77 | + ?? null; |
| 78 | + } |
| 79 | + |
| 80 | + return null; |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * Get the resolved Vehicle model instance after validation passes. |
| 85 | + */ |
| 86 | + public function getResolved(): ?Vehicle |
| 87 | + { |
| 88 | + return $this->resolved; |
| 89 | + } |
| 90 | +} |
0 commit comments