me-io/php-lodash

A full-on PHP manipulation utility-belt that provides support for the usual functional.

2.0.0 2019-01-24 12:35 UTC

README

PHP Lodash

php-lodash is a PHP utility library, similar to Underscore/Lodash, that utilizes `namespace`s and dynamic auto loading to improve library performance.

Build Status Code Cov Scrutinizer downloads MIT License SymfonyInsight

All Contributors PRs Welcome Code of Conduct Watch on GitHub Star on GitHub Tweet Donate

Table of Contents

Requirements

This library requires php php_mbstring extension. To enable this extension open your php.ini file and find for the line extension=php_mbstring.dll and uncomment it. If this line is not there then manually add this line in php.ini.

extension=php_mbstring.dll

Introduction

lodash-php is a PHP utility library, similar to Underscore/Lodash, that utilizes namespaces and dynamic auto loading to improve library performance.

Project Structure

  • __.php is the entry point for the lodash-php utility library
  • All lodash-php methods are stored in separate files within their respective namespace folder outlined in /src/__
  • Tests reflect the namespace defined within the library and are processed using phpunit testing
    • To run tests run the following command phpunit
.
├── images                               # Place relevant graphics in this folder
├── src                                  # Core code of the application.
│   ├── __.php                           # Entry point for the library                  
│   └── Traits                           # Contains all lodash-php methods
│       ├── Sequence\Chain.php           # Methods related to chaining
│       ├── Sequence\ChainWrapper.php    # Methods related to chaining
│       ├── Arrays.php                   # Methods related to arrays
│       ├── Collections.php              # Methods related to collections
│       ├── Functions.php                # Methods related to functions
│       ├── Objects.php                  # Methods related to objects
│       ├── Strings.php                  # Methods related to strings
│       └── Utilities.php                # Methods related to utilities
├── tests                                # Tests are placed in that folder.
├── composer.json                        # This file defines the project requirements
├── phpcs.xml.dist                       # Contains the configuration for PHPcs.
├── phpstan.neon.dist                    # Contains the configuration for PHPStan.
├── phpunit.xml.dist                     # Contains the configuration for PHPUnit.
├── LICENSE                              # License file for `lodash-php`
└── README.md                            # Introduces our library to user.

NOTE: lodash-php is not currently in feature parity with Underscore/Lodash. Review the contributing section for more information.

Installation

Just add me-io/php-lodash to your project composer.json file:

{
    "require": {
        "me-io/php-lodash": "^2"
    }
}

and then run composer install. This will install me-io/php-lodash and all it's dependencies. Or run the following command:

composer require me-io/php-lodash

Usage

Arrays

__::append(array $array = [], $value = null)

Append item to array

__::append([1, 2, 3], 4);
# [1, 2, 3, 4]
__::compact(array $array = [])

Returns a copy of the array with falsy values removed.

__::compact([0, 1, false, 2, '', 3]);
# [1, 2, 3]
__::flatten($array, $shallow = false)

Flattens a multidimensional array. If you pass shallow, the array will only be flattened a single level.

__::flatten([1, 2, [3, [4]]], [flatten]);
# [1, 2, 3, 4]
__::patch($arr, $patches, $parent = '')

Patches array with list of xpath-value pairs.

__::patch(['addr' => ['country' => 'US', 'zip' => 12345]], ['/addr/country' => 'CA', '/addr/zip' => 54321]);
# ['addr' => ['country' => 'CA', 'zip' => 54321]]
__::prepend(array $array = [], $value = null)
__::prepend([1, 2, 3], 4);
# [4, 1, 2, 3]
__::range($start = null, $stop = null, $step = 1)

Returns an array of integers from start to stop (exclusive) by step.

__::range(1, 10, 2);
# [1, 3, 5, 7, 9]
__::repeat($object = '', $times = null)

Returns an array of $n length with each index containing the provided value.

__::repeat('foo', 3);
# ['foo', 'foo', 'foo']

__::chunk(array $array, $size = 1, $preserveKeys = false)

Split an array into chunks

__::chunk([1, 2, 3, 4, 5], 3);
# [[1, 2, 3], [4, 5]]

__::drop(array $input, $number = 1)

Creates a slice of array with n elements dropped from the beginning.

__::drop([0, 1, 3], 2);
# [3]

__::randomize(array $array)

Shuffle an array ensuring no item remains in the same position.

__::randomize([1, 2, 3]);
# [2, 3, 1]

__::search($array, $value)

Search for the index of a value in an array.

__::search(['a', 'b', 'c'], 'b');
# 1

__::average($array, $decimals)

Returns the average value of an array.

__::average([1, 2, 3]);
# 2

__::size($array)

Get the size of an array.

__::size([1, 2, 3]);
# 3

__::contains($array, $value)

Check if an item is in an array.

__::contains(['a', 'b', 'c'], 'b');
# true

__::clean(array $array)

Clean all falsy values from an array.

__::clean([true, false, 0, 1, 'string', '']);
# [true, 1, 'string']

__::random(array $array, $take = null)

Get a random string from an array.

__::random([1, 2, 3]);
# Returns 1, 2 or 3

__::intersection(array $a, array $b)

Return an array with all elements found in both input arrays.

__::intersection(["green", "red", "blue"], ["green", "yellow", "red"]);
# ["green", "red"]

__::intersects(array $a, array $b)

Return a boolean flag which indicates whether the two input arrays have any common elements.

__::intersects(["green", "red", "blue"], ["green", "yellow", "red"])
# true

__::initial(array $array, int $to = 1)

Exclude the last X elements from an array

__::initial([1, 2, 3], 1);
# [1, 2]

__::rest(array $array, int $from = 1)

Exclude the first X elements from an array

__::rest([1, 2, 3], 2);
# [3]

__::sortKeys(array $array, string $direction = 'ASC')

Sort an array by key.

__::sortKeys(['z' => 0, 'b' => 1, 'r' => 2]);
# ['b' => 1, 'r' => 2, 'z' => 0]

__::sortKeys(['z' => 0, 'b' => 1, 'r' => 2], 'desc');
# ['z' => 0, 'r' => 2, 'b' => 1]

____::without(array $array, $remove, $preserveKeys = false)

Remove unwanted values from array

Returns new array without preserving keys.

__::without([1, 1 => 3, 2 => 4, 5], 4)
# [0 => 1, 1 => 3, 2 => 5] 

Returns new array with preserving keys.

__::without([1, 3 => 3, 2 => 4, 5], 4, true)
# [0 => 1, 3 => 3, 4 => 5]

Chaining

__::chain($initialValue)

Returns a wrapper instance, allows the value to be passed through multiple php-lodash functions

__::chain([0, 1, 2, 3, null])
    ->compact()
    ->prepend(4)
    ->value();
# [4, 1, 2, 3]

Collections

__::filter($array, callback($n))

Returns the values in the collection that pass the truth test.

$a = [
    ['name' => 'fred',   'age' => 32],
    ['name' => 'maciej', 'age' => 16]
];

__::filter($a, function($n) {
    return $n['age'] > 24;
});
# [['name' => 'fred', 'age' => 32]]
__::first($array, [$n])

Gets the first element of an array. Passing n returns the first n elements.

__::first([1, 2, 3, 4, 5], 2);
# [1, 2]
__::get($array, JSON $string)

Get item of an array by index, aceepting nested index

__::get(['foo' => ['bar' => 'ter']], 'foo.bar');
# 'ter'
__::last($array, [$n])

Gets the last element of an array. Passing n returns the last n elements.

__::last([1, 2, 3, 4, 5], 2);
# [4, 5]
__::map($array, callback($n))

Returns an array of values by mapping each in collection through the iterator.

__::map([1, 2, 3], function($n) {
    return $n * 3;
});
# [3, 6, 9]
__::max($array)

Returns the maximum value from the collection. If passed an iterator, max will return max value returned by the iterator.

__::max([1, 2, 3]);
# 3
__::min($array)

Returns the minimum value from the collection. If passed an iterator, min will return min value returned by the iterator.

__::min([1, 2, 3]);
# 1
__::pluck($array, $property)

Returns an array of values belonging to a given property of each item in a collection.

$a = [
    ['foo' => 'bar',  'bis' => 'ter' ],
    ['foo' => 'bar2', 'bis' => 'ter2'],
];

__::pluck($a, 'foo');
# ['bar', 'bar2']
__::where($array, $parameters[])

Returns a collection of objects matching the given array of parameters.

$a = [
    ['name' => 'fred',   'age' => 32],
    ['name' => 'maciej', 'age' => 16]
];

__::where($a, ['age' => 16]);
# [['name' => 'maciej', 'age' => 16]]

__::assign($collection1, $collection2)

Combines and merge collections provided with each others.

$a = [
    'color' => [
        'favorite' => 'red', 
        5
    ], 
    3
];
$b = [
    10, 
    'color' => [
        'favorite' => 'green', 
        'blue'
    ]
];

__::assign($a, $b);
# ['color' => ['favorite' => 'green', 'blue'], 10]

__::reduceRight($collection, \Closure $iteratee, $accumulator = null)

Reduces $collection to a value which is the $accumulator result of running each element in $collection - from right to left - thru $iteratee, where each successive invocation is supplied the return value of the previous.

__::reduceRight(['a', 'b', 'c'], function ($word, $char) {
    return $word . $char;
}, '');
# 'cba'

__::doForEachRight($collection, \Closure $iteratee)

Iterate over elements of the collection, from right to left, and invokes iterate for each element.

__::doForEachRight([1, 2, 3], function ($value) { print_r($value) });
# (Side effect: print 3, 2, 1)

__::doForEach($collection, \Closure $iteratee)

Iterate over elements of the collection and invokes iterate for each element.

__::doForEach([1, 2, 3], function ($value) { print_r($value) });
# (Side effect: print 1, 2, 3)

__::set($collection, $path, $value = null)

Return a new collection with the item set at index to given value. Index can be a path of nested indexes.

__::set(['foo' => ['bar' => 'ter']], 'foo.baz.ber', 'fer');
# '['foo' => ['bar' => 'ter', 'baz' => ['ber' => 'fer']]]'

__::hasKeys($collection, $path, $value = null)

Returns if $input contains all requested $keys. If $strict is true it also checks if $input exclusively contains the given $keys.

__::hasKeys(['foo' => 'bar', 'foz' => 'baz'], ['foo', 'foz']);
# true

__::has($collection, $path)

Return true if $collection contains the requested $key.

__::has(['foo' => ['bar' => 'num'], 'foz' => 'baz'], 'foo.bar');
# true

__::hasKeys((object) ['foo' => 'bar', 'foz' => 'baz'], 'bar');
# false

__::concat($collection1, $collection2)

Combines and concat collections provided with each others.

__::concat(['color' => ['favorite' => 'red', 5], 3], [10, 'color' => ['favorite' => 'green', 'blue']]);
# ['color' => ['favorite' => ['green'], 5, 'blue'], 3, 10]

__::concatDeep($collection1, $collection2)

Recursively combines and concat collections provided with each others.

__::concatDeep(['color' => ['favorite' => 'red', 5], 3], [10, 'color' => ['favorite' => 'green', 'blue']]);
# ['color' => ['favorite' => ['red', 'green'], 5, 'blue'], 3, 10]

__::ease(array $collection, $glue = '.')

Flattens a complex collection by mapping each ending leafs value to a key consisting of all previous indexes.

__::ease(['foo' => ['bar' => 'ter'], 'baz' => ['b', 'z']]);
# '['foo.bar' => 'ter', 'baz.0' => 'b', , 'baz.1' => 'z']'

__::every($collection, \Closure $iteratee)

Checks if predicate returns truthy for all elements of collection.

__::every([1, 3, 4], function ($v) { return is_int($v); });
// → true

__::groupBy(array $array, $key)

Returns an associative array where the keys are values of $key.

__::groupBy([
        ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
        ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
        ['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen'],
    ],
    'state'
);
# [
#   'IN' => [
#       ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
#       ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
#   ],
#   'CA' => [
#       ['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen']
#    ]
# ]

__::groupBy([
        ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
        ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
        ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
    ],
    function ($value) {
        return $value->city;
    }
);
# [
#   'Indianapolis' => [
#     ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
#     ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
#   ],
#   'San Diego' => [
#     ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
#   ]
# ]

__::isEmpty($value)

Check if value is an empty array or object.

__::isEmpty([]);
# true

__::merge($collection1, $collection2)

Recursively combines and merge collections provided with each others.

__::merge(['color' => ['favorite' => 'red', 'model' => 3, 5], 3], [10, 'color' => ['favorite' => 'green', 'blue']]);
# ['color' => ['favorite' => 'green', 'model' => 3, 'blue'], 10]

__::pick($collection = [], array $paths = [], $default = null)

Returns an array having only keys present in the given path list.

__::pick(['a' => 1, 'b' => ['c' => 3, 'd' => 4]], ['a', 'b.d']);
# ['a' => 1, 'b' => ['d' => 4]]

__::reduce($collection, \Closure $iteratee, $accumulator = null)

Reduces $collection to a value which is the $accumulator result of running each element in $collection thru $iteratee, where each successive invocation is supplied the return value of the previous.

__::reduce([1, 2], function ($sum, $number) {
    return $sum + $number;
}, 0);
# 3

$a = [
    ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'School bus'],
    ['state' => 'IN', 'city' => 'Indianapolis', 'object' => 'Manhole'],
    ['state' => 'IN', 'city' => 'Plainfield', 'object' => 'Basketball'],
    ['state' => 'CA', 'city' => 'San Diego', 'object' => 'Light bulb'],
    ['state' => 'CA', 'city' => 'Mountain View', 'object' => 'Space pen'],
];
$iteratee = function ($accumulator, $value) {
    if (isset($accumulator[$value['city']]))
        $accumulator[$value['city']]++;
    else
        $accumulator[$value['city']] = 1;
    return $accumulator;
};
__::reduce($c, $iteratee, []);
# [
#    'Indianapolis' => 2,
#    'Plainfield' => 1,
#    'San Diego' => 1,
#    'Mountain View' => 1,
# ]

$object = new \stdClass();
$object->a = 1;
$object->b = 2;
$object->c = 1;
__::reduce($object, function ($result, $value, $key) {
    if (!isset($result[$value]))
        $result[$value] = [];
    $result[$value][] = $key;
    return $result;
}, [])
# [
#     '1' => ['a', 'c'],
#     '2' => ['b']
# ]

__::unease(array $collection, $separator = '.')

Builds a multidimensional collection out of a hash map using the key as indicator where to put the value.

__::unease(['foo.bar' => 'ter', 'baz.0' => 'b', , 'baz.1' => 'z']);
# '['foo' => ['bar' => 'ter'], 'baz' => ['b', 'z']]'

Strings

__::split($input, $delimiter, $limit = PHP_INT_MAX)

Split a string by string.

__::split('a-b-c', '-', 2);
# ['a', 'b-c']

__::camelCase($input)

Converts string to camel case.

__::camelCase('Foo Bar');
# 'fooBar'

__::capitalize($input)

Converts the first character of string to upper case and the remaining to lower case.

__::capitalize('FRED');
# 'Fred'

__::kebabCase($input)

Converts string to kebab case.

__::kebabCase('Foo Bar');
# 'foo-bar'

__::lowerFirst($input)

Converts the first character of string to lower case, like lcfirst.

__::lowerFirst('Fred');
# 'fred'

__::snakeCase($input)

Converts string to snake case.

__::snakeCase('Foo Bar');
# 'foo_bar'

__::startCase($input)

Converts string to start case.

__::startCase('--foo-bar--');
# 'Foo Bar'

__::toLower($input)

Converts string, as a whole, to lower case just like strtolower.

__::toLower('fooBar');
# 'foobar'

__::toUpper($input)

Converts string, as a whole, to lower case just like strtoupper.

__::toUpper('fooBar');
# 'FOOBAR'

__::upperCase($input)

Converts string, as space separated words, to upper case.

__::upperCase('--foo-bar');
# 'FOO BAR'

__::upperFirst($input)

Converts the first character of string to upper case, like ucfirst.

__::upperFirst('fred');
# 'Fred'

__::words($input, $pattern = null)

Splits string into an array of its words.

__::words('fred, barney, & pebbles');
# ['fred', 'barney', 'pebbles']

__::words('fred, barney, & pebbles', '/[^, ]+/');
# ['fred', 'barney', '&', 'pebbles']

__::lowerCase($input)

Converts string, as space separated words, to lower case.

__::lowerCase('--Foo-Bar--');
# 'foo bar'

Functions

__::slug($string, [array $options])
__::slug('Jakieś zdanie z dużą ilością obcych znaków!');
# 'jakies-zdanie-z-duza-iloscia-obcych-znakow'

$options = [
    'delimiter' => '-',
    'limit' => 30,
    'lowercase' => true,
    'replacements' => array(),
    'transliterate' => true
]

__::slug('Something you don\'t know about know about Jackson', $options);
# 'something-you-dont-know-about'
__::truncate($string, [$limit=40])

Truncate string based on count of words

$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque et mi orci.';
__::truncate($string);
# 'Lorem ipsum dolor sit amet, consectetur...'

__::truncate($string, 60);
# 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pel...'
__::urlify($string)

Find the urls inside a string a put them inside anchor tags

__::urlify('I love https://google.com');
# 'I love <a href="https://google.com">google.com</a>'

Objects

__::isArray($array)

Check if give value is array or not.

__::isArray([1, 2, 3]);
# true

__::isArray(123);
# false
__::isFunction($string)

Check if give value is function or not.

__::isFunction(function ($a) { return $a + 2; });
# true
__::isNull($null)

Check if give value is null or not.

__::isNull(null);
# true
__::isNumber($int|$float)

Check if give value is number or not.

__::isNumber(123);
# true
__::isObject($object)

Check if give value is object or not.

__::isObject('fred');
# false
__::isString($string)

Check if give value is string or not.

__::isString('fred');
# true

Utilities

__::isEmail($string)

Check if the value is valid email.

__::isEmail('test@test.com');
# true

__::isEmail('test_test.com');
# false
__::now()

Wrapper of the time() function that returns the current offset in seconds since the Unix Epoch.

__::now();
# 1417546029
__::stringContains($needle, $haystack, [$offset])

Wrapper of the time() function that returns the current offset in seconds since the Unix Epoch.

__::stringContains('waffle', 'wafflecone');
# true

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please feel free to contribute to this project! Pull requests and feature requests welcome! ✌️

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Contributors

A huge thanks to all of our contributors:

License

The MIT License (MIT). Please see License File for more information.