Index
abort abort_if add_trailing_slash app array_list ask command compact_unique_array concat_ws config convert_array_to_object esc_attr esc_attr__ esc_html esc_html__ esc_js esc_textarea esc_url flatten_array gate gravatar gravatar_profile is_error is_false is_null__ is_true__ mail method_field now php_like php_where purify_html queue remove_trailing_slash site_url sort_element_callback strip_tags__ t__ throw_if trim__ truncate_string user
abort
Throw an HttpException with the given data.
<?php
use Domain\User\Query\FindUserByIdQuery;
use function Codefy\Framework\Helpers\abort;
use function Codefy\Framework\Helpers\ask;
function find_user_by_id(string $id): object
{
$user = ask(new FindUserByIdQuery(['userId' => $id]));
if (!$user) {
abort(
code: 404,
uri: '/admin/',
message: 'User not found.'
);
}
return $user;
}
abort_if
Abort (throw an HttpException) if the given condition is true.
<?php
use Domain\User\Query\FindUserByIdQuery;
use function Codefy\Framework\Helpers\abort_if;
use function Codefy\Framework\Helpers\ask;
function find_user_by_id(string $id): object|bool
{
return ask(new FindUserByIdQuery(['userId' => $id]));
}
abort_if(
condition: false === find_user_by_id('01KDNPDG0YE32R47FBC6R0VBE2'),
code: 404,
uri: '/admin/',
message: 'User not found.'
);
abort_unless
Abort (throw an HttpException) unless the given condition is true.
<?php
use function Codefy\Framework\Helpers\abort_if;
use function Codefy\Framework\Helpers\gate;
abort_unless(
condition: gate('edit_user'),
code: 403,
uri: '/admin/',
message: 'Access denied.'
);
add_trailing_slash
Appends a trailing slash.
Will remove trailing forward and backslashes if it exists already before adding a trailing forward slash. This prevents double slashing a string or path.
app
Returns the Qubus\Injector\ServiceContainer or Psr\Container\ContainerInterface instance. You may pass a class, alias, or interface name to resolve it from the container as well as any needed parameters.
Warning
This helper is available for ease of use, but should be used sparingly. It is highly recommended that you use a ServiceProvider and dependency injection.
<?php
use function Codefy\Framework\Helpers\app;
return app(); // returns ContainerInterface|ServiceContainer
<?php
use Qubus\Routing\Psr7Router;
use function Codefy\Framework\Helpers\app;
$router = app(name: Psr7Router::class); // resolves router from Injector
<?php
use Qubus\Routing\Psr7Router;
use function Codefy\Framework\Helpers\app;
$router = app()->alias(
original: \Psr\SimpleCache\CacheInterface::class,
alias: \Qubus\Cache\Psr16\SimpleCache::class
); // binds alias to the original (interface)
array_list
Return a collection based on type.
<?php
use function Qubus\Support\Helpers\array_list;
$callables = [
fn() => 'Hello World!',
fn() => 'I love programming!',
fn() => 'I love PHP!'
];
$list = array_list('callable');
foreach ($callables as $callable) {
$list->add($callable);
}
echo $list->type(); // callable
// or
echo $list->all()[2](); // I love PHP!
To use the array_list() helper beyond the example above, check out Collections. The array_list() helper and the collect() helper inherit some of the same methods but may return different results. Another difference is that collect() can return a mixture of primitives and data structures, while array_list() returns an array of the same specified primitive type.
ask
Queries the given query and returns a result if any.
<?php
use Domain\User\Query\FindUserByIdQuery;
use function Codefy\Framework\Helpers\ask;
$userId = '01KFRYWSVYEFS9MHXHZR0JDF59';
$query = new FindUserByIdQuery(data: [
'userId' => $userId,
]);
$user = ask($query);
command
Dispatches the given $command through the CommandBus.
<?php
use App\Domain\Post\Commands\CreatePostCommand;
use App\Domain\Post\ValueObject\Content;
use App\Domain\Post\ValueObject\PostId;
use App\Domain\Post\ValueObject\Title;
use function Codefy\Framework\Helpers\command;
$createPostCommand = new CreatePostCommand();
$createPostCommand->postId = new PostId();
$createPostCommand->title = new Title(value: 'New Post Title');
$createPostCommand->content = new Content(value: 'Short form content.');
command(command: $createPostCommand);
compact_unique_array
Strips out all duplicate values and compact the array.
concat_ws
Concatenation with separator.
echo concat_ws('CodefyPHP', 'Framework'); // "CodefyPHP,Framework"
echo concat_ws(
'I love mangoes',
'grapes',
', ',
'pears',
'and pineapple on pizza.'
); // "I love mangoes, grapes, pears, and pineapple on pizza."
config
Return the ConfigContainer instance or get / set the specified configuration value. The configuration values may be accessed using "dot" syntax, which includes the name of the file and the option you wish to access. You may also provide a default value that will be returned if the configuration option does not exist.
<?php
use function Codefy\Framework\Helpers\config;
$timezone = config(key: 'app.timezone');
// or
$timezone = config(key: 'app.timezone', default: 'America/Los_Angeles');
<?php
use function Codefy\Framework\Helpers\config;
$config = config(); // returns the ConfigContainer instance.
<?php
use function Codefy\Framework\Helpers\config;
config(key: ['app' => ['locale' => 'es']]); // set app.locale value to 'es'.
convert_array_to_object
Takes an array and turns it into an object.
esc_attr
Escaping for HTML attributes.
esc_attr__
Escapes a translated string to make it safe for HTML attribute.
esc_html
Escapes html.
esc_html__
Escapes a translated string to make it safe for HTML output.
esc_js
Escaping for inline javascript.
<?php
$esc_js = json_encode("Joshua's \"code\"");
$attribute = esc_js("alert($esc_js);");
echo '<input type="button" value="push" onclick="'.$attribute.'" />';
esc_textarea
Escapes for textarea.
esc_url
Escapes a url.
flatten_array
Turns multi-dimensional array into a regular array.
gate
Returns a Codefy\Framework\Auth\Gate instance or true if user has specified permission.
<?php
use function Codefy\Framework\Helpers\gate;
$auth = gate(); // returns Gate instance
// or
$auth = gate(permission: 'edit_user');
// or
$auth = gate(
permission: 'edit_user',
ruleParams: ['userId' => $userId, 'post' => $post]
);
gravatar
Return a new Gravatar Image instance.
<?php
// Get a Gravatar image instance:
$image = gravatar('email@example.com');
// return: Gravatar\Image
// Get a Gravatar image URL:
$imageUrl = gravatar('email@example.com')->url();
// return: //www.gravatar.com/avatar/5658ffccee7f0ebfda2b226238b1eb6e
// Show a Gravatar image URL:
echo gravatar('email@example.com');
// output: //www.gravatar.com/avatar/5658ffccee7f0ebfda2b226238b1eb6e
// With optional parameters:
$avatar = gravatar('email@example.com')
->size(120)
->defaultImage('robohash')
->maxRating('pg')
->extension('jpg');
echo $avatar;
// Or set the email later:
$avatar = gravatar()
->email('email@example.com')
->size(200);
echo $avatar;
// With initials (convenience method):
$avatar = gravatar('email@example.com')
->withInitials('JD')
->size(120);
echo $avatar;
gravatar_profile
Return a new Gravatar Profile instance.
<?php
// Get a Gravatar profile instance:
$profile = gravatar_profile('email@example.com');
// return: Gravatar\Profile
// Get a Gravatar profile URL:
echo gravatar_profile('email@example.com');
// output: https//www.gravatar.com/5658ffccee7f0ebfda2b226238b1eb6e
// With format parameter:
$profileUrl = gravatar_profile('email@example.com')
->format('json')
->url();
is_error
Check whether variable is an Error instance.
<?php
use Qubus\Error\Error;
use function Qubus\Error\Helpers\is_error;
function has_permission(string $permission): Error|string
{
if ($permission === '') {
return new Error('The permission value is invalid');
}
return $permission;
}
$permission = has_permission('');
if (is_error($permission)) {
echo $permission->getMessage();
}
is_false
Checks if return is false.
is_null__
Checks if a variable is null.
Works the same as PHP’s native is_null() function.
is_true__
Checks if return is true.
An alternative to using PHP's native mail function with other options for SMTP (default), Qmail, and Sendmail.
<?php
use function Codefy\Framework\Helpers\mail;
use function Codefy\Framework\Helpers\storage_path;
try {
return mail(
to: ['test@example.com' => 'Recipient Name'],
subject: 'Email Message',
message: 'This is a <strong>simple</strong> email message.',
headers: [
'cc' => [
'recipientone@example.com' => 'Recipient One',
'recipienttwo@example.com' => 'Recipient Two'
],
'bcc' => ['another@example.com' => 'Another Recipient'],
],
attachments: [storage_path('file.pdf')]
);
} catch (\PHPMailer\PHPMailer\Exception | Exception $e) {
return $e->getMessage();
}
method_field
This function generates an HTML hidden input field containing the spoofed value of the form's HTTP verb.
now
Create a new Carbon instance for the current datetime.
<?php
use function Qubus\Support\Helpers\now;
$now = now();
// or with timezone
$now = now('America/Los_Angeles');
php_like
SQL Like operator in PHP.
<?php
php_like('%uc%','Lucy'); //true
php_like('%cy', 'Lucy'); //true
php_like('lu%', 'Lucy'); //true
php_like('%lu', 'Lucy'); //false
php_like('cy%', 'Lucy'); //false
php_where
SQL Where operator in PHP.
<?php
// Where dog is in ['cat', 'bear', 'chicken', 'dog']
php_where('dog', 'in', ['cat', 'bear', 'chicken', 'dog']); // true
purify_html
Makes content safe to print on screen.
This function should only be used on output. Except uploading images, never use this function on input. All inputted data should be accepted and then purified on output for optimal results. For output of images, make sure to escape with esc_url().
queue
Helper function to send a job to a queue or dispatch a job.
Send a job to the queue:
<?php
return queue(
queue: new \Application\Service\NewEmailSignup(
request: new \Qubus\Http\ServerRequest()
)
)->createItem();
// returns the last inserted id (ULID)
Dispatch a queued job:
<?php
return queue(queue: $queue)->dispatch();
// returns bool; $queue is the object that is plucked out of the queue
remove_trailing_slash
Removes trailing forward slashes and backslashes if they exist.
site_url
Returns the url of your application.
sort_element_callback
Sorts a structured array by Name property.
strip_tags__
Properly strip all HTML tags including script and style (default).
This differs from PHP’s native strip_tags() function because this function removes the contents of the tags. E.g. strip_tags__( '<script>something</script>' ) will return ''.
<?php
$string = '<b>sample</b> text with <div>tags</div>';
strip_tags__(string: $string); //returns 'text with'
strip_tags__(
string: $string,
removeBreaks: false,
tags: '<b>'
); //returns '<b>sample</b> text with'
strip_tags__(
string: $string,
removeBreaks: false,
tags: '<b>',
invert: true
); //returns 'text with <div>tags</div>'
t__
Translates a string.
throw_if
Throw the given exception if the given condition is true.
<?php
$auth = gate('edit_user') === false;
throw_if($auth, new AuthException('Access denied.'));
// or
throw_if($auth, AuthException::class, 'Access denied');
trim__
Trims all whitespace.
truncate_string
Truncates a string to the given length. It will optionally preserve HTML tags if $isHtml is set to true.
user
Returns the authenticated user.
<?php
use function Codefy\Framework\Helpers\user;
$user = user();
echo $user->user_id; // returns the user's ID
echo $user->email; // returns the user's email