Skip to content

Commit

Permalink
Changed findValueByName to correctly parse SimpleXmlObjects. Will not…
Browse files Browse the repository at this point in the history
… traverse anymore
  • Loading branch information
milos-pejanovic-devtech committed Mar 8, 2017
1 parent e43d89a commit 3233965
Showing 1 changed file with 33 additions and 13 deletions.
46 changes: 33 additions & 13 deletions src/Common/Util/Iteration.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,30 +17,50 @@ class Iteration {
* @param string $name
* @param object|array $source
* @param mixed $defaultValue
* @param bool $traverse
* @return mixed
*/
public static function findValueByName($name, $source, $defaultValue = null, $traverse = false) {
public static function findValueByName($name, $source, $defaultValue = null) {
if(!is_array($source) && !is_object($source)) {
throw new \InvalidArgumentException('The source must be an array, or an object with accessible properties.');
}
$sourceValue = $defaultValue;
foreach($source as $key => $value) {
if($name === $key && !Validation::isEmpty($value)) {
$sourceValue = $value;
break;
}
if($traverse && (is_array($value) || is_object($value))) {
$sourceValue = self::findValueByName($name, $value, $defaultValue, true);
if($sourceValue !== $defaultValue) {
break;
}
}
if(is_array($source)) {
$sourceValue = self::findValueInArray($source, $name, $defaultValue);
}
elseif($source instanceof \SimpleXMLElement) {
$sourceValue = self::findValueInSimpleXmlElement($source, $name, $defaultValue);
}
elseif(is_object($source)) {
$sourceValue = self::findValueInObject($source, $name, $defaultValue);
}

return $sourceValue;
}

public static function findValueInArray($source, $name, $defaultValue) {
$value = $defaultValue;
if(isset($source[$name]) && !Validation::isEmpty($value)) {
$value = $source[$name];
}
return $value;
}

public static function findValueInObject($source, $name, $defaultValue) {
$value = $defaultValue;
if(isset($source->$name) && !Validation::isEmpty($source->$name)) {
$value = $source->$name;
}
return $value;
}

public function findValueInSimpleXmlElement(\SimpleXMLElement $source, $name, $defaultValue) {
$value = self::findValueInObject($source, $name, $defaultValue);
if($value instanceof \SimpleXMLElement && $value->children()->count() === 0) {
$value = (string) $value;
}
return $value;
}

/**
* Assigns null to values considered empty
* @see Validation::isEmpty
Expand Down

0 comments on commit 3233965

Please sign in to comment.