Skip to content

Instantly share code, notes, and snippets.

@maxchehab
Last active September 14, 2017 04:47
Show Gist options
  • Save maxchehab/84d06743453639c523e45732077225d7 to your computer and use it in GitHub Desktop.
Save maxchehab/84d06743453639c523e45732077225d7 to your computer and use it in GitHub Desktop.
Shopify backend intern test. Hosted: http://104.236.141.69/shopify/shopify.php
<?php
$data = get_data();
$response = array();
$response["invalid_customers"] = validate($data["validations"], $data["customers"]);
echo json_encode($response);
function validate($rules, $entries){
$errors = array();
foreach($entries as $entry){
while ($rule = current($rules)) {
//required fields
if($rule[key($rule)]["required"] && gettype($entry[key($rule)]) == "NULL"){
add_error($entry, $errors, key($rule));
}
//type
if(array_key_exists("type", $rule[key($rule)])){
switch ($rule[key($rule)]["type"]) {
case "number":
if(gettype($entry[key($rule)]) != "integer" && gettype($entry[key($rule)]) != "double"){
add_error($entry, $errors, key($rule));
}
break;
case "boolean":
if(gettype($entry[key($rule)]) != "boolean"){
add_error($entry, $errors, key($rule));
}
break;
case "string":
if(gettype($entry[key($rule)]) != "string"){
add_error($entry, $errors, key($rule));
}
break;
}
}
//length
if(array_key_exists("length", $rule[key($rule)])){
if(array_key_exists("min", $rule[key($rule)]["length"]) && strlen($entry[key($rule)]) < $rule[key($rule)]["length"]["min"]){
add_error($entry, $errors, key($rule));
}
if(array_key_exists("max", $rule[key($rule)]["length"]) && strlen($entry[key($rule)]) > $rule[key($rule)]["length"]["max"]){
add_error($entry, $errors, key($rule));
}
}
next($rules);
}
reset($rules);
}
return $errors;
}
function add_error($entry, &$errors, $reason){
foreach($errors as &$e){
if($e["id"] == $entry["id"]){
if(!in_array($reason, $e["invalid_fields"])){
array_push($e["invalid_fields"], $reason);
}
return;
}
}
$error = array();
$error["id"] = $entry["id"];
$error["invalid_fields"] = array($reason);
array_push($errors, $error);
}
function get_data($data = array(), $page = 1){
$json = file_get_contents("https://backend-challenge-winter-2017.herokuapp.com/customers.json?page=" . $page);
$json = json_decode($json, true);
if(count($data) == 0){
$data["validations"] = $json["validations"];
$data["customers"] = $json["customers"];
}else{
$data["customers"] = array_merge($data["customers"], $json["customers"]);
}
if(end($data["customers"])["id"] == $json["pagination"]["total"]){
return $data;
}else{
return get_data($data, $page + 1);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment