NewsItem kan direct gedeserialiseerd worden vanuit API JSON

This commit is contained in:
2017-06-07 01:17:43 +02:00
parent ad7e82e01d
commit 3f726e884d
2 changed files with 20 additions and 7 deletions

View File

@@ -4,10 +4,24 @@ namespace Model;
class Model { class Model {
protected function ConvertToDateTime(&$field) { protected function ConvertToDateTime(&$field) {
if($field) { if($field) {
$field = new \DateTime($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 === 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; $field = null;
} else {
// If valid, return local timezone
$field->setTimezone(new \DateTimeZone("Europe/Amsterdam"));
} }
} }
} }

View File

@@ -19,9 +19,8 @@ class NewsImage extends Model {
public $url; public $url;
public $title; public $title;
public function __construct($data, $urlPrefix = '/') { public function getUrl() {
parent::__construct($data); return '/img/news/' . $this->url;
if($this->url) { $this->url = $urlPrefix . $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->source = $data->source ? new \Model\NewsSource($data->source, $data->source_url, $data->showsource) : null;
$this->keywords = trim($data->keywords) ? explode(' ', $data->keywords) : null; $this->keywords = trim($data->keywords) ? explode(' ', $data->keywords) : null;
$this->podcast = $data->podcast ? $data->podcast : null; $this->podcast = $data->podcast ? $data->podcast : null;
if($images) { if($images = $images ?? $data->images) {
$this->images = []; $this->images = [];
foreach($images as $image) { foreach($images as $image) {
$this->images[] = new NewsImage($image, '/img/news/'); $this->images[] = new NewsImage($image, '/img/news/');