1<?php
2
3declare(strict_types=1);
4
5/*
6 * The MIT License (MIT)
7 *
8 * Copyright (c) 2014-2019 Spomky-Labs
9 *
10 * This software may be modified and distributed under the terms
11 * of the MIT license.  See the LICENSE file for details.
12 */
13
14namespace Webauthn\AuthenticationExtensions;
15
16use ArrayIterator;
17use Assert\Assertion;
18use Countable;
19use Iterator;
20use IteratorAggregate;
21use JsonSerializable;
22
23class AuthenticationExtensionsClientOutputs implements JsonSerializable, Countable, IteratorAggregate
24{
25    /**
26     * @var AuthenticationExtension[]
27     */
28    private $extensions = [];
29
30    public function add(AuthenticationExtension $extension): void
31    {
32        $this->extensions[$extension->name()] = $extension;
33    }
34
35    public static function createFromString(string $data): self
36    {
37        $data = json_decode($data, true);
38        Assertion::eq(JSON_ERROR_NONE, json_last_error(), 'Invalid data');
39        Assertion::isArray($data, 'Invalid data');
40
41        return self::createFromArray($data);
42    }
43
44    public static function createFromArray(array $json): self
45    {
46        $object = new self();
47        foreach ($json as $k => $v) {
48            $object->add(new AuthenticationExtension($k, $v));
49        }
50
51        return $object;
52    }
53
54    public function has(string $key): bool
55    {
56        return \array_key_exists($key, $this->extensions);
57    }
58
59    /**
60     * @return mixed
61     */
62    public function get(string $key)
63    {
64        Assertion::true($this->has($key), sprintf('The extension with key "%s" is not available', $key));
65
66        return $this->extensions[$key];
67    }
68
69    public function jsonSerialize(): array
70    {
71        return $this->extensions;
72    }
73
74    public function getIterator(): Iterator
75    {
76        return new ArrayIterator($this->extensions);
77    }
78
79    public function count(int $mode = COUNT_NORMAL): int
80    {
81        return \count($this->extensions, $mode);
82    }
83}
84