PHP code example of ps / fluent-traversable

1. Go to this page and download the library: Download ps/fluent-traversable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ps / fluent-traversable example snippets



    $patients = array(...);
    
    $info = FluentTraversable::from($patients)
        ->groupBy(get::value('bloodType'))
        ->map(
            FluentComposer::forArray()
                ->partition(is::eq('sex', 'female'))
                ->map(func::unary('count'))
                ->collect(function($elements){
                    list($femalesCount, $malesCount) = $elements;
                    return $femalesCount / ($femalesCount + $malesCount) * 100;
                })
        )
        ->toMap();


    $books = array(/* some books */);
    
    $emails = array();
    
    foreach($books as $book) {
        if($book->getReleaseDate() < 2007) {
            $authors = $book->getAuthors();
            foreach($authors as $author) {
                if($author->getSex() == 'male' && $author->getEmail()) {
                    $emails[] = $author->getEmail();
                }
            }
        }
    }


    //some imports
    use FluentTraversable\FluentTraversable;
    use FluentTraversable\Semantics\is;
    use FluentTraversable\Semantics\get;

    $books = array(/* some books */);
    
    $emails = FluentTraversable::from($books)
        ->filter(is::lt('releaseDate', 2007))
        ->flatMap(get::value('authors'))
        ->filter(is::eq('sex', 'male'))
        ->map(get::value('email'))
        ->filter(is::notNull())
        ->toArray();       



    function($object){
        return $object->getAuthors();
    }


>     FluentTraversable::from(array('a' => 'A', 'b' => 'B'))
>         ->map(function($value, $index){
>             return $value.$index;
>         })
>         ->toMap();
>         //result will be: array('a' => 'Aa', 'b' => 'Bb')
> 

>     FluentTraversable::from(array('some', 'values'))
>         ->flatMap(func::unary('str_split'))
>         ->toArray();
>         //result will be: array('s', 'o', 'm', 'e', 'v', 'a', 'l', 'u', 'e')
> 


    FluentTraversable::from(array())
        ->filter(...)//intermediate operation, so I can chain
        ->map(...)//intermediate operation, so I can chain
        ->size()//terminate operation, I cannot chain - it returns integer



    FluentTraversable::from($books)
        ->firstMatch(is::eq('author.name', 'Stephen King'))
        //there is Option instance, you can transform value (thanks to map) if this value exists
        ->map(function($book){
            return 'Found book: '.$book->getTitle();
        })
        //provide default value if book wasn't found
        ->orElse(Option::fromValue('Not found any book...'))
        //print result to stdout thanks to Option::map method
        ->map('printf')
        //or you can call "->get()" and assign to variable, it is safe because you provided default value by "orElse"
        ;



    FluentTraversable::from($books)
        ->maxBy(get::value('rating'))
        ->map(function(Book $book){
            $this->takeToBackpack($book);
        });


> Option::fromValue($patientId)
>   ->map([$patientRepo,'find'])
>   //there could be `Some(null)` value! 
>   ->map(get::value('doctor.phone'))
>   //there could be also `Some(null)` value, so `null` might be passed to `$this::callToDoctor`
>   ->each([$this,'callToDoctor']);
> 

> Option::fromArrayValue($patientId)
>   ->flatMap(get::option([$patientRepo,'find']))
>   //when `$this::callToDoctor` return `null` there will be `None`
>   ->flatMap(get::option('doctor.phone'))
>   //when doctor has not phone set, there will be `None` value
>   ->each([$this,'callToDoctor']);
> 


    $maxEvenPrinter = FluentComposer::forArray();

    //very important is, to not chain directly from `forArray()` method, first you should assign created object
    //to variable, and then using reference to object you can compose your function

    $maxEvenPrinter
        ->filter(function($number){
            //only even numbers
            return $number % 2 === 0;
        })
        ->max()
        //"max" (as same as firstMatch) returns Option, because there is possibility given array is empty
        ->map(function($value){
            return 'max even number: '.$value;
        })
        ->orElse(Option::fromValue('max even number not found'))
        ->map('printf');



    $maxEvenPrinter(array(1, 3, 5, 2, 4));
    //output will be: "max even number: 4"
    
    $maxEvenPrinter(array(1, 3, 5));
    //output will be: "max even number not found"



        $func = FluentComposer::forArray();
        $func-> /* some chaining methods */;
            
        $func(array('value1', 'value2', 'value3'));

    

    
        $func = FluentComposer::forVarargs();
        $func-> /* some chaining methods */;
        
        $func('value1', 'value2', 'value3');
    
    

    
        $func = FluentComposer::forValue();
        $func-> /* some chaining methods */;
    
        $func('value1', 'this value will be ignored')
    
    


    $patients = array(...);
    
    $info = FluentTraversable::from($patients)
        ->groupBy(get::value('bloodType'))
        //we have multi-dimensional array, where key is bloodType, value is array of patients
        ->map(
            //we map array of patients for each blood type to percentage value, so lets compose a function
            FluentComposer::forArray()
                //split array of patients into two arrays, first females, second males
                ->partition(is::eq('sex', 'female'))
                //map those arrays to its size, so we have number of females and males
                ->map(func::unary('count'))
                //calculate a percent
                ->collect(function($elements){
                    list($femalesCount, $malesCount) = $elements;
                    return $femalesCount / ($femalesCount + $malesCount) * 100;
                })
        )
        //get our result with index preserving 
        ->toMap();

>
>   ->map(
>       $f = FluentComposer::forArray(), $f
>            ->firstMatch(is::eq('name', 'Stefan'))
>            ->getOrElse('Not found')
>   )
>
> 

    
    $doctors = array(/* some doctors */);

    $doctors = FluentTraversable::from($doctors)
        ->filter(
            FluentComposer::forValue()
                ->flatMap(get::value('patients'))
                ->allMatch(is::eq('sex', 'female'))
        )
        ->toArray();


    
        $gt25 = is::gt(25);    
        $gt25(26);//evaluates to true
    
    

    
        $ageGt25 = is::gt('age', 25);
        $gt25(array('age', 26));//evaluates to true
    
    

    
        $true = is::true();    
        $true(true);//evaluates to true
    
    

    
        $true = is::true('awesome');    
        $true(array('awesome' => true));//evaluates to true
    
    


    $alwaysFalse = is::allTrue(false, is::eq(25));
    $alwaysTrue = is::anyTrue(true, is::eq(25));


> 
>     $doctors = array(...);
>     
>     $doctors = FluentTraversable::from($doctors)
>         ->filter(is::lt(size::of('patients'), 5))
>         ->toArray();
> 
> 


    $book = ...;
    $puppet = Puppet::record()->getPublisher()->getName();
    
    echo $puppet($book);//$book->getPublisher()->getName() will be invoked