lstrojny / functional-php

Primitives for functional programming in PHP
MIT License
1.98k stars 204 forks source link

Add path, path_or, prop, prop_or, props functions #187

Open win0err opened 5 years ago

win0err commented 5 years ago

I'm happy to introduce the amazing set of functions: path, path_or, prop, prop_or, props.

Example:

<?php

use function Functional\map;
use function Functional\path_or;
use function Functional\prop;
use function Functional\prop_or;
use function Functional\props;
use function Functional\each;

include 'vendor/autoload.php';

$users = [
    ['first_name' => 'John', 'last_name' => 'Doe', 'birth' => 1969, 'languages' => ['js' => 5, 'php' => 10], 'os' => 'Ubuntu'],
    ['first_name' => 'Valerich', 'birth' => 1980],
    (object)['first_name' => 'John', 'last_name' => 'Appleseed', 'birth' => 1985, 'languages' => ['swift' => 15], 'os' => 'macOS'],
    ['first_name' => 'Taylor', 'last_name' => 'Otwell', 'birth' => 1986, 'languages' => ['php' => 12]],
];
$currentYear = (int) date('Y');

$developers = map(
    $users,
    function ($item) use ($currentYear) {
        return [
            'full_name' => implode(' ', props(['first_name', 'last_name'], $item)),
            'php_experience' => path_or(0, ['languages', 'php'], $item),
            'os' => prop_or('Fedora', 'os', $item),
            'age' => $currentYear - prop('birth', $item),
        ];
    }
);

each(
    $developers,
    function ($developer) {
        printf(
            "%s (%d y.o.), enjoys PHP for %d years\n",
            ...props(['full_name', 'age', 'php_experience'], $developer)
        );
    }
);

Result:

John Doe (50 y.o.), enjoys PHP for 10 years
Valerich (39 y.o.), enjoys PHP for 0 years
John Appleseed (34 y.o.), enjoys PHP for 0 years
Taylor Otwell (33 y.o.), enjoys PHP for 12 years
lstrojny commented 5 years ago

Thank you for the well done PR! Did you look into pick and pluck to compare what use cases aren’t supported?

win0err commented 5 years ago

Of course, I did! pick — almost same as prop_or, but works only with arrays, but prop, prop_or, props also works with objects (that's why it's called props). pluck — can be represented with the following code: map($list, fn($item) => prop($key, $item))

P.S. If you have any questions — feel free to ask.