Skip to content

Instantly share code, notes, and snippets.

@useless-stuff
Created February 16, 2016 09:56
Show Gist options
  • Save useless-stuff/9b4063570f343dd70eac to your computer and use it in GitHub Desktop.
Save useless-stuff/9b4063570f343dd70eac to your computer and use it in GitHub Desktop.
PHP - Filter iterator
<?php
/**
* Class ServerList
*/
class ServersList extends RecursiveArrayIterator
{
}
/**
* Class ServerListManager
*/
class ServersListFilter extends FilterIterator
{
protected $filterKey = null, $filterValue = null;
/**
* Wrapper to accept();
* @param $key
* @param $value
* @return bool
*/
public function filterBy($key, $value)
{
$this->filterKey = $key;
$this->filterValue = $value;
return $this->accept();
}
/**
* Check whether the current element of the iterator is acceptable
* @link http://php.net/manual/en/filteriterator.accept.php
* @return bool true if the current element is acceptable, otherwise false.
* @since 5.1.0
*/
public function accept()
{
if (!$this->filterKey || !$this->filterValue) {
throw new RuntimeException("Filter was not set! ".__METHOD__);
}
$item = $this->getInnerIterator()->current();
if (isset($item[$this->filterKey])) {
return ($this->filterValue === $item[$this->filterKey]);
}
return null;
}
}
$serverList = new ServersList(
array(
'server_01' => array(
'location' => 'EU',
'availability' => true,
'name' => 'chopin01',
'services' => array(
'http' => 80,
'ssh' => 22,
),
),
'server_02' => array(
'location' => 'US',
'availability' => false,
'name' => 'mozart01',
'services' => array(
'http' => 80,
'ssh' => 22,
),
),
'server_03' => array(
'location' => 'EU',
'availability' => true,
'name' => 'chopin02',
'services' => array(
'http' => 8080,
'ssh' => 22,
),
),
)
);
$iterator = new ServersListFilter($serverList);
$iterator->accept();
$iterator->filterBy('availability', true);
$output = array();
foreach ($iterator as $key => $value) {
print_r($value);
}
// Output:
/*
[
{
location: "EU",
availability: "1",
name: "chopin01",
services:
{
http: "80",
ssh: "22"
}
},
{
location: "EU",
availability: "1",
name: "chopin02",
services:
{
http: "8080",
ssh: "22"
}
}
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment