Created
July 24, 2018 07:15
-
-
Save rbg246/a3ec384f6fc82586f82c83a01056995e to your computer and use it in GitHub Desktop.
Abstract Transformer class for PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Class TransformerAbstract | |
* contains functions for validating fields | |
* | |
* @package Drupal\streamtime | |
*/ | |
abstract class TransformerAbstract { | |
/** | |
* map input property names with transformed output keys | |
* @var array | |
*/ | |
protected $property_map = []; | |
/** | |
* input to transform class | |
* @var array | |
*/ | |
protected $input = []; | |
/** | |
* fields that are required | |
* @var array | |
*/ | |
protected $requiredFields = []; | |
/** | |
* validates $input against a required set of fields | |
* | |
* @return array|bool | |
*/ | |
public function validate() { | |
$valid = true; | |
foreach($this->requiredFields as $field) { | |
$sub_fields = explode('.', $field); | |
$inner_array = false; | |
foreach($sub_fields as $sub_field) { | |
if ($inner_array !== false) { | |
$valid = isset($inner_array[$sub_field]); | |
$inner_array = ($valid === true) ? $inner_array[$sub_field] : $inner_array; | |
} else { | |
$valid = isset($this->input[$sub_field]); | |
$inner_array = ($valid === true) ? $this->input[$sub_field] : false; | |
} | |
if ($valid !== true) { | |
$message = sprintf('The required field %s was not found', $field); | |
$valid = [ | |
'error' => true, | |
'message' => $message | |
]; | |
break; | |
} | |
} | |
} | |
return $valid; | |
} | |
/** | |
* gets a value of a field | |
* @param $property | |
* | |
* @return mixed | |
*/ | |
public function getValue($property) { | |
$fields = explode('.', $property); | |
$object = $this->input; | |
foreach ($fields as $field) { | |
$object = $object[$field]; | |
} | |
return $object; | |
} | |
/** | |
* creates the transformed output | |
* @return array | |
*/ | |
public function output () { | |
$output = []; | |
foreach ($this->input as $property => $value) { | |
if (in_array($property, $this->requiredFields)) { | |
$value = $this->getValue($property); | |
$field_name = $this->getFieldName($property); | |
$output[$field_name] = $value; | |
} | |
} | |
return $output; | |
} | |
public function getFieldName($property) { | |
return (isset($this->property_map[$property])) ? $this->property_map[$property] : $property; | |
} | |
/** | |
* TransformerAbstract constructor. | |
* | |
* @param $input | |
*/ | |
public function __construct($input) { | |
$this->input = $input; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment