Skip to content

Instantly share code, notes, and snippets.

@pepakriz
Last active December 25, 2015 16:59
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 pepakriz/7009908 to your computer and use it in GitHub Desktop.
Save pepakriz/7009908 to your computer and use it in GitHub Desktop.
<?php
/**
* This file is part of the Grido (http://grido.bugyik.cz)
*
* Copyright (c) 2011 Petr Bugyík (http://petr.bugyik.cz)
*
* For the full copyright and license information, please view
* the file license.md that was distributed with this source code.
*/
namespace Grido\PropertyAccessors;
/**
* Accessor for array and object structures.
*
* @package Grido
* @subpackage PropertyAccessors
* @author Josef Kříž <pepakriz@gmail.com>
*/
class ArrayObjectAccessor implements IPropertyAccessor
{
/**
* @param mixed $object
* @param string $name
* @return mixed
*/
public static function getProperty($object, $name)
{
if (is_array($object)) {
try {
return $object[$name];
} catch (\Exception $e) {
throw new PropertyAccessorException("Property with name '$name' does not exists in datasource.");
}
} elseif (is_object($object)) {
try {
return $object->$name;
} catch (\Exception $e) {
throw new PropertyAccessorException("Property with name '$name' does not exists in datasource.");
}
}
throw new \InvalidArgumentException('Please implement your own property accessor.');
}
/**
* @param mixed $object
* @param string $name
* @param string $value
*/
public static function setProperty($object, $name, $value)
{
if (isset($object->$name) || (is_object($object) && property_exists($object, $name))) {
$object->$name = $value;
} else {
$object[$name] = $value;
}
}
}
@o5
Copy link

o5 commented Oct 16, 2013

https://gist.github.com/pepakriz/7009908#file-arrayobjectaccessor-php-L33
..joo takto by to bylo fajn, ale to IMHO PHP neumi.. jedine pres error handler si nastavit zpracovani notice - ale trochu overkill ne?

@o5
Copy link

o5 commented Oct 16, 2013

Pak je taky řešení se na všechno vyprdnout a nechat jen holé:

public static function getProperty($object, $name)
{
    if (is_array($object)) {
        return $object[$name];

    } elseif (is_object($object)) {
        return $object->$name;

    } else {
        throw new \InvalidArgumentException('Please implement your own property accessor.');
    }
}

S tím, že tedy žádná kontrola typu https://github.com/o5/grido/blob/tests/Grido/Components/Actions/Action.php#L173-L179 nebude...(To jsi asi navrhoval před tím půlrokem :D )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment