summaryrefslogtreecommitdiff
path: root/server/vendor/php-opencloud/common/src/Common/JsonSchema/Schema.php
blob: e1e3f65770d1679d1248f1dc2bf2b86fd7e24677 (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
68
69
70
71
72
73
74
75
<?php declare(strict_types=1);

namespace OpenCloud\Common\JsonSchema;

use JsonSchema\Validator;

class Schema
{
    /** @var object */
    private $body;

    /** @var Validator */
    private $validator;

    public function __construct($body, Validator $validator = null)
    {
        $this->body = (object) $body;
        $this->validator = $validator ?: new Validator();
    }

    public function getPropertyPaths(): array
    {
        $paths = [];

        foreach ($this->body->properties as $propertyName => $property) {
            $paths[] = sprintf("/%s", $propertyName);
        }

        return $paths;
    }

    public function normalizeObject($subject, array $aliases): \stdClass
    {
        $out = new \stdClass;

        foreach ($this->body->properties as $propertyName => $property) {
            $name = isset($aliases[$propertyName]) ? $aliases[$propertyName] : $propertyName;
            if (isset($property->readOnly) && $property->readOnly === true) {
                continue;
            } elseif (property_exists($subject, $name)) {
                $out->$propertyName = $subject->$name;
            } elseif (property_exists($subject, $propertyName)) {
                $out->$propertyName = $subject->$propertyName;
            }
        }

        return $out;
    }

    public function validate($data)
    {
        $this->validator->check($data, $this->body);
    }

    public function isValid(): bool
    {
        return $this->validator->isValid();
    }

    public function getErrors(): array
    {
        return $this->validator->getErrors();
    }

    public function getErrorString(): string
    {
        $msg = "Provided values do not validate. Errors:\n";

        foreach ($this->getErrors() as $error) {
            $msg .= sprintf("[%s] %s\n", $error['property'], $error['message']);
        }

        return $msg;
    }
}