Skip to content

Instantly share code, notes, and snippets.

@rquast
Created March 19, 2018 13:25
Show Gist options
  • Save rquast/fe4471048ed0ee463df070fbf0e60206 to your computer and use it in GitHub Desktop.
Save rquast/fe4471048ed0ee463df070fbf0e60206 to your computer and use it in GitHub Desktop.
<?php
namespace Cavy\Model\DTO;
abstract class AbstractBase implements Base {
/**
* @return array
*/
public function toArray() {
// NOTE: function($value, $key) is the right order.
$arr = array_filter(get_object_vars($this), function($value, $key) {
if (is_array($value)) {
return true;
}
if ($key === 0 || $value === 0) {
return true;
}
if ($key === false || $value === false) {
return true;
}
if (!isset($value) || is_null($value) || $value == null) {
return false;
}
if (!isset($key) || is_null($key) || $key == null) {
return false;
}
return true;
}, ARRAY_FILTER_USE_BOTH);
return $arr;
}
private function _snakeToCamel($val) {
$val = str_replace(' ', '', ucwords(str_replace('_', ' ', $val)));
$val = strtolower(substr($val,0,1)).substr($val,1);
return $val;
}
/**
* @param $json mixed The JSON string to be hydrated
*/
public function hydrate($json) {
$arr = $json;
if (!is_array($arr)) {
$arr = json_decode($json, true);
}
foreach($arr as $key => $value) {
$method = 'set' . ucfirst($this->_snakeToCamel($key));
if(is_callable(array($this, $method))) {
call_user_func(array($this, $method), $value);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment