Skip to content

php-lodash is a PHP utility library, similar to Underscore/Lodash.

License

Notifications You must be signed in to change notification settings

me-io/php-lodash

Repository files navigation

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 item to array

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

Returns a copy of the array with falsy values removed.

__::compact([0, 1, false, 2, '', 3]);
# [1, 2, 3]

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]

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([1, 2, 3], 4);
# [4, 1, 2, 3]

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

__::range(1, 10, 2);
# [1, 3, 5, 7, 9]

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

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

Split an array into chunks

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

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

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

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

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

Search for the index of a value in an array.

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

Returns the average value of an array.

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

Get the size of an array.

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

Check if an item is in an array.

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

Clean all falsy values from an array.

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

Get a random string from an array.

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

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

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

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

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

Exclude the last X elements from an array

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

Exclude the first X elements from an array

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

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]

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

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

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]]

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

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

Get item of an array by index, aceepting nested index

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

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

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

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]

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

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

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']

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]]

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]

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'

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)

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)

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']]]'

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

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

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]

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]

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']'

Checks if predicate returns truthy for all elements of collection.

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

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'],
#   ]
# ]

Check if value is an empty array or object.

__::isEmpty([]);
# true

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]

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]]

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']
# ]

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 a string by string.

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

Converts string to camel case.

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

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

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

Converts string to kebab case.

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

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

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

Converts string to snake case.

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

Converts string to start case.

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

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

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

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

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

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

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

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

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

Splits string into an array of its words.

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

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

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

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

Functions

__::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 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...'

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

Check if give value is array or not.

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

__::isArray(123);
# false

Check if give value is function or not.

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

Check if give value is null or not.

__::isNull(null);
# true

Check if give value is number or not.

__::isNumber(123);
# true

Check if give value is object or not.

__::isObject('fred');
# false

Check if give value is string or not.

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

Utilities

Check if the value is valid email.

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

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

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

__::now();
# 1417546029

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:


Mohamed Meabed

💻 ⚠️ 📢

Zeeshan Ahmad

💻 🐛 ⚠️ 📖

License

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

About

php-lodash is a PHP utility library, similar to Underscore/Lodash.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages