kristos80 / opton
Easily get a value from an array or object without all of those unnecessary array_key_exists or isset controls
Installs: 3 859
Dependents: 1
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 0
Open Issues: 0
Requires (Dev)
- phpunit/phpunit: ^7
README
Opton
Easily get a value from an array or object without all of those unnecessary array_key_exists
or isset
controls.
Install (via composer)
$ composer require kristos80/opton
Notation syntax allowed as of version 1.1.2
$dataContainer = array( 'container' => (object) array( // Object or array it doesn't matter 'nested' => array( 'value' => array( 'in' => array( 'value', ), ), ), ), ); echo Opton::get('container.nested.value.in', $dataContainer); // Prints `value`
Source code
/** * * @param array|object|string $name * The name of the option/key to be found * @param array|object|NULL $pool * The pool of data to search within * @param mixed|NULL $default * Default value if nothing is found * @param array|object|NULL $acceptedValues * Array of accepted values. It affects even the `default` value * @return mixed|NULL */ static function get($name, $pool = array(), $default = NULL, array $acceptedValues = array()) {
Examples
<?php require_once 'vendor/autoload.php'; use Kristos80\Opton\Opton; $options = array( 'optionName' => 'optionValue', ); $acceptedValues = array( 'optionValue', ); // prints 'optionValue' echo Opton::get('optionName', $options, NULL, $acceptedValues); echo "\r\n"; // prints `NULL` echo Opton::get('optionNameNonExistent', $options); echo "\r\n"; // prints 'defaultValue' echo Opton::get('optionNameNonExistent', $options, 'defaultValue'); echo "\r\n"; // prints `NULL` echo Opton::get('optionNameNonExistent', $options, 'defaultValue', $acceptedValues); echo "\r\n"; // `name` can be an array // prints 'optionValue' echo Opton::get(array( 'optionName', 'optionNameNonExistent', ), $options); echo "\r\n"; // Use a single configuration array with keys: // `name` // `pool` // `default` // `acceptedValues` // // prints 'defaultValue' echo Opton::get(array( 'name' => 'optionNameNonExistent', 'pool' => $options, 'default' => 'defaultValue', )); echo "\r\n";
Run tests
vendor/bin/phpunit --bootstrap vendor/autoload.php vendor/kristos80/opton/tests/OptonTest