Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Importing data into WordPress using the strategy pattern
<?php
class CSVCustomerDataConverter implements CustomerDataConverterInterface
{
/**
* Convert the given CSV data array into an array of customers. The returned
* array should use the following format:
*
* @param array $data
*
* @return array
*/
public function convert(array $data)
{
$customers = array();
foreach ($data as $row) {
$row = str_getcsv($row);
$customers[] = array(
'name' => $row[0],
'email' => $row[1],
'details' => $row[2],
);
}
return $customers;
}
}
<?php
interface CustomerDataConverterInterface
{
/**
* Convert the given data array into an array of customers. The returned
* array should use the following format:
*
* array(
* array(
* 'name' => (string) Name of the customer.
* 'email' => (string) Email address of the customer.
* 'details' => (string) The customer details.
* )
* )
*
* @param array $data
*
* @return array
*/
public function convert(array $data);
}
<?php
class CustomerImporter
{
/**
* The customer data converter used by the importer.
*
* @var CustomerDataConverterInterface
*/
private $converter;
/**
* Constructor.
*
* @param CustomerDataConverterInterface $converter
*/
public function __construct(CustomerDataConverterInterface $converter)
{
$this->converter = $converter;
}
/**
* Import a customer data file.
*
* @param string $filename
*
* @return bool|WP_Error
*/
public function import_from_file($filename)
{
if (!is_readable($filename)) {
return new WP_Error('file_unreadable', sprintf('Unable to read "%" customer data file.', $filename));
}
$customer_data = file($filename, FILE_IGNORE_NEW_LINES);
if (!is_array($customer_data)) {
return new WP_Error('parse_error', sprintf('Failed to parse the "%" customer data file.', $filename));
}
$customers = $this->converter->convert($customer_data);
foreach ($customers as $customer) {
$this->add_customer($customer['name'], $customer['email'], $customer['details']);
}
return true;
}
/**
* Add a new customer into the WordPress database.
*
* @param string $name
* @param string $email
* @param string $details
*
* @return int|WP_Error
*/
private function add_customer($name, $email, $details = '')
{
$customer_id = wp_insert_post(array(
'post_title' => $name,
'post_content' => $details,
'post_status' => 'publish',
'post_type' => 'customer'
), true);
if ($customer_id instanceof WP_Error) {
return $customer_id;
}
update_post_meta($customer_id, 'email', $email);
return $customer_id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.