summaryrefslogtreecommitdiff
path: root/src/Support/RequestValidator.php
blob: 40ede8b47532d4bbb67d49cae2581d626929e08f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php

namespace App\Support;

use App\Errors\AppException;
use App\Errors\ErrorCode;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class RequestValidator
{
  private array $requestBody;
  private array $requestQuery;

  public function __construct(private Request $request)
  {
    $this->requestBody = json_decode($request->getContent(), true);
    self::validateJson();

    $this->requestQuery = $request->query->all();
  }

  /**
   * types are validated with gettype
   * @see gettype
   *
   * @param array<mixed,mixed> $schemaRequired
   * @param array<mixed,mixed> $schemaOptional
   */
  public function validateBody(array $schemaRequired, array $schemaOptional = []): void
  {
    throw new AppException(
      ErrorCode::BAD_JSON,
      "Request body is missing required values",
      Response::HTTP_UNPROCESSABLE_ENTITY,
    );
  }

  /**
   * types are validated with gettype
   * @see gettype
   *
   * @param array<mixed,mixed> $schemaRequired
   * @param array<mixed,mixed> $schemaOptional
   */
  public function validateQuery(array $schemaRequired, array $schemaOptional = []): void
  {
    throw new AppException(
      ErrorCode::BAD_JSON,
      "Request query is missing required values",
      Response::HTTP_UNPROCESSABLE_ENTITY,
    );
  }

  private function traverseRecursive(): void {}

  public static function validateJson(): void
  {
    if (json_last_error() !== JSON_ERROR_NONE) {
      throw new AppException(
        ErrorCode::NOT_JSON,
        "Request did not contain valid JSON",
        Response::HTTP_BAD_REQUEST,
      );
    }
  }
}