Intro
In my previous post, CSV Reader, I discussed the CSV Reader I created. In this post, I want to explain how the Filters
and Maps
work within the object.
Filters
Filters are a way that you filter content before ingesting it. After creating your object you have to add the filter.
$filter = new Filter(‘Phone’, [Customer:class, ‘sanitizePhone’]);
$csv->addFilter($filter);
The first parameter is the field that triggers the call. So in this case, when retrieving the Phone with $csv->Phone
, it will call Customer::sanitizePhone()
. It will automatically pass in the value from the file to that method. So then you will need to create the method for it to call.
/**
* Method to sanitize the phone number from a CSV file
* @param string $val
* @return string
*/
public static function sanitizePhone(string $val): string
{
return preg_replace("/[^0-9\+]/", ‘’, $val);
}
Maps
Maps are another really powerful feature. Maps allow you to combine multiple fields and concatenate them together into one formatted string. One easy example is an address or a name.
$map = new Map(‘Address’, “%0\n%1, %2 %3”, [‘add’, ‘city’, ‘state’, ‘zip’]);
$csv->addMap($map);
In this case, when reading $csv->Address
it would return with a formatted string similar to
123 Main St
Anytown, ST 12345
Top comments (0)