property-accessor.php

Simple property accessor library
git clone git://git.finwo.net/lib/property-accessor.php
Log | Files | Refs

commit b71d773f39a247e6fec31d73e7cb047099bf54f0
parent 8e24b69046eb7076d4f18ffa20468cb9d490c341
Author: finwo <finwo@pm.me>
Date:   Tue, 19 Apr 2016 15:13:15 +0200

Added unset

Diffstat:
Msrc/PropertyAccessor.php | 53++++++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 52 insertions(+), 1 deletion(-)

diff --git a/src/PropertyAccessor.php b/src/PropertyAccessor.php @@ -40,7 +40,7 @@ class PropertyAccessor $target = $subject; $path = explode($pathSplit, $path); foreach($path as $part) { - $target = $this->get($target, $part, $pathSplit); + $target = &$this->get($target, $part, $pathSplit); } return $target; } @@ -202,6 +202,57 @@ class PropertyAccessor return $target; } + public function remove(&$input, $path, $splitChar = '|') + { + // Do nothing if we can't use the property + if (!is_array($input) && !is_object($input)) { + return; + } + + // Convert the path to something useful + if (!is_array($path)) { + + // Do nothing if we can't use the path + if (!is_string($path)) { + return; + } + + // Split by the split character + $path = explode($splitChar, $path); + } + + // Fetch the last key + $lastKey = array_pop($path); + + // Fetch the parent + if (count($path)) { + $target = &$this->get($input, implode('|', $path), '|'); + } else { + $target = &$input; + } + + // Handle if the target is an array + if (is_array($target)) { + if (!isset($target[$lastKey])) { + return; + } + unset($target[$lastKey]); + return; + } + + // Handle if the target is an object + if (is_object($target)) { + if (!isset($target->{$lastKey})) { + return; + } + unset($target->{$lastKey}); + return; + } + + // We're not compatible with this type + return; + } + protected function setArrayProperty(&$input = array(), $path = array(), $value) { $target = &$input;