php-simple-jwt/src/Collection/PropertyBag.php

145 lines
3.1 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 $prop Property name
* @param mixed $value 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 $prop Property name
* @param mixed $value Value
*/
public function set(string $prop, $value)
{
$this->props[$prop] = $value;
}
/**
* Apply properties without removing anything.
*
* @param array $props The properties to apply
*/
public function setAll(array $props)
{
$this->props = array_merge(
$this->props,
$props
);
}
/**
* 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 $prop 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 $prop Property name
* @param mixed|null $default 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
*
* @param string $prop Property name
*/
public function delete(string $prop)
{
unset($this->props[$prop]);
}
/**
* Check if a property is present
*
* @param string $prop Property name
*/
public function has(string $prop): bool
{
return array_key_exists($prop, $this->props);
}
/**
* Check if all the provided properties are present
*
* @param array $props Property names
*/
public function hasAll(array $props)
{
foreach ($props as $prop) {
if (!$this->has($prop)) return false;
}
return true;
}
}