@@ -15,136 +15,279 @@ The MaplePHP DTO library simplifies working with structured data in PHP by wrapp
1515
1616** Note:** MaplePHP DTO also includes polyfill classes for Multibyte String and Iconv support.
1717
18- ---
19-
20- ## Usage
18+ ## ** 1. Creating a DTO Object**
2119
22- The simplest way to work with the library is to start with the ` Traverse ` class, which provides powerful control over your data.
20+ The simplest way to start using ** MaplePHP DTO ** is with the ` Traverse ` class:
2321
2422``` php
2523use MaplePHP\DTO\Traverse;
2624
2725$obj = Traverse::value([
2826 "firstname" => "<em >daniel</em >",
2927 "lastname" => "doe",
30- "slug" => "Lorem ipsum åäö",
3128 "price" => "1999.99",
3229 "date" => "2023-08-21 14:35:12",
3330 "feed" => [
34- "t1" => ["firstname" => "<em >john 1</em >", "lastname" => "doe 1" ],
35- "t2" => ["firstname" => "<em >jane 2</em >", "lastname" => "doe 2" ]
31+ "t1" => ["firstname" => "<em >john 1</em >", "lastname" => "doe-1", 'salary' => 40000 ],
32+ "t2" => ["firstname" => "<em >jane 2</em >", "lastname" => "doe-2", 'salary' => 20000 ]
3633 ]
3734]);
3835```
3936
40- ### Accessing Nested Data
41- Each key in the array is accessible as an object property, and you can continue to drill down into nested arrays, maintaining consistency and safety.
37+ Now, ` $obj ` behaves like an object where you can access its properties directly.
38+
39+ ---
40+
41+ ## ** 2. Accessing Data**
42+
43+ ### ** Direct Property Access**
44+
45+ ``` php
46+ echo $obj->firstname;
47+ // Output: <em >daniel</em >
48+ ```
49+
50+ ### ** Safe Fallback for Missing Values**
4251
4352``` php
44- echo $obj->feed->t1->firstname ;
45- // Output: < em >john 1</ em >
53+ echo $obj->feed->t1->doNotExist->fallback('lorem')->strUcFirst() ;
54+ // Output: Lorem
4655```
4756
48- ### Iterating Through Arrays
57+ ---
58+
59+ ## ** 3. Working with Collections**
60+
61+ ### ** Iterating Over Arrays**
4962
5063``` php
51- foreach($obj->feed->fetch() as $row) {
52- echo $row->firstname;
64+ foreach ($obj->feed->fetch() as $row) {
65+ echo $row->firstname->strStripTags()->strUcFirst() ;
5366}
5467// Output:
55- // <em >john 1</em >
56- // <em >jane 2</em >
68+ // John 1
69+ // Jane 2
70+ ```
71+
72+ ### ** Filtering Data (` filter ` )**
73+
74+ Filters an array based on a callback function.
75+
76+ ``` php
77+ $filtered = $obj->feed->filter(fn($row) => $row->salary->get() > 30000);
78+ echo $filtered->count();
79+ // Output: 1
80+ ```
81+
82+ ### ** Finding Specific Values**
83+
84+ ``` php
85+ echo $obj->shopList->search('cheese');
86+ // Output: 3
87+ ```
88+
89+ ``` php
90+ echo $obj->feed->pluck('lastname')->toArray()[1];
91+ // Output: doe-2
5792```
5893
5994---
6095
61- ## Built-in Data Handlers
96+ ## ** 4. Transforming Collections **
6297
63- MaplePHP DTO comes with powerful handlers for common data transformations. These handlers make it easy to manipulate strings, numbers, URIs, arrays, dates, and more.
98+ ### ** Mapping ( ` map ` ) **
6499
65- ### String Handling Example
100+ Applies a function to each element.
66101
67- You can chain methods for string manipulation:
102+ ``` php
103+ $mapped = $obj->shopList->map(fn($item) => strtoupper($item));
104+ print_r($mapped->toArray());
105+ ```
106+ ** Output:**
107+ ``` php
108+ ['SOAP', 'TOOTHBRUSH', 'MILK', 'CHEESE', 'POTATOES', 'BEEF', 'FISH']
109+ ```
110+
111+ ### ** Reducing (` reduce ` )**
112+
113+ Combines values into a single result.
68114
69115``` php
70- echo $obj->feed->t1->firstname->strStripTags()->strUcFirst();
71- // Equivalent to:
72- // echo $obj->feed->t1->firstname->str()->stripTags()->ucFirst();
73- // Output: John 1
116+ $sum = $obj->feed->reduce(fn($carry, $item) => $carry + $item->salary->get(), 0);
117+ echo $sum;
118+ // Output: 60000
74119```
75120
76- You can also apply transformations when iterating over an array:
121+ ### ** Sorting ( ` reverse ` , ` shuffle ` ) **
77122
78123``` php
79- foreach($obj->feed->fetch() as $row) {
80- echo $row->firstname->strStripTags()->strUcFirst();
81- }
82- // Output:
83- // John 1
84- // Jane 2
124+ echo $obj->shopList->reverse()->eq(0);
125+ // Output: fish
126+ ```
127+
128+ ``` php
129+ echo $obj->shopList->shuffle()->eq(0); // Random Output
130+ ```
131+
132+ ### ** Chunking and Slicing (` chunk ` , ` slice ` , ` splice ` )**
133+
134+ ``` php
135+ echo $obj->shopList->chunk(3)->count();
136+ // Output: 3
137+ ```
138+
139+ ``` php
140+ echo $obj->shopList->slice(1, 2)->count();
141+ // Output: 2
142+ ```
143+
144+ ``` php
145+ $spliced = $obj->shopList->splice(1, 2, ['replaced'])->toArray();
146+ print_r($spliced);
147+ ```
148+ ** Output:**
149+ ``` php
150+ ['soap', 'replaced', 'potatoes', 'beef', 'fish']
151+ ```
152+
153+ ---
154+
155+ ## ** 5. Modifying Collections**
156+
157+ ### ** Adding and Removing Items**
158+
159+ ``` php
160+ echo $obj->shopList->push('barbie')->count();
161+ // Output: 8
162+ ```
163+
164+ ``` php
165+ echo $obj->shopList->pop($value)->count();
166+ echo $value;
167+ // Output: fish
168+ ```
169+
170+ ``` php
171+ echo $obj->shopList->shift($value)->count();
172+ echo $value;
173+ // Output: soap
85174```
86175
87176---
88177
89- ## More Examples
178+ ## ** 6. Advanced Traversal & Recursion**
179+
180+ ### ** Walking Through Nested Structures (` walk ` , ` walkRecursive ` )**
181+
182+ ``` php
183+ $value = "";
184+ $obj->feed->walkRecursive(function ($val) use (& $value) {
185+ $value .= strip_tags(str_replace(" ", "", $val));
186+ });
187+ echo $value;
188+ // Output: john1doe-1400001jane2doe-2200002
189+ ```
190+
191+ ### ** Flattening Data (` flatten ` , ` flattenWithKeys ` )**
192+
193+ ``` php
194+ $flatten = $obj->feed->flatten()->map(fn($row) => $row->strToUpper())->toArray();
195+ ```
196+
197+ ---
90198
91- Here are more examples of using the DTO library’s built-in handlers for different types of data:
199+ ## ** 7. String, Number, and Date Handling **
92200
93- ### String Manipulation
201+ ### ** String Manipulations **
94202
95203``` php
96204echo $obj->firstname->strStripTags()->strUcFirst();
97205// Output: Daniel
98206```
99207
100- ### Number Formatting
208+ ### ** Number Formatting**
101209
102210``` php
103211echo $obj->price->numToFilesize();
104212// Output: 1.95 kb
213+ ```
105214
215+ ``` php
106216echo $obj->price->numRound(2)->numCurrency("SEK", 2);
107217// Output: 1 999,99 kr
108218```
109219
110- ### Date Formatting
220+ ### ** Date Handling **
111221
112222``` php
113223echo $obj->date->clockFormat("y/m/d, H:i");
114224// Output: 23/08/21, 14:35
115225```
116226
117- ---
118-
119- ** Note:** This guide is a work in progress, with more content to be added soon.
227+ ``` php
228+ \MaplePHP\DTO\Format\Clock::setDefaultLanguage('sv_SE');
229+ echo $obj->date->clockFormat('d M');
230+ // Output: 21 augusti
231+ ```
120232
121233---
122234
123- ## How It Works
235+ ## ** 8. Array Utility Methods **
124236
125- The ** MaplePHP DTO ** library operates by wrapping data into objects that allow easy traversal and transformation using a chainable API. This structure allows for consistent and safe data handling, minimizing direct data manipulation risks.
237+ ### ** Merging and Replacing Arrays **
126238
127- Here’s how the key components of the library work:
128-
129- ### 1. ** Traverse Class **
130-
131- At the core of the library is the ` Traverse ` class. This class allows you to wrap an associative array (or any data structure) into an object, making each element of the array accessible as an object property.
132-
133- - ** Key-to-Property Mapping ** : Each key in the array becomes an object property, and its value is transformed into a nested ` Traverse ` object if it's an array.
134- - ** Lazy Loading ** : The values are only accessed when needed, which allows you to traverse large data structures efficiently.
239+ ``` php
240+ $merged = $obj->shopList->merge(['eggs', 'bread']);
241+ print_r($merged->toArray());
242+ ```
243+ ** Output: **
244+ ``` php
245+ ['soap', 'toothbrush', 'milk', 'cheese', 'potatoes', 'beef', 'fish', 'eggs', 'bread']
246+ ```
135247
136- ### 2. ** Handlers for Data Types**
248+ ``` php
249+ $replaced = $obj->shopList->replaceRecursive([0 => 'soap_bar']);
250+ print_r($replaced->toArray());
251+ ```
252+ ** Output:**
253+ ``` php
254+ ['soap_bar', 'toothbrush', 'milk', 'cheese', 'potatoes', 'beef', 'fish']
255+ ```
137256
138- MaplePHP DTO uses specific handlers (such as ` Str ` , ` Num ` , ` DateTime ` , ` Uri ` , etc.) to manage different data types. These handlers provide methods to transform and validate the data.
257+ ### ** Computing Differences ( ` diff ` , ` diffAssoc ` , ` diffKey ` ) **
139258
140- - ** String Handling** : The ` Str ` handler enables string-related operations, such as stripping tags, formatting case, and more.
141- - ** Number Handling** : The ` Num ` handler allows numerical operations like rounding, formatting as currency, and converting to file sizes.
142- - ** Date and Time Handling** : The ` DateTime ` handler provides methods for formatting and manipulating dates and times.
259+ ``` php
260+ $diff = $obj->shopList->diff(['milk', 'cheese']);
261+ print_r($diff->toArray());
262+ ```
263+ ** Output:**
264+ ``` php
265+ ['soap', 'toothbrush', 'potatoes', 'beef', 'fish']
266+ ```
143267
144- ### 3. ** Immutability**
268+ ``` php
269+ $diffAssoc = $obj->shopList->diffAssoc(['soap', 'toothbrush']);
270+ print_r($diffAssoc->toArray());
271+ ```
272+ ** Output:**
273+ ``` php
274+ ['milk', 'cheese', 'potatoes', 'beef', 'fish']
275+ ```
145276
146- When transformations are applied (e.g., ` strUcFirst() ` or ` numRound() ` ), the library ensures immutability by returning a new ` Traverse ` instance with the modified data. This prevents accidental mutations of the original data.
277+ ### ** Extracting Keys ( ` keys ` , ` pluck ` ) **
147278
148- ### 4. ** Fetch Method for Arrays**
279+ ``` php
280+ print_r($obj->shopList->keys()->toArray());
281+ ```
282+ ** Output:**
283+ ``` php
284+ [0, 1, 2, 3, 4, 5, 6]
285+ ```
149286
150- The ` fetch() ` method simplifies working with arrays. Instead of manually looping through the array, you can use ` fetch() ` to iterate over the elements and apply transformations to each one.
287+ ``` php
288+ print_r($obj->feed->pluck('lastname')->toArray());
289+ ```
290+ ** Output:**
291+ ``` php
292+ ['doe-1', 'doe-2']
293+ ```
0 commit comments