2017 © Pedro Peláez
 

library var-check

Accessing properties, keys and instance methods without checking them all the time.

image

itarato/var-check

Accessing properties, keys and instance methods without checking them all the time.

  • Tuesday, February 23, 2016
  • by itarato
  • Repository
  • 0 Watchers
  • 0 Stars
  • 752 Installations
  • PHP
  • 1 Dependents
  • 0 Suggesters
  • 1 Forks
  • 0 Open issues
  • 1 Versions
  • 31 % Grown

The README.md

VarCheck

Build Status, (*1)

VarCheck is a single class to verify nested complex variable without lots of isset() and exist()., (*2)

To avoid multiple level of isset/exist/etc this class provides an easy way to verify nested values in a variable. Typical use case when you have a large variable, and you are not sure if it has the right index, and inside there an object, and an attribute ..., (*3)

The complex variable

$myComplexVar = array(1 => new stdClass());
$myComplexVar[1]->name = 'John Doe';

Problem to solve

// Get the value:
$output = isset($myComplexVar[1]) && isset($myComplexVar[1]->name) ? $myComplexVar[1]->name : $otherwise;

Solution

$output = VarCheck::take($myComplexVar)->key(1)->attr('name')->value($otherwise);
// or even simpler:
$output = VarCheck::take($myComplexVar)->{'1'}->name->value($otherwise);

Checking if the nested value exist

VarCheck::take($myComplexVar)->key(1)->attr('name')->exist(); // TRUE;
// or:
VarCheck::take($myComplexVar)->{'1'}->name->exist(); // TRUE;

Get the nested value

VarCheck::take($myComplexVar)->key(1)->attr('name')->value(); // John Doe;

Call a function on the value if exist

// Instead of this:
$value = isset($variable['key']['foo']->element) ? my_function($variable['key']['foo']->element) : NULL;
// Do this:
$value = VarCheck::take($variable)->key->foo->element->my_function();
// Or:
$myClassInstance;
$value = arCheck::take($variable)->key->foo->element->call(array($myClassInstance, 'instanceFunction'));

Failsafe check in case it does not exist

VarCheck::take($myComplexVar)->key(1)->attr('job')->exist(); // FALSE;
VarCheck::take($myComplexVar)->key(1)->attr('job')->attr('title')->exist(); // FALSE;

Check and value at the same time

if ($value = VarCheck::take($form_status)->key('values')->key('#node')->attr('field_image')->key(LANGUAGE_NONE)->key(0)->key('item')->key('fid')->value()) {
  // Use $value;
}
// or:
if ($value = VarCheck::take($form_status)->values->{'#node'}->field_image->{LANGUAGE_NONE}->{'0'}->item->fid->value()) {
  // Use $value;
}

Custom validation

VarCheck::take($myVar)->key(3)->attr('title')->call(function ($v) {
  return $v > 10;
});

The Versions

23/02 2016

2.x-dev

2.9999999.9999999.9999999-dev

Accessing properties, keys and instance methods without checking them all the time.

  Sources   Download

MIT