Skip to content

Instantly share code, notes, and snippets.

@kevindees
Last active March 12, 2020 18: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 kevindees/0b673c53f084484a296b9844febeecb1 to your computer and use it in GitHub Desktop.
Save kevindees/0b673c53f084484a296b9844febeecb1 to your computer and use it in GitHub Desktop.
<?php
$job = new stdClass;
$job->title = 'dev';
$data = [
'person' => [
'name' => ['first' => 'kevin', 'last' => 'dees']
],
'job' => $job
];
echo nil($data)['person']['name']['first']->get(); // kevin
echo nil($data)->person->name->first->get(); // null
echo nil($data)['job']->title->get(); // dev
nil($data)['job']->title; // Nil
isset( nil($data)['person']->email ); // false
<?php
nil($value) {
return new Nil($value);
}
<?php
class Nil implements ArrayAccess
{
/** @var mixed */
protected $value;
/**
* @param mixed $value
*
* @return void
*/
public function __construct($value = null)
{
$this->value = $value;
}
/**
* @return mixed|null
*/
public function get()
{
return $this->value instanceof Nil ? $this->value->get() : $this->value;
}
/**
* @param string $key
*
* @return mixed
*/
public function __get($key)
{
return new Nil($this->value->{$key} ?? new Nil);
}
/**
* @param mixed $name
*
* @return bool
*/
public function __isset($name)
{
if (is_object($this->value)) {
return isset($this->value->{$name});
}
if ($this->arrayCheck()) {
return isset($this->value[$name]);
}
return false;
}
/**
* @param mixed $key
*
* @return bool
*/
public function offsetExists($key)
{
return $this->arrayCheck($key);
}
/**
* @param mixed $key
*
* @return mixed
*/
public function offsetGet($key)
{
return new Nil($this->value[$key] ?? new Nil);
}
/**
* @param mixed $key
* @param mixed $value
*
* @return void
*/
public function offsetSet($key, $value)
{
if ($this->arrayCheck()) {
$this->value[$key] = $value;
}
}
/**
* @param string $key
*
* @return void
*/
public function offsetUnset($key)
{
if ($this->arrayCheck()) {
unset($this->value[$key]);
}
}
/**
* @param null|string $key
*
* @return bool
*/
protected function arrayCheck($key = null) {
if(is_array($this->value) || $this->value instanceof ArrayAccess) {
if($key && !($this->value[$key] ?? null)) {
return false;
}
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment