krzystof / a-bunch-of-macros

:skull: :skull: :skull: [Abandonned] A bunch of useful macros for Laravel's Macroable's components

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A Bunch Of Macros

This is just a list of Laravel's macro found here and there. Feel free to add yours!

Laravel's macroable classes are:

Collection

Count Recursive

Collection::macro('countRecursive', function () {
    return count($this->items, COUNT_RECURSIVE);
});

by krzystof

Pipe (added in core, see PR)

Apply any given function to the collection

Collection::macro('pipe', function ($callback) {
    return $callback($this);
});

Source adamwathan's book

toAssoc

Given a collection of pairs, turn it into a key => value collection

Collection::macro('toAssoc', function () {
    return $this->reduce(function ($items, $pair) {
        list($key, $value) = $pair;
        return $items->put($key, $value);
    }, new static);
});

Source: adamwathan

Transpose

Collection::macro('transpose', function () {
    $items = array_map(function (...$items) {
        return $items;
    }, ...$this->values());

    return new static($items);
});

Source: adamwathan

Filesystem

Is Writable By All

Check if a file or directory is writable by all users

Filesystem::macro('isWritableByAll', function ($filepath) {
    return file_exists($path) && substr(sprintf('%o', fileperms($path)), -1) === '7';
});

by krzystof

Make Writable By All

Change permissions on a file or directory to be writable by all users

Filesystem::macro('makeWritableByAll', function ($filepath) {
    return chmod($path, 0777);
});

by krzystof

Request

Filter only

Get only the parameters of the request if they are not empty

Request::macro('filterOnly', function (...$attributes) {
    return array_filter($this->only($attributes));
});

echo $request->title;
// ''
echo $request->content;
// 'something'

$request->only('title', 'content');
// ['title' => '', content' => 'something']

$request->filterOnly('title', 'content');
// ['content' => 'something']

by krzystof

About

:skull: :skull: :skull: [Abandonned] A bunch of useful macros for Laravel's Macroable's components

License:MIT License