From 3f726e884d25b130f4d36632fdb5f0c7da636201 Mon Sep 17 00:00:00 2001 From: Mischa Spelt Date: Wed, 7 Jun 2017 01:17:43 +0200 Subject: [PATCH] NewsItem kan direct gedeserialiseerd worden vanuit API JSON --- common/classes/Model.php | 18 ++++++++++++++++-- common/classes/NewsItem.php | 9 ++++----- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/common/classes/Model.php b/common/classes/Model.php index 5a68ebb..9fd8936 100644 --- a/common/classes/Model.php +++ b/common/classes/Model.php @@ -4,10 +4,24 @@ namespace Model; class Model { protected function ConvertToDateTime(&$field) { - if($field) { - $field = new \DateTime($field); + if($field) { + // PHP7 JSON-encodes to {date: "", "timezone_type": ..., "timezone": "UTC" } + // In that case $field will be an object + if(is_object($field)) { + $field = ($field->timezone) + ? new \DateTime($field->date, new \DateTimeZone($field->timezone)) + : (new \DateTime($field->date)); + } else { + // If $field is not an object, assume it's a plain, valid, string + $field = new \DateTime($field); + } + if($field === false || $field->getTimestamp() == 0) { + // If field had data but is invalid DateTime or is 0000-00-00 00:00, set it to null. $field = null; + } else { + // If valid, return local timezone + $field->setTimezone(new \DateTimeZone("Europe/Amsterdam")); } } } diff --git a/common/classes/NewsItem.php b/common/classes/NewsItem.php index 4bfdebf..9061acb 100644 --- a/common/classes/NewsItem.php +++ b/common/classes/NewsItem.php @@ -19,9 +19,8 @@ class NewsImage extends Model { public $url; public $title; - public function __construct($data, $urlPrefix = '/') { - parent::__construct($data); - if($this->url) { $this->url = $urlPrefix . $this->url; } + public function getUrl() { + return '/img/news/' . $this->url; } } @@ -52,8 +51,8 @@ class NewsItem extends Model { $this->source = $data->source ? new \Model\NewsSource($data->source, $data->source_url, $data->showsource) : null; $this->keywords = trim($data->keywords) ? explode(' ', $data->keywords) : null; $this->podcast = $data->podcast ? $data->podcast : null; - - if($images) { + + if($images = $images ?? $data->images) { $this->images = []; foreach($images as $image) { $this->images[] = new NewsImage($image, '/img/news/');