Skip to content

Instantly share code, notes, and snippets.

@AnrDaemon
Created February 20, 2019 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnrDaemon/87dfd8593b9aed123bac5c6ae466f4b3 to your computer and use it in GitHub Desktop.
Save AnrDaemon/87dfd8593b9aed123bac5c6ae466f4b3 to your computer and use it in GitHub Desktop.
Typed array
<?php
/** Collection handler for webpage content blocks
*
* @version SVN: $Id: PageUnitsCollection.php 1231 2018-08-11 19:40:50Z anrdaemon $
*/
namespace AnrDaemon\CcWeb\Helpers;
use
AnrDaemon\CcWeb\Objects\PageUnit;
class PageUnitsCollection
extends \ArrayObject
{
public function _sort(PageUnit $a, PageUnit $b)
{
if($a['showorder'] > $b['showorder'])
return 1;
if($a['showorder'] < $b['showorder'])
return -1;
if($a['id'] > $b['id'])
return 1;
if($a['id'] < $b['id'])
return -1;
return 0;
}
protected function _validate($state, $index = null)
{
if(is_null($state))
return null;
if($state instanceof PageUnit)
return $state;
if(is_array($state))
{
$value = PageUnit::createFromState($value);
return $value;
}
throw new \InvalidArgumentException("Value " . ($index ? "at index {$index} " : "") . "must be of type AnrDaemon\\CcWeb\\Objects\\PageUnit or compatible.");
}
// Magic!
public function __construct($array = array(), $flags = 0)
{
parent::{__FUNCTION__}([], $flags);
$this->exchangeArray($array);
}
// ArrayAccess
public function offsetSet($offset, $state)
{
$value = $this->_validate($state);
if(empty($value))
return $this->offsetUnset($offset);
return parent::{__FUNCTION__}($offset, $value);
}
// ArrayObject
public function append($value)
{
return $this->offsetSet(null, $value);
}
public function asort()
{
$this->uasort([$this, "_sort"]);
}
public function exchangeArray($array)
{
$data = [];
foreach($array as $offset => $state)
{
$value = $this->_validate($state, $offset);
if(empty($value))
continue;
$data[$offset] = $value;
}
return parent::{__FUNCTION__}($data);
}
// Serializable
public function serialize()
{
return serialize($this->getArrayCopy());
}
public function unserialize($value)
{
$this->exchangeArray(unserialize($value));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment