Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improvement App\Parameters #45

Merged
merged 1 commit into from
Jan 26, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 64 additions & 5 deletions src/Parameters.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,88 @@

namespace App;

use function array_key_exists;
use function strpos;
use function explode;

/**
* Parameters provides a way to get application parameters defined in config/params.php
*
* In order to use in a handler or any other place supporting auto-wired injection:
*
* ```php
* $params = [
* 'admin' => [
* 'email' => 'demo@example.com'
* ]
* ];
* ```
*
* ```php
* public function actionIndex(Parameters $parameters)
* {
* $adminEmail = $parameters->get('admin.email', 'admin@example.com');
* $adminEmail = $parameters->get('admin.email', 'admin@example.com'); // return demo@example.com or admin@example.com if search key not exists in parameters
* }
* ```
*/
class Parameters
{
private array $parameters;
private string $glue;

public function __construct(array $data, string $glue = '.')
{
$this->parameters = $data;
$this->glue = $glue;
}

public function get(string $key, $default = null)
{
if (strpos($key, $this->glue) !== false) {
$keys = explode($this->glue, $key);
return $this->hasNesting($keys) ? $this->getNesting($keys) : $default;
}

return $this->has($key) ? $this->parameters[$key] : $default;
}

public function has(string $key): bool
{
if (strpos($key, $this->glue) !== false) {
return $this->hasNesting(explode($this->glue, $key));
}

return array_key_exists($key, $this->parameters);
}

public function __construct(array $parameters)
public function getAll(): array
{
$this->parameters = $parameters;
return $this->parameters;
}

public function get(string $name, $default = null)
private function hasNesting(array $keys): bool
{
return $this->parameters[$name] ?? $default;
$ref = $this->parameters;
foreach ($keys as $key) {
if (!array_key_exists($key, $ref)) {
return false;
}
$ref = $ref[$key];
}

return true;
}

private function getNesting(array $keys)
{
$data = $this->parameters;
foreach ($keys as $key) {
if (!array_key_exists($key, $data)) {
return null;
}
$data = $data[$key];
}

return $data;
}
}