You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
'city' => new Callback(fn (array $data) => $this->extractCity($data['Addresses'][0][2])),
232
+
'postcode' => new Regex(new Copy('Addresses->0->2'), '[.*\b(\d{5})]', 1),
240
233
'country' => 'US',
241
234
];
242
235
}
@@ -245,19 +238,12 @@ class BarBucketAddressToAddresesMapping extends Mapping
245
238
{
246
239
return explode(',', $line, 2)[0];
247
240
}
248
-
249
-
private function extractZipCode($line)
250
-
{
251
-
if (preg_match('[.*\b(\d{5})]', $line, $matches)) {
252
-
return $matches[1];
253
-
}
254
-
}
255
241
}
256
242
```
257
243
258
244
*Line1* can be copied straight from the input data and *country* can be hard-coded with a constant value because we assume it does not change.
259
245
260
-
City and postcode must be extracted from the last line of the address. For this we use `Callback`strategies that indirectly point to private methods of our mapping. Callbacks are only necessary because there are currently no included strategies to perform string splitting or regular expression matching.
246
+
City and postcode must be extracted from the last line of the address. For _city_, we use the `Callback`strategy that points to a private method of our mapping. A callback is necessary because there are currently no included strategies to perform string splitting. For _postcode_, we can use the [`Regex`](#regex) strategy.
261
247
262
248
The anonymous function wrapper picks the relevant part of the input data to pass to our methods. The weakness of this solution is dereferencing non-existent values will cause PHP to generate *undefined index* notices whereas injecting `Copy` strategies would gracefully resolve to `null` if any part of the path does not exist. Therefore, the most elegant solution would be to create custom strategies to promote code reuse and avoid errors, but is beyond the scope of this demonstration. For more information see [writing strategies](#writing-strategies).
263
249
@@ -302,6 +288,7 @@ The following strategies ship with Mapper and provide a suite of commonly used f
302
288
-[IfExists](#ifexists)– Delegates to one expression or another depending on whether the specified condition maps to null.
303
289
-[Join](#join)– Joins sub-string expressions together with a glue string.
304
290
-[Merge](#merge)– Merges two data sets together giving precedence to the latter if keys collide.
291
+
-[Regex](#regex)– Captures a portion of a string using regular expression matching.
305
292
-[Replace](#replace)– Replaces one or more substrings.
306
293
-[TakeFirst](#takefirst)– Takes the first value from a collection one or more times.
307
294
-[ToList](#tolist)– Converts data to a single-element list unless it is already a list.
0 commit comments