dechamp / shorty
Just a few tools to help avoid annoying things such as long logic where it should be simple.
Requires
- php: >=5.6
Requires (Dev)
- phpunit/phpunit: ^5.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
The goal of this library is to provide easy helpers to shorten repetitive task that are used day in and day out.
Guidelines
- Do not create something that you can get from another supported library.
- K.I.S.S. (Keep it simple stupid), don't make large helpers.
- Keep them as static methods for simplicity
Helps shorten typical logic that can become excessive, such as getting a value from an deep array or returning null.
Methods
grabOrNull((array|object) $haystack, (string) $needle)
Used when dealing with arrays or object, when getting values. check recursively for key, return value or null if key not found
- $haystack - (array|object) it will do the same, for array or object
- $needle - (string) search recursively by seperating the keys with
/, expa/b/c
example usage
use
Shorty::grabOrNull($deepArray, "a/b/c/d");
instead of...
isset($deepArray['a']['b']['c']['d']) ? $deepArray['a']['b']['c']['d'] : null;
grabOr((array|object) $haystack, (string) $needle, (mixed) $default)
Used when dealing with arrays or object, when getting values. check recursively for key, return value or your default if key not found
- $haystack - (array|object) it will do the same, for array or object
- $needle - (string) search recursively by seperating the keys with
/, expa/b/c - $default - (mixed) anything you wish to return by default
example usage
use
Shorty::grabOr($deepArray, "a/b/c/d", "tacos");
instead of...
isset($deepArray['a']['b']['c']['d']) ? $deepArray['a']['b']['c']['d'] : "tacos";
grabOrThrow((array|object) $haystack, (string) $needle, Exception $exception)
Used when dealing with arrays or object, when getting values. check recursively for key, return value or throw your exception.
- $haystack - (array|object) it will do the same, for array or object
- $needle - (string) search recursively by seperating the keys with
/, expa/b/c - $exception - Exception instance
example usage
use
try {
$val = Shorty::grabOrThrow($deepArray, "a/b/c/d", new Exception('No tacos'));
} ...
instead of...
try {
if (! isset($deepArray['a']['b']['c']['d'])) {
throw new Exception('No Tacos');
}
$val = $deepArray['a']['b']['c']['d'];
} ...
guard() this is now deprecated, use https://packagist.org/packages/webmozart/assert instead
Testing
You can use the included Dockerfile for running phpunit.
Setup
1 docker build -t shorty .
2 docker run -it -v $PWD:/var/www/html shorty /bin/bash
3 phpunit and phpunit --coverage-text