CSV Reader - Filters and Maps

godsgood33

Ryan P

Posted on October 28, 2022

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
💖 💪 🙅 🚩
godsgood33
Ryan P

Posted on October 28, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

CSV Reader - Filters and Maps
programming CSV Reader - Filters and Maps

October 28, 2022