scratch – Blame information for rev 87

Subversion Repositories:
Rev:
Rev Author Line No. Line
87 office 1 # fusonic/linq
2  
3 [![Build Status](https://travis-ci.org/fusonic/linq.png)](https://travis-ci.org/fusonic/linq)
4 [![Total Downloads](https://poser.pugx.org/fusonic/linq/downloads.png)](https://packagist.org/packages/fusonic/linq)
5  
6 fusonic/linq is a lightweight PHP library inspired by the LINQ 2 Objects extension methods in .NET.
7  
8 For a full introduction read my blog-post: http://www.fusonic.net/en/blog/2013/08/14/fusonic-linq-write-less-do-more/
9  
10 LINQ queries offer three main advantages over traditional foreach loops:
11  
12 * They are more concise and readable, especially when filtering multiple conditions.
13  
14 * They provide powerful filtering, ordering, and grouping capabilities with a minimum of application code.
15  
16 * In general, the more complex the operation you want to perform on the data, the more benefit you will realize by using LINQ instead of traditional iteration techniques.
17  
18 ## Requirements
19  
20 fusonic/linq is supported on PHP 5.3 and up.
21  
22  
23 ## Installation & Usage
24  
25 The most flexible installation method is using Composer: Simply create a composer.json file in the root of your project:
26 ``` json
27 {
28 "require": {
29 "fusonic/linq": "@dev"
30 }
31 }
32 ```
33  
34 Install composer and run install command:
35 ``` bash
36 curl -s http://getcomposer.org/installer | php
37 php composer.phar install
38 ```
39  
40 Once installed, include vendor/autoload.php in your script to autoload fusonic/linq.
41  
42 ``` php
43 require 'vendor/autoload.php';
44 use Fusonic\Linq\Linq;
45  
46 Linq::from(array())->count();
47 ```
48  
49 ## Examples
50  
51 ### Calculate the average file size of files in a directory:
52 ``` php
53 $source = glob("files/*");
54 Linq::from($source)
55 ->select(function($i) { return filesize($i); })
56 ->average();
57 ```
58  
59 ### Find all files bigger than 1024 bytes and return the fileinfo object:
60 ``` php
61 $source = glob("files/*");
62 Linq::from($source)
63 ->where(function($i) { return filesize($i) > 1024; })
64 ->select(function($i) { return pathinfo($i); });
65 ```
66  
67 ### Search for all users containing "Max 1", Skip 5 items, Take 2 items and select the property ID of each user:
68 ```php
69 $result = Linq::from($users)
70 ->where(function (User $u) { return strstr($u->surname, "Max 1"); })
71 ->skip(5)
72 ->take(2)
73 ->select(function (User $u) { return $u->usrId; });
74 ```
75  
76 ### Flatten multiple sequences into one sequence:
77 ```php
78 $array1 = array("key" => "a", "data" => array("a1", "a2"));
79 $array2 = array("key" => "b", "data" => array("b1", "b2"));
80 $array3 = array("key" => "c", "data" => array("c1", "c2"));
81  
82 $allArrays = array($array1, $array2, $array3);
83  
84 $result = Linq::from($allArrays)
85 ->selectMany(function($x) { return $x["data"]; })
86 ->toArray();
87  
88 // $result is now: array("a1", "a2", "b1", "b2", "c1", "c2");
89  
90 ```
91 ### Map sequence to array with key/value selectors:
92 ```php
93 $category1 = new stdClass(); $category1->key = 1; $category1->value = "Cars";
94 $category2 = new stdClass(); $category2->key = 2; $category2->value = "Ships";
95  
96 $result = Linq::from(array($category1, $category2))
97 ->toArray(
98 function($x) { return $x->key; }, // key-selector
99 function($x) { return $x->value; } // value-selector
100 );
101  
102 // $result is now: array(1 => "Cars", 2 => "Ships");
103 ```
104  
105 ### The aggregate method makes it simple to perform a calculation over a sequence of values:
106 ```php
107 $numbers = Linq::from(array(1,2,3,4));
108 $sum = $numbers->aggregate(function($a, $b) { return $a + $b; });
109 // echo $sum; // output: 10 (1+2+3+4)
110  
111 $chars = Linq::from(array("a", "b", "c"));
112 $csv = $chars->aggregate(function($a, $b) { return $a . "," . $b; });
113 // echo $csv; // output: "a,b,c"
114  
115 $chars = Linq::from(array("a", "b", "c"));
116 $csv = $chars->aggregate(function($a, $b) { return $a . "," . $b; }, "seed");
117 // echo $csv; // output: "seed,a,b,c"
118  
119 ```
120  
121  
122 ### The chunk method makes it simple to split a sequence into chunks of a given size:
123 ```php
124 $chunks = Linq::from(array("a","b","c","d","e"))->chunk(2);
125 $i = 0;
126 foreach($chunk in $chunks) {
127 $i++;
128 echo "Row $i <br>";
129 foreach($char in $chunk) {
130 echo $char . "|";
131 }
132 }
133 // Result:
134 // Row 1
135 // a|b
136 // Row 2
137 // c|d
138 // Row 3
139 // e|
140  
141 ```
142  
143 ## List of methods provided by fusonic/linq:
144  
145 ```php
146 aggregate($func, $seed = null) // Applies an accumulator function over a sequence.
147 all($func) // Determines wheter all elements satisfy a condition.
148 any($func) // Determines wheter any element satisfies a condition.
149 average($func = null) // Computes the average of all numeric values.
150 concat($second) // Concatenates 2 sequences
151 contains($value) // Determines whether a sequence contains a specified element.
152 count() // Counts the elements of the sequence.
153 chunk($chunksize) // Splits the sequence in chunks according to $chunksize.
154 except($second) // Returns all items except the ones of the given sequence.
155 distinct($func = null) // Returns all distinct items of a sequence using the optional selector.
156 each($func) // Performs the specified action on each element of the sequence.
157 elementAt($index) // Returns the element at a specified index or throws an exception.
158 elementAtOrNull($index) // Returns the element at a specified index or returns null
159 first($func = null) // Returns the first element that satisfies a specified condition or throws an exception.
160 firstOrNull($func = null) // Returns the first element, or NULL if the sequence contains no elements.
161 groupBy($keySelector) // Groups the object according to the $keySelector generated key.
162 intersect($second) // Intersects the Linq sequence with second Iterable sequence.
163 last($func = null) // Returns the last element that satisfies a specified condition or throws an exception.
164 lastOrNull($func = null) // Returns the last element that satisfies a condition or NULL if no such element is found.
165 max($func = null) // Returns the maximum item value according to $func.
166 min($func = null) // Returns the minimum item value according to $func
167 orderBy($func) // Sorts the elements in ascending order according to a key provided by $func.
168 orderByDescending($func) // Sorts the elements in descending order according to a key provided by $func.
169 select($func) // Projects each element into a new form by invoking the selector function.
170 selectMany($func) // Projects each element of a sequence to a new Linq and flattens the resulting sequences into one sequence.
171 single($func = null) // Returns the only element that satisfies a specified condition or throws an exception.
172 singleOrDefault($func = null) // Returns the only element that satisfies a specified condition or returns Null.
173 skip($count) // Bypasses a specified number of elements and then returns the remaining elements.
174 sum($func = null) // Gets the sum of all items or by invoking a transform function on each item to get a numeric value.
175 take($count) // Returns a specified number of contiguous elements from the start of a sequence.
176 toArray($keySelector=null, $valueSelector=null) // Creates an Array from this Linq object with an optional key selector.
177 where($func) // Filters the Linq object according to func return result.
178 ```
179  
180 ## Simple, Consistent and Predictable
181  
182 One important design goal was the principle of the least surprise. As PHP is a fully dynamic language with nearly no type-safety, it is common to shoot yourself into the foot because of accidentally mixing up incompatible types.
183  
184 We protect you from these programing errors by asserting that every callback functions you supply to the library must return a correctly typed value. In addition, every supported aggregate function will throw an exception if you are accidentally mixing up incompatible types.
185  
186 This means that we made this library totally predictable in what it does, and verified that every function has its defined exceptions which are thrown when certain operations fail, or if certain types are not correct.
187  
188 ```php
189 /* Throws an UnexpectedValueException if the
190 provided callback function does not return a boolean */
191 Linq::from(array("1", "1"))
192 ->where(function($x) { return "NOT A BOOLEAN"; });
193  
194 /* Throws an UnexpectedValueException if one of the values
195 is not convertible to a numeric value:*/
196 Linq::from(array(1, 2, "Not a numeric value"))
197 ->sum();
198 ```
199  
200 ## Running tests
201  
202 You can run the test suite with the following command:
203  
204 ```bash
205 phpunit --bootstrap tests/bootstrap.php .
206 ```
207