DEV Community

Ryan P
Ryan P

Posted on • Edited on

CSV Reader - Filters and Maps

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);
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

In this case, when reading $csv->Address it would return with a formatted string similar to

123 Main St
Anytown, ST  12345
Enter fullscreen mode Exit fullscreen mode

Top comments (0)