125 lines
2.6 KiB
PHP
125 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace NoccyLabs\SimpleJwt\Collection;
|
|
|
|
use ArrayAccess;
|
|
use Countable;
|
|
|
|
class PropertyBag
|
|
{
|
|
|
|
/**
|
|
* @var array
|
|
*/
|
|
private $props = [];
|
|
|
|
public function __construct(array $props=[])
|
|
{
|
|
$this->props = $props;
|
|
}
|
|
|
|
/**
|
|
* Add a property value, fails if the property exists
|
|
*
|
|
* @param string Property name
|
|
* @param mixed Value
|
|
* @throws PropertyException if the property already exists
|
|
*/
|
|
public function add(string $prop, $value)
|
|
{
|
|
if (array_key_exists($prop, $this->props)) {
|
|
throw new PropertyException("Property already exists");
|
|
}
|
|
$this->props[$prop] = $value;
|
|
}
|
|
|
|
/**
|
|
* Set a property value, create the property if it doesn't
|
|
* exist.
|
|
*
|
|
* @param string Property name
|
|
* @param mixed Value
|
|
*/
|
|
public function set(string $prop, $value)
|
|
{
|
|
$this->props[$prop] = $value;
|
|
}
|
|
|
|
/**
|
|
* Get the value of a property, fails if the property does not exist.
|
|
* Use the value() method to get with a default value
|
|
*
|
|
* @param string Property name
|
|
* @return mixed
|
|
* @throws PropertyException if the property does not exist
|
|
*/
|
|
public function get(string $prop)
|
|
{
|
|
if (!array_key_exists($prop, $this->props)) {
|
|
throw new PropertyException("No such property");
|
|
}
|
|
return $this->props[$prop];
|
|
}
|
|
|
|
/**
|
|
* Retrieve all properties.
|
|
*
|
|
* @return array
|
|
*/
|
|
public function getAll(): array
|
|
{
|
|
return $this->props;
|
|
}
|
|
|
|
/**
|
|
* Retrieve all properties as a json string
|
|
*
|
|
* @return string
|
|
*/
|
|
public function getJson(): string
|
|
{
|
|
return json_encode($this->props, JSON_UNESCAPED_SLASHES);
|
|
}
|
|
|
|
/**
|
|
* Get the value of the property, or use the provided default value.
|
|
*
|
|
* @param string Property name
|
|
* @param mixed Default value
|
|
* @return mixed
|
|
*/
|
|
public function valueOf(string $prop, $default=null)
|
|
{
|
|
return array_key_exists($prop, $this->props)
|
|
? $this->props[$prop]
|
|
: $default;
|
|
}
|
|
|
|
/**
|
|
* Remove a property
|
|
*/
|
|
public function delete(string $prop)
|
|
{
|
|
unset($this->props[$prop]);
|
|
}
|
|
|
|
/**
|
|
* Check if a property is present
|
|
*/
|
|
public function has(string $prop): bool
|
|
{
|
|
return array_key_exists($prop, $this->props);
|
|
}
|
|
|
|
/**
|
|
* Check if all the provided properties are present
|
|
*/
|
|
public function hasAll(array $props)
|
|
{
|
|
foreach ($props as $prop) {
|
|
if (!$this->has($prop)) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
} |