Skip to content

Instantly share code, notes, and snippets.

@useless-stuff
Created February 11, 2016 12:10
Show Gist options
  • Save useless-stuff/902bd5325687b23b4d1e to your computer and use it in GitHub Desktop.
Save useless-stuff/902bd5325687b23b4d1e to your computer and use it in GitHub Desktop.
PHP - IteratorIterator
<?php
// IteratorIterator is a wrapper to work with others Iterator
/**
* Class ImagesFilter
*/
class ImagesFilter extends IteratorIterator
{
/**
* @param $status
* @return ArrayObject
*/
public function getImagesByStatus($status)
{
$status = $this->validateInputStatus($status);
$result = new \ArrayObject();
foreach (parent::getInnerIterator() as $image) {
/** @var Image $image */
if ($image->getStatus() === $status) {
$result->append($image);
}
}
return $result;
}
/**
* @param $status
* @return mixed
*/
protected function validateInputStatus($status)
{
if (is_int($status) && $status === 1 || $status === 0) {
return $status;
}
throw new \InvalidArgumentException(__METHOD__.' - param given: '.$status);
}
}
class ImagesCollection extends ArrayIterator implements Collection
{
/**
* Proxy to getArrayCopy
* @return array
*/
public function getCollection()
{
return $this->getArrayCopy();
}
}
/**
* Class Image
*/
class Image
{
const FIELD_STATUS_ACTIVE = 1;
const FIELD_STATUS_INACTIVE = 0;
protected $name;
protected $status;
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return mixed
*/
public function getStatus()
{
return $this->status;
}
/**
* @param mixed $status
*/
public function setStatus($status)
{
$this->status = $status;
}
}
/**
* Interface Collection
*/
interface Collection
{
/**
* @return Collection
*/
public function getCollection();
}
// Generate random Image objects
$imagesCollection = new ImagesCollection();
for ($i = 0; $i < 100; $i++) {
$tmp = new Image();
$tmp->setName(md5(microtime()));
$tmp->setStatus(rand(0, 1));
$imagesCollection->append($tmp);
}
unset($tmp);
$activeImagesFilter = new ImagesFilter($imagesCollection);
$activeImages = $activeImagesFilter->getImagesByStatus(Image::FIELD_STATUS_ACTIVE);
foreach($activeImages->getIterator() as $image){
print_r($image);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment