Skip to content

Instantly share code, notes, and snippets.

@devosc
Last active March 25, 2018 18:42
Show Gist options
  • Save devosc/6a601d4b2be549624030f340c460ff0e to your computer and use it in GitHub Desktop.
Save devosc/6a601d4b2be549624030f340c460ff0e to your computer and use it in GitHub Desktop.
multiple has get
<?php
/**
*
*/
namespace Mvc5\Config;
trait Config
{
/**
* @param array|string $name
* @return mixed
*/
function get($name)
{
if (is_string($name)) {
return is_array($this->config) ? ($this->config[$name] ?? null) : $this->config[$name];
}
$matched = [];
foreach($name as $key) {
null !== ($value = $this->config[$key] ?? null)
&& $matched[$key] = $value;
}
return $matched;
}
/**
* @param array|string $name
* @return bool
*/
function has($name) : bool
{
if (is_string($name)) {
return isset($this->config[$name]);
}
foreach($name as $key) {
if (!isset($this->config[$key])) {
return false;
}
}
return true;
}
}
<?php
/**
*
*/
namespace Mvc5\Test\Config;
class ConfigTest
extends TestCase
{
/**
*
*/
function test_get_multiple()
{
$config = new Config(['foo' => 'bar', 'baz' => 'bat']);
$this->assertEquals(['foo' => 'bar', 'baz' => 'bat'], $config->get(['foo', 'foobar', 'baz']));
$config = new Config(new Config(['foo' => 'bar', 'baz' => 'bat']));
$this->assertEquals(['foo' => 'bar', 'baz' => 'bat'], $config->get(['foo', 'foobar', 'baz']));
}
/**
*
*/
function test_has_multiple()
{
$config = new Config(['foo' => 'bar', 'baz' => 'bat']);
$this->assertTrue($config->has(['foo', 'baz']));
$this->assertFalse($config->has(['foo', 'foobar', 'baz']));
$config = new Config(new Config(['foo' => 'bar', 'baz' => 'bat']));
$this->assertTrue($config->has(['foo', 'baz']));
$this->assertFalse($config->has(['foo', 'foobar', 'baz']));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment