- Requirements
- How to install
- Global helper functions
- Debug global helper functions
- Class helpers
- License
- Change log
- Testing
- Contributing
- Security
- Credits
- About
- PHP 7.2 or higher
Via Composer:
composer require sebastiaanluca/php-helpers
All function helpers will be enabled by default (if those functions haven't already been defined). Class helpers are enabled per-case when used.
You can find more info on how to use a helper and what there requirements are in their respective section (see the table of contents above for an overview).
Randomly return true
or false
.
rand_bool();
// true
Wrap a string with another string.
str_wrap('foo', '*');
// "*foo*"
Check if an array is associative.
Performs a simple check to determine if the given array's keys are numeric, start at 0, and count up to the amount of values it has.
is_assoc_array(['color' => 'blue', 'age' => 31]);
// true
is_assoc_array([0 => 'blue', 7 => 31]);
// true
is_assoc_array(['blue', 31]);
// false
is_assoc_array([0 => 'blue', 1 => 31]);
// false
Expand a flat dotted array into a multi-dimensional associative array.
If a key is encountered that is already present and the existing value is an array, each new value will be added to that array. If it's not an array, each new value will override the existing one.
array_expand(['products.desk.price' => 200]);
/*
[
"products" => [
"desk" => [
"price" => 200,
],
],
]
*/
Get the array without the given values.
Accepts either an array or a value as parameter to remove.
$cars = ['bmw', 'mercedes', 'audi'];
$soldOut = ['audi', 'bmw'];
$inStock = array_without($cars, $soldOut);
// ["mercedes"]
array_without(['one', 'two', 'three'], 'two');
// ["one", "three"]
Pull a single value from a given array.
Returns the given value if it was successfully removed from the source array or null
if it was not found.
$source = ['A', 'B', 'C'];
$removed = array_pull_value($source, 'C');
// $removed = "C"
// $source = ["A", "B"]
Pull an array of values from a given array.
Returns the values that were successfully removed from the source array or an empty array if none were found.
$source = ['A', 'B', 'C'];
$removed = array_pull_values($source, ['A', 'B']);
// $removed = ["A", "B"]
// $source = ["C"]
Create a unique string identifier for an array.
The identifier will be entirely unique for each combination of keys and values.
array_hash([1, 2, 3]);
// "262bbc0aa0dc62a93e350f1f7df792b9"
array_hash(['hash' => 'me']);
// "f712e79b502bda09a970e2d4d47e3f88"
Create a unique string identifier for an object.
Similar to array_hash, this uses serialize
to stringify all public properties first. The identifier will be entirely unique based on the object class, properties, and its values.
class ValueObject {
public $property = 'randomvalue';
}
object_hash(new ValueObject);
// "f39eaea7a1cf45f5a0c813d71b5f2f57"
Check if a class has a certain public method.
class Hitchhiker {
public function answer() {
return 42;
}
}
has_public_method(Hitchhiker::class, 'answer');
// true
has_public_method(new Hitchhiker, 'answer');
// true
Create a Carbon datetime object from a string or return a new object referencing the current date and time.
Requires the nesbot/carbon package.
carbon('2017-01-18 11:30');
/*
Carbon\Carbon {
"date": "2017-01-18 11:30:00.000000",
"timezone_type": 3,
"timezone": "UTC",
}
*/
carbon();
/*
Carbon\Carbon {
"date": "2017-10-27 16:18:00.000000",
"timezone_type": 3,
"timezone": "UTC",
}
*/
Create a temporary file.
Returns an array with the file handle (resource) and the full path as string.
The temporary file is readable and writeable by default. The file is automatically removed when closed (for example, by calling fclose() on the handle, or when there are no remaining references to the file handle), or when the script ends.
temporary_file();
/*
[
"file" => stream resource {
timed_out: false
blocked: true
eof: false
wrapper_type: "plainfile"
stream_type: "STDIO"
mode: "r+b"
unread_bytes: 0
seekable: true
uri: "/tmp/phpxm4bcZ"
options: []
}
"path" => "/tmp/phpxm4bcZ"
]
*/
Display structured debug information about one or more values in plain text using Kint and halt script execution afterwards. Accepts multiple arguments to dump.
Output will be identical to ddd
when used in a command line interface. In a browser, it'll display plain, but structured text.
Requires the kint-php/kint package.
sss('string');
/*
┌─────────────────────────────────────────┐
│ literal │
└─────────────────────────────────────────┘
string (6) "string"
═══════════════════════════════════════════
Called from .../src/MyClass.php:42
*/
sss('string', 0.42, ['array']);
/*
┌─────────────────────────────────────────┐
│ literal │
└─────────────────────────────────────────┘
string (6) "string"
┌─────────────────────────────────────────┐
│ literal │
└─────────────────────────────────────────┘
double 0.42
┌─────────────────────────────────────────┐
│ literal │
└─────────────────────────────────────────┘
array (1) [
0 => string (5) "array"
]
═══════════════════════════════════════════
Called from .../src/MyClass.php:42
*/
Display structured debug information about one or more values using Kint and halt script execution afterwards. Accepts multiple arguments to dump. Output will be identical to sss
when used in a command line interface. In a browser, it'll display an interactive, structured tree-view.
Requires the kint-php/kint package.
See the sss helper for example output.
Display structured debug information about one or more values in plain text using Kint and halt script execution afterwards, but only if the condition is truthy. Does nothing if falsy. Accepts multiple arguments to dump.
Requires the kint-php/kint package.
sss_if($user->last_name, 'User has a last name', $user->last_name);
See the sss helper for example output.
Display structured debug information about one or more values using Kint and halt script execution afterwards, but only if the condition is truthy. Does nothing if falsy. Accepts multiple arguments to dump.
Requires the kint-php/kint package.
ddd_if(app()->environment('local'), 'Debugging in a local environment!');
See the ddd helper for example output.
The primary use of the Enum
trait is to enable you to store all cases of a specific type in a single class or value object and have it return those with a single call.
This can be useful for instance when your database uses integers to store states, but you want to use descriptive strings throughout your code (i.e. enums). It also allows you to refactor these elements at any time without having to waste time searching your code for any raw values (and probably miss a few, introducing new bugs along the way).
Returns an array of element keys and their values.
<?php
use SebastiaanLuca\PhpHelpers\Classes\Enum;
class UserStates
{
use Enum;
public const REGISTERED = 'registered';
public const ACTIVATED = 'activated';
public const DISABLED = 'disabled';
}
UserStates::enums();
// or
(new UserStates)->enums();
/*
[
"REGISTERED" => "registered",
"ACTIVATED" => "activated",
"DISABLED" => "disabled",
]
*/
Returns all the keys of the elements in an enum.
<?php
use SebastiaanLuca\PhpHelpers\Classes\Enum;
class UserStates
{
use Enum;
public const REGISTERED = 'registered';
public const ACTIVATED = 'activated';
public const DISABLED = 'disabled';
}
UserStates::keys();
/*
[
"REGISTERED",
"ACTIVATED",
"DISABLED",
]
*/
Returns all the values of the elements in an enum.
<?php
use SebastiaanLuca\PhpHelpers\Classes\Enum;
class UserStates
{
use Enum;
public const REGISTERED = 'registered';
public const ACTIVATED = 'activated';
public const DISABLED = 'disabled';
}
UserStates::values();
/*
[
"registered",
"activated",
"disabled",
]
*/
The ProvidesClassInfo
trait provides an easy-to-use getClassDirectory()
helper method that returns the directory of the current class.
<?php
namespace Kyle\Helpers;
use SebastiaanLuca\PhpHelpers\Classes\ProvidesClassInfo;
class MyClass
{
use ProvidesClassInfo;
public function __construct()
{
var_dump($this->getClassDirectory());
}
}
// "/Users/Kyle/Projects/php-helpers"
A static class helper to help you figure out the visibility/accessibility of an object's methods.
<?php
class SomeClass
{
private function aPrivateMethod() : string
{
return 'private';
}
protected function aProtectedMethod() : string
{
return 'protected';
}
public function aPublicMethod() : string
{
return 'public';
}
}
MethodHelper::hasMethodOfType($class, 'aPrivateMethod', 'private');
// true
MethodHelper::hasProtectedMethod($class, 'aProtectedMethod');
// true
MethodHelper::hasPublicMethod($class, 'aPublicMethod');
// true
MethodHelper::hasProtectedMethod($class, 'aPrivateMethod');
// false
MethodHelper::hasPublicMethod($class, 'invalidMethod');
// false
This package operates under the MIT License (MIT). Please see LICENSE for more information.
Please see CHANGELOG for more information what has changed recently.
composer install
composer test
Please see CONTRIBUTING and CODE OF CONDUCT for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
My name is Sebastiaan and I'm a freelance back-end developer specializing in building custom Laravel applications. Check out my portfolio for more information, my blog for the latest tips and tricks, and my other packages to kick-start your next project.
Have a project that could use some guidance? Send me an e-mail at [email protected]!