Skip to content

Instantly share code, notes, and snippets.

@wouterj
Created February 8, 2013 16:44
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 wouterj/4740229 to your computer and use it in GitHub Desktop.
Save wouterj/4740229 to your computer and use it in GitHub Desktop.
ParameterAccessor
{
"require": {
"symfony/property-access": "2.3.x@dev"
}
}
<?php
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
class ParameterAccessor
{
private $parameters;
/**
* @var PropertyAccessorInterface
*/
private $accessor;
public function __construct(PropertyAccessorInterface $accessor)
{
$this->accessor = $accessor;
}
public function get($path)
{
if (is_array($this->parameters)) {
if ('[' !== substr($path, 0, 1)) {
if (false === strpos($path, '.')) {
$path = '['.$path.']';
} else {
$path = '['.str_replace('.', '][', $path).']';
}
}
}
// use the accessor
return $this->accessor->getValue($this->parameters, $path);
}
public function setData($parameters)
{
$this->parameters = $parameters;
}
}
<?php
use Symfony\Component\PropertyAccess\PropertyAccess;
require "ParameterAccessor.php";
class ParameterAccessorTest extends \PHPUnit_Framework_TestCase
{
protected $accessor;
public function setUp()
{
$this->accessor = new ParameterAccessor($this->getPropertyAccessor());
}
/**
* @dataProvider getArraysData
*/
public function testArrays(array $array, $path, $expected)
{
$a = $this->accessor;
$a->setData($array);
$this->assertEquals($expected, $a->get($path));
}
public function getArraysData()
{
return array(
// 1 level
array(array('foo' => 'bar'), 'foo', 'bar'),
// 2 levels
array(array('foo' => array('bar' => 'cat')), 'foo.bar', 'cat'),
// 3 levels
array(array('foo' => array('bar' => array('cat' => 'dolor'))), 'foo.bar.cat', 'dolor'),
// normal way
array(array('foo' => 'bar'), '[foo]', 'bar'),
);
}
/**
* @dataProvider getObjectsData
*/
public function testObjects($object, $path, $expected)
{
$a = $this->accessor;
$a->setData($object);
$this->assertEquals($expected, $a->get($path));
}
public function getObjectsData()
{
return array(
// 1 level
array((object) array('foo' => 'bar'), 'foo', 'bar'),
// 2 levels
array((object) array('foo' => (object) array('bar' => 'cat')), 'foo.bar', 'cat'),
// 3 levels
array((object) array('foo' => (object) array('bar' => (object) array('cat' => 'dolor'))), 'foo.bar.cat', 'dolor'),
);
}
protected function getPropertyAccessor()
{
return PropertyAccess::getPropertyAccessor();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment