Skip to content

Instantly share code, notes, and snippets.

@drupol
Created June 2, 2020 12:22
Show Gist options
  • Save drupol/30d0c0b806491aba6c9dc315b0a50131 to your computer and use it in GitHub Desktop.
Save drupol/30d0c0b806491aba6c9dc315b0a50131 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace loophp\collection;
use ArrayAccess;
use ArrayIterator;
use ArrayObject;
use Countable;
use InvalidArgumentException;
use IteratorAggregate;
use SplFixedArray;
final class FixedArray implements ArrayAccess, Countable, IteratorAggregate
{
/**
* @var SplFixedArray
*/
private $storage;
/**
* FixedArray constructor.
*
* @param iterable $iterable
*/
public function __construct(iterable $iterable)
{
$this->storage = SplFixedArray::fromArray([]);
foreach ($iterable as $item) {
$this->storage = SplFixedArray::fromArray(array_merge($this->storage->toArray(), [$item]));
}
}
public function asort()
{
$data = $this->storage->toArray();
asort($data);
return new self($data);
}
public function count(): int
{
new ArrayObject();
return $this->storage->count();
}
public function filter(callable $callback, int $flag = 0)
{
$data = $this->storage->toArray();
return array_filter($data, $callback, $flag);
}
public function getIterator()
{
return new ArrayIterator($this->storage->toArray());
}
public function ksort()
{
$data = $this->storage->toArray();
ksort($data);
return new self($data);
}
public function natcasesort()
{
$data = $this->storage->toArray();
natcasesort($data);
return new self($data);
}
public function natsort()
{
$data = $this->storage->toArray();
natsort($data);
return new self($data);
}
public function offsetExists($offset)
{
return $this->storage->offsetExists($offset);
}
public function offsetGet($offset)
{
return $this->storage->offsetGet($offset);
}
public function offsetSet($offset, $value)
{
throw new InvalidArgumentException('Use FixedArray::set($offset, $value).');
}
public function offsetUnset($offset)
{
throw new InvalidArgumentException('Use FixedArray::unset($offset).');
}
public function set($offset, $value): FixedArray
{
$data = $this->storage->toArray();
$data[$offset] = $value;
return new self($data);
}
public function uasort(callable $callback)
{
$data = $this->storage->toArray();
uasort($data, $callback);
return new self($data);
}
public function uksort(callable $callback)
{
$data = $this->storage->toArray();
uksort($data, $callback);
return new self($data);
}
public function unset(...$offsets): FixedArray
{
$data = $this->storage->toArray();
foreach ($offsets as $offset) {
unset($data[$offset]);
}
return new self($data);
}
public function usort(callable $callback)
{
$data = $this->storage->toArray();
usort($data, $callback);
return new self($data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment