|
| 1 | +<?php declare(strict_types=1); |
| 2 | +/** |
| 3 | + * This file is part of toolkit/stdlib. |
| 4 | + * |
| 5 | + * @author https://github.com/inhere |
| 6 | + * @link https://github.com/php-toolkit/stdlib |
| 7 | + * @license MIT |
| 8 | + */ |
| 9 | + |
| 10 | +namespace Toolkit\Stdlib\Obj; |
| 11 | + |
| 12 | +use ArrayObject; |
| 13 | + |
| 14 | +/** |
| 15 | + * Class ConfigObject |
| 16 | + * |
| 17 | + * @package Toolkit\Stdlib\Obj |
| 18 | + */ |
| 19 | +class ConfigObject extends ArrayObject |
| 20 | +{ |
| 21 | + /** |
| 22 | + * @param array $data |
| 23 | + * |
| 24 | + * @return static |
| 25 | + */ |
| 26 | + public static function new(array $data = []) |
| 27 | + { |
| 28 | + return new static($data); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * @param string $key |
| 33 | + * @param mixed $default |
| 34 | + * |
| 35 | + * @return mixed|null |
| 36 | + */ |
| 37 | + public function getValue(string $key, $default = null) |
| 38 | + { |
| 39 | + return $this[$key] ?? $default; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * @param string $key |
| 44 | + * @param bool $default |
| 45 | + * |
| 46 | + * @return bool |
| 47 | + */ |
| 48 | + public function getBool(string $key, bool $default = false): bool |
| 49 | + { |
| 50 | + if ($this->offsetExists($key)) { |
| 51 | + return (bool)$this->offsetGet($key); |
| 52 | + } |
| 53 | + |
| 54 | + return $default; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * @param string $key |
| 59 | + * @param int $default |
| 60 | + * |
| 61 | + * @return int |
| 62 | + */ |
| 63 | + public function getInt(string $key, int $default = 0): int |
| 64 | + { |
| 65 | + return $this->getInteger($key, $default); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * @param string $key |
| 70 | + * @param int $default |
| 71 | + * |
| 72 | + * @return int |
| 73 | + */ |
| 74 | + public function getInteger(string $key, int $default = 0): int |
| 75 | + { |
| 76 | + if ($this->offsetExists($key)) { |
| 77 | + return (int)$this->offsetGet($key); |
| 78 | + } |
| 79 | + |
| 80 | + return $default; |
| 81 | + } |
| 82 | + |
| 83 | + /** |
| 84 | + * @param string $key |
| 85 | + * @param string $default |
| 86 | + * |
| 87 | + * @return string |
| 88 | + */ |
| 89 | + public function getString(string $key, string $default = ''): string |
| 90 | + { |
| 91 | + if ($this->offsetExists($key)) { |
| 92 | + return (string)$this->offsetGet($key); |
| 93 | + } |
| 94 | + |
| 95 | + return $default; |
| 96 | + } |
| 97 | + |
| 98 | + /** |
| 99 | + * @return array |
| 100 | + */ |
| 101 | + public function toArray(): array |
| 102 | + { |
| 103 | + return $this->getArrayCopy(); |
| 104 | + } |
| 105 | +} |
0 commit comments