kristos80/opton

Easily get a value from an array or object without all of those unnecessary array_key_exists or isset controls

v1.1.2 2020-03-16 14:49 UTC

This package is auto-updated.

Last update: 2025-03-01 00:16:21 UTC


README

Reliability Rating Security Rating Technical Debt Vulnerabilities Bugs Codacy Badge Maintainability CodeScene Code Health CodeScene System Mastery Packagist

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