phplibrary/src/Collection.php
2025-11-02 12:33:26 +03:00

114 lines
2.2 KiB
PHP

<?php
namespace ctiso;
/**
* Коллекция
* @implements \ArrayAccess<string,mixed>
*/
class Collection implements \ArrayAccess
{
/** @var array */
protected $data = [];
/**
* Преобразование массива в коллекцию
*
* @param array $data
* @return bool
*/
public function import(array $data)
{
$this->data = array_merge($this->data, $data);
return true;
}
/**
* Преобразование коллекции в массив
*
* @return array
*/
public function export()
{
return $this->data;
}
/**
* @param string $key
* @param mixed $value
*
* @return void
*/
public function set(string $key, mixed $value)
{
$this->data[$key] = $value;
}
/**
* Read stored "request data" by referencing a key.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public function get($key, $default = null)
{
return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default;
}
/**
* @param string $key
* @param int $default
* @return int
*/
public function getInt($key, $default = 0)
{
return (int)$this->get($key, $default);
}
/**
* @param string $key
* @param string $default
* @return string
*/
public function getString(string $key, string $default = ''): string
{
return (string)$this->get($key, $default);
}
/**
* @param string $key
* @param int $default
* @return int
*/
public function getNat($key, $default = 1)
{
$result = (int)$this->get($key, $default);
return (($result > 0) ? $result : $default);
}
public function clear(): void
{
$this->data = [];
}
public function offsetSet($key, $value): void
{
$this->data[$key] = $value;
}
public function offsetExists($key): bool
{
return isset($this->data[$key]);
}
public function offsetUnset($key): void
{
unset($this->data[$key]);
}
public function offsetGet($key): mixed
{
return $this->data[$key] ?? null;
}
}