Failed Conditions
Push — master ( cf9b90...f0e999 )
by Florent
05:40
created

DataBag::jsonSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(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
14
namespace OAuth2Framework\Component\Core\DataBag;
15
16
use ArrayIterator;
17
use Assert\Assertion;
18
19
class DataBag implements \IteratorAggregate, \Countable, \JsonSerializable
20
{
21
    /**
22
     * @var array
23
     */
24
    private $parameters = [];
25
26
    public function __construct(array $parameters)
27
    {
28
        $this->parameters = $parameters;
29
    }
30
31
    public function has(string $key): bool
32
    {
33
        return \array_key_exists($key, $this->parameters);
34
    }
35
36
    /**
37
     * @param null|mixed $default
38
     *
39
     * @return null|mixed
40
     */
41
    public function get(string $key, $default = null)
42
    {
43
        if ($this->has($key)) {
44
            return $this->parameters[$key];
45
        }
46
47
        return $default;
48
    }
49
50
    /**
51
     * @param null|mixed $value
52
     */
53
    public function set(string $key, $value): void
54
    {
55
        $this->parameters[$key] = $value;
56
    }
57
58
    public function all(): array
59
    {
60
        return $this->parameters;
61
    }
62
63
    public function count(): int
64
    {
65
        return \count($this->parameters);
66
    }
67
68
    public function getIterator(): ArrayIterator
69
    {
70
        return new ArrayIterator($this->parameters);
71
    }
72
73
    public static function createFromString(string $data): self
74
    {
75
        $json = json_decode($data, true);
76
        Assertion::eq(JSON_ERROR_NONE, json_last_error(), 'Invalid data');
77
        Assertion::isArray($json, 'Invalid data');
78
79
        return new self($json);
80
    }
81
82
    public function jsonSerialize(): array
83
    {
84
        return $this->parameters;
85
    }
86
}
87