|
3 | 3 | namespace Keepsuit\CookieSolution; |
4 | 4 |
|
5 | 5 | use Carbon\Carbon; |
| 6 | +use DateTimeInterface; |
6 | 7 | use Illuminate\Support\Arr; |
7 | 8 | use Illuminate\Support\Collection; |
8 | 9 | use Illuminate\Support\Facades\File; |
| 10 | +use Illuminate\Support\Facades\Validator; |
9 | 11 | use Illuminate\Support\HtmlString; |
10 | 12 | use Illuminate\Support\Str; |
11 | 13 | use Illuminate\Support\Stringable; |
| 14 | +use Illuminate\Validation\ValidationException; |
12 | 15 |
|
13 | 16 | class CookieSolution |
14 | 17 | { |
@@ -41,22 +44,44 @@ public function status(): CookieSolutionStatus |
41 | 44 |
|
42 | 45 | $json = \Illuminate\Support\Facades\Cookie::get(config('cookie-solution.cookie_name')); |
43 | 46 |
|
44 | | - if ($json === null) { |
| 47 | + if (! is_string($json)) { |
45 | 48 | return $this->status = CookieSolutionStatus::default(); |
46 | 49 | } |
47 | 50 |
|
48 | 51 | try { |
49 | 52 | $value = json_decode($json, true, JSON_THROW_ON_ERROR); |
| 53 | + } catch (\JsonException) { |
| 54 | + return $this->status = CookieSolutionStatus::default(); |
| 55 | + } |
50 | 56 |
|
51 | | - if ($this->configDigest() !== ($value['digest'] ?? null)) { |
| 57 | + try { |
| 58 | + $validator = Validator::make($value, [ |
| 59 | + 'digest' => ['required', 'string'], |
| 60 | + 'timestamp' => ['required', sprintf('date_format:%s', DateTimeInterface::ATOM)], |
| 61 | + 'purposes' => ['required', 'array'], |
| 62 | + 'purposes.*' => ['required', 'boolean'], |
| 63 | + ]); |
| 64 | + |
| 65 | + /** |
| 66 | + * @var array{ |
| 67 | + * digest: string, |
| 68 | + * timestamp: string, |
| 69 | + * purposes: array<string, bool> |
| 70 | + * } $validated |
| 71 | + */ |
| 72 | + $validated = $validator->validated(); |
| 73 | + |
| 74 | + if ($this->configDigest() !== $validated['digest']) { |
52 | 75 | return $this->status = CookieSolutionStatus::default(); |
53 | 76 | } |
54 | 77 |
|
55 | 78 | return $this->status = new CookieSolutionStatus( |
56 | | - timestamp: Carbon::parse($value['timestamp']), |
57 | | - purposes: $value['purposes'], |
| 79 | + timestamp: Carbon::createFromFormat(DateTimeInterface::ATOM, $validated['timestamp']), |
| 80 | + purposes: collect($validated['purposes']) |
| 81 | + ->filter(fn (bool $active, string $key) => CookiePurpose::tryFrom($key) !== null) |
| 82 | + ->all(), |
58 | 83 | ); |
59 | | - } catch (\JsonException $e) { |
| 84 | + } catch (ValidationException) { |
60 | 85 | return $this->status = CookieSolutionStatus::default(); |
61 | 86 | } |
62 | 87 | } |
|
0 commit comments