2017 © Pedro PelΓ‘ez
 

library php-lodash

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

image

me-io/php-lodash

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

  • Tuesday, May 15, 2018
  • by meabed
  • Repository
  • 7 Watchers
  • 27 Stars
  • 903 Installations
  • PHP
  • 2 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 7 Versions
  • 26 % Grown

The README.md

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. , (*1)


Build Status Code Cov ![Scrutinizer][scrutinizer-badge] ![downloads][downloads-badge] ![MIT License][license-badge] SymfonyInsight, (*2)

All Contributors ![PRs Welcome][prs-badge] ![Code of Conduct][coc-badge] ![Watch on GitHub][github-watch-badge] ![Star on GitHub][github-star-badge] [Tweet][twitter] ![Donate][donate-badge], (*3)

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., (*4)

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., (*5)

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. , (*6)


Installation

Just add me-io/php-lodash to your project composer.json file:, (*7)

{
    "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:, (*8)

composer require me-io/php-lodash

Usage

Arrays

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

Append item to array, (*9)

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

Returns a copy of the array with falsy values removed., (*10)

__::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., (*11)

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

Patches array with list of xpath-value pairs., (*12)

__::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., (*13)

__::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., (*14)

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

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

Split an array into chunks, (*15)

__::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., (*16)

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

__::randomize(array $array)

Shuffle an array ensuring no item remains in the same position., (*17)

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

__::search($array, $value)

Search for the index of a value in an array., (*18)

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

__::average($array, $decimals)

Returns the average value of an array., (*19)

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

__::size($array)

Get the size of an array., (*20)

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

__::contains($array, $value)

Check if an item is in an array., (*21)

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

__::clean(array $array)

Clean all falsy values from an array., (*22)

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

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

Get a random string from an array., (*23)

__::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., (*24)

__::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., (*25)

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

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

Exclude the last X elements from an array, (*26)

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

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

Exclude the first X elements from an array, (*27)

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

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

Sort an array by key., (*28)

__::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, (*29)

Returns new array without preserving keys., (*30)

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

Returns new array with preserving keys., (*31)

__::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, (*32)

__::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., (*33)

$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., (*34)

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

Get item of an array by index, aceepting nested index, (*35)

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

Gets the last element of an array. Passing n returns the last n elements., (*36)

__::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., (*37)

__::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., (*38)

__::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., (*39)

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

Returns an array of values belonging to a given property of each item in a collection., (*40)

$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., (*41)

$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., (*42)

$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., (*43)

__::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., (*44)

__::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., (*45)

__::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., (*46)

__::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., (*47)

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

__::has($collection, $path)

Return true if $collection contains the requested $key., (*48)

__::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., (*49)

__::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., (*50)

__::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., (*51)

__::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., (*52)

__::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., (*53)

__::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., (*54)

__::isEmpty([]);
# true

__::merge($collection1, $collection2)

Recursively combines and merge collections provided with each others., (*55)

__::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., (*56)

__::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., (*57)

__::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., (*58)

__::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., (*59)

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

__::camelCase($input)

Converts string to camel case., (*60)

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

__::capitalize($input)

Converts the first character of string to upper case and the remaining to lower case., (*61)

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

__::kebabCase($input)

Converts string to kebab case., (*62)

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

__::lowerFirst($input)

Converts the first character of string to lower case, like lcfirst., (*63)

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

__::snakeCase($input)

Converts string to snake case., (*64)

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

__::startCase($input)

Converts string to start case., (*65)

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

__::toLower($input)

Converts string, as a whole, to lower case just like strtolower., (*66)

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

__::toUpper($input)

Converts string, as a whole, to lower case just like strtoupper., (*67)

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

__::upperCase($input)

Converts string, as space separated words, to upper case., (*68)

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

__::upperFirst($input)

Converts the first character of string to upper case, like ucfirst., (*69)

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

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

Splits string into an array of its words., (*70)

__::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., (*71)

__::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, (*72)

$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, (*73)

__::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., (*74)

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

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

Check if give value is function or not., (*75)

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

Check if give value is null or not., (*76)

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

Check if give value is number or not., (*77)

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

Check if give value is object or not., (*78)

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

Check if give value is string or not., (*79)

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

Utilities

__::isEmail($string)

Check if the value is valid email., (*80)

__::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., (*81)

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

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

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

Change log

Please see CHANGELOG for more information on what has changed recently., (*83)

Testing

bash $ composer test, (*84)

Contributing

Please feel free to contribute to this project! Pull requests and feature requests welcome! :v:, (*85)

Please see CONTRIBUTING and CODE_OF_CONDUCT for details., (*86)

Contributors

A huge thanks to all of our contributors:, (*87)

|
Mohamed Meabed

πŸ’» ⚠️ πŸ“’ |
Zeeshan Ahmad

πŸ’» πŸ› ⚠️ πŸ“– | | :---: | :---: | , (*88)

License

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

The Versions

15/05 2018

dev-master

9999999-dev

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

  Sources   Download

MIT

The Requires

  • php >=7.0

 

The Development Requires

library utility functions lodash __ bottomline

15/05 2018

1.0.3

1.0.3.0

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

  Sources   Download

MIT

The Requires

  • php >=7.0

 

The Development Requires

library utility functions lodash __ bottomline

09/03 2018

1.0.2

1.0.2.0

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

  Sources   Download

MIT

The Requires

  • php >=7.0

 

The Development Requires

library utility functions lodash __ bottomline

25/02 2018

1.0.1

1.0.1.0

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

  Sources   Download

MIT

The Requires

  • php >=7.0

 

The Development Requires

library utility functions lodash __ bottomline

18/02 2018

1.0.0

1.0.0.0

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

  Sources   Download

MIT

The Requires

  • php >=7.0

 

The Development Requires

library utility functions lodash __ bottomline

18/02 2018

dev-update-1

dev-update-1

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

  Sources   Download

MIT

The Requires

  • php >=7.0

 

The Development Requires

library utility functions lodash __ bottomline

16/02 2018

dev-php7

dev-php7

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

  Sources   Download

MIT

The Requires

  • php >=7.0

 

The Development Requires

library utility functions lodash __ bottomline