Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
artyomich committed Aug 26, 2019
1 parent f97545a commit 6b1533c
Show file tree
Hide file tree
Showing 2 changed files with 160 additions and 126 deletions.
50 changes: 26 additions & 24 deletions api/comments.xml
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<posts last_id="3" last_session_id="Гриша" last_update_timestamp="1532645879">
<post>
<id>1</id>
<name>Вася</name>
<message>FSAFdsf</message>
<parent_id>0</parent_id>
<time>1532645879</time>
</post>
<post>
<id>2</id>
<name>Петя</name>
<message>цуауцауц</message>
<parent_id>0</parent_id>
<time>1532645879</time>
</post>
<post>
<id>3</id>
<name>Гриша</name>
<message>фафыафыва</message>
<parent_id>1</parent_id>
<time>1542645879</time>
</post>
</posts>
<?xml version="1.0" encoding="UTF-8"?>
<root>
<posts last_id="3" last_session_id="afsdf" last_update_timestamp="1566816024">
<post>
<id>1</id>
<name>John</name>
<message>John's comment</message>
<parent_id>0</parent_id>
<time>1532645879</time>
</post>
<post>
<id>2</id>
<name>Petya</name>
<message>Petya's comment</message>
<parent_id>0</parent_id>
<time>1532645879</time>
</post>
<post>
<id>3</id>
<name>Grisha</name>
<message>Grisha's comment</message>
<parent_id>1</parent_id>
<time>1542645879</time>
</post>
</posts>
</root>
236 changes: 134 additions & 102 deletions api/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,170 +6,202 @@
$_POST = isset($_POST['name']) ? : json_decode(file_get_contents("php://input"), true);
// Simple CORS
header("Access-Control-Allow-Origin: *");

// Set default timezone Moscow
date_default_timezone_set('Europe/Moscow');


/**************************************
* XML load using SimpleXML *
**************************************/
$fileXML = 'comments.xml';


if (file_exists($fileXML)) {
$posts = simplexml_load_file($fileXML);
$xmlRoot = simplexml_load_file($fileXML);
} else {
$err = "Can't load file " . $fileXML;
json_response(['error' => $err], 500);
jsonResponse(['error' => $err], 500);
exit($err);
}

/**************************************
* Handle Post comment *
**************************************/
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

//10 sec limit between actions
$lastSessionId = (string)$posts['last_session_id'];
$lastUpdateTimestamp = (int)$posts['last_update_timestamp'];
//Get posts attributes last_session_id, last_update_timestamp, last_id for update after manipulation
foreach ($xmlRoot->children() as $posts) {
foreach($posts->attributes() as $key => $value) {
if ($key == 'last_session_id') {
$lastSessionId = $value;
} elseif ($key == 'last_update_timestamp') {
$lastUpdateTimestamp = (int) $value;
} elseif ($key == 'last_id') {
$lastId = (int) $value;
} else {
$err = 'In XML attritute structure unresolved element with key: ' . $key . ', and value: ' . $value;
jsonResponse(['error' => $err], 500);
exit($err . now());
}
}
break;
}

//All attributes are required
if (!isset($lastId) && !isset($lastUpdateTimestamp) && !isset($lastSessionId)) {
$err = "Can't find required attributes in XML: " . $fileXML;
jsonResponse(['error' => $err], 500);
exit($err);
}
$currentSessionId = @$_POST['name'];

/* if (($lastSessionId == @$_POST['name']) && (now() - $lastUpdateTimestamp < 10)) {
//10 sec limit between actions
if (($lastSessionId == $currentSessionId) && (time() - $lastUpdateTimestamp < 10)) {
//error 429 - Too Many Request
$err = '10 sec limit between user\'s comments! ';
json_response(['error' => $err], 422);
jsonResponse(['error' => $err], 429);
exit($err . now());
}*/
}

// Inputs
$name = @$_POST['name'];
$comment = @$_POST['message'];
// Inputs
$name = @$_POST['name'];
$comment = @$_POST['message'];
//$parentId = @$_POST['parent_id'];
$parentId = 0;

// Validate the input
if (strlen($name) < 3) {
json_response(['error' => 'Name is required!'], 422);
}

if (strlen($comment) < 5) {
json_response(['error' => 'Comment is required!'], 422);
}

$data = [
'id' => (int)$posts['last_id'] + 1,
$time = time();

// Validate the input
if (strlen($name) < 3) {
jsonResponse(['error' => 'Name is required!'], 422);
}
if (strlen($comment) < 5) {
jsonResponse(['error' => 'Comment is required!'], 422);
}
$data = [
'id' => $lastId + 1,
'name' => $name,
'message' => $comment,
'parent_id' => $parentId
];

save_comment($data + ['time' => time(), 'lastSessionId' => $lastSessionId], $posts, $fileXML);

json_response(transform($data + ['time' => time()]), 201);
saveComment($data + ['time' => $time, 'lastSessionId' => $currentSessionId], $xmlRoot, $fileXML);
jsonResponse(transform($data + ['time' => time()]), 201);
}

/**************************************
* Return list of Comments *
**************************************/

// Read xml and print the results:
foreach ($posts->children() as $post) {
$comments[] = time_elapsed_string((int)$post->time);
foreach ($xmlRoot->children() as $posts) {
foreach ($posts->children() as $post) {
$comments[] = $post;
}
}

$comments = array_map('transform', $comments);
//$comments = array_map('transform', $comments);

// Transform result
json_response($comments);


jsonResponse($comments);
/************************************** Helper functions *************************************/

/*
* Save a comment in xml
*
*
* @param $data
* @param $posts
* @param $file
* @return boolean
*/
function save_comment($data, $posts, $file)
function saveComment($data, $xmlRoot, $file)
{
// Prepare statement
$options = $posts->addChild('options');
$options->addAttribute('last_id', strip_tags($data['id']));
$options->addAttribute('last_session_id', strip_tags($data['lastSessionId']));
$options->addAttribute('last_update_timestamp', strip_tags(strip_tags($data['time'])));

$post = $posts->addChild('post');
$post->addChild('id', strip_tags($data['id']));
$post->addChild('name', strip_tags($data['name']));
$post->addChild('message', strip_tags($data['message']));
$post->addChild('parent_id', strip_tags($data['parent_id']));
$post->addChild('time', strip_tags($data['time']));
// Prepare data
foreach ($xmlRoot->children() as $posts) {
$posts->attributes()->last_id = strip_tags($data['id']);
$posts->attributes()->last_session_id = strip_tags($data['lastSessionId']);
$posts->attributes()->last_update_timestamp = (int)$data['time'];

$post = $posts->addChild('post');
$post->addChild('id', strip_tags($data['id']));
$post->addChild('name', strip_tags($data['name']));
$post->addChild('message', strip_tags($data['message']));
$post->addChild('parent_id', strip_tags($data['parent_id']));
$post->addChild('time', strip_tags($data['time']));
}
// Bind and execute
return $xmlRoot->asXML($file);
}

/*
* Update a comment in xml
*
* @param $data
* @param $posts
* @param $file
* @return boolean
*/
function updateComment($data, $xmlRoot, $file)
{
// Prepare data
foreach ($xmlRoot->children() as $posts) {
$posts->attributes()->last_id = strip_tags($data['id']);
$posts->attributes()->last_session_id = strip_tags($data['lastSessionId']);
$posts->attributes()->last_update_timestamp = (int)$data['time'];

$post = $posts->addChild('post');
$post->addChild('id', strip_tags($data['id']));
$post->addChild('name', strip_tags($data['name']));
$post->addChild('message', strip_tags($data['message']));
$post->addChild('parent_id', strip_tags($data['parent_id']));
$post->addChild('time', strip_tags($data['time']));
}
// Bind and execute
return $posts->asXML($file);
return $xmlRoot->asXML($file);
}

/**
* Die a valid json response
*
*
* @param $data
* @param int $status_code
*/
function json_response($data, $status_code = 200)
function jsonResponse($data, $status_code = 200)
{
http_response_code($status_code);
header('Content-Type: application/json');
global $posts;
$posts = null;
die(json_encode($data));
http_response_code($status_code);
header('Content-Type: application/json');
global $xmlRoot;
$xmlRoot = null;
die(json_encode($data));
}


/*
* Transform record from db
*
*
* @param $comm
* @return array
*/
function transform($comm)
{
return [
'id' => (int)$comm['id'],
return [
'id' => (int)$comm['id'],
'parent_id' => (int)$comm['parent_id'],
'name' => $comm['name'],
'message' => $comm['message'],
'time' => time_elapsed_string((int)$comm['time']),
];
'name' => $comm['name'],
'message' => $comm['message'],
'time' => time_elapsed_string((int)$comm['time']),
];
}

function time_elapsed_string($datetime, $full = false)
{
$now = new DateTime;
$ago = new DateTime('@' . $datetime);
$diff = $now->diff($ago);

$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;

$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}

if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
$now = new DateTime;
$ago = new DateTime('@' . $datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}

0 comments on commit 6b1533c

Please sign in to comment.