summaryrefslogtreecommitdiff
path: root/providers/Provider.php
blob: baec21543820d2a6903e6ca75490c6e29751f2b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php

namespace Providers;

abstract class Provider {

    protected $_options = [];
    protected $_feed = NULL;
    protected $_cacheTimeout = '15 minutes';
    protected $_cacheTime;

    public function __construct($feed, $options=[]) {
        $this->_feed = $feed;
        $this->_options = $options;
    }

    abstract protected function _getCachePath();

    protected function _getCache($path) {
        return file_get_contents($path);
    }

    abstract protected function _fetchItems();

    abstract protected function _spamFilter($items);

    abstract protected function _mapItems($content);

    abstract protected function _sortContent($content);

    protected function _getItems() {
        $cacheFile = sprintf($this->_getCachePath(), $this->_feed);
        $this->_cacheTime = file_exists($cacheFile) ? filemtime($cacheFile) : PHP_INT_MIN;
        if ($this->_cacheTime > strtotime('-' . $this->_cacheTimeout)) {
            return unserialize($this->_getCache($cacheFile));
        } else {
            $content = $this->_fetchItems();
            if (empty($content) && file_exists($cacheFile)) {
                return unserialize($this->_getCache($cacheFile));
            }
            file_put_contents($cacheFile, serialize($content));
            $this->_cacheTime = time();
            return $content;
        }
    }

    private function _filterEmoji($items) {
        $dictionary = json_decode(file_get_contents('../config/emoji.json'), TRUE);
        $filtered = [];
        foreach ($items as $item) {
            foreach (['Title', 'Text'] as $field) {
                $item->{$field} = strtr($item->{$field}, $dictionary);
            }
        }
        return $items;
    }

    protected function _filterItemContent($items) {
        $items = $this->_filterEmoji($items);

        if (array_key_exists('title', $this->_options)) {
            $keyword = strtolower($this->_options['title']);
            $items = array_filter($items, function($item) use($keyword) {
                return str_contains(strtolower($item->Title), $keyword);
            });
        }

        return $items;
    }

    public function get() {
        $items = $this->_getItems();
        if (isset($this->_options['spamfilter'])) {
            $items = $this->_spamFilter($items);
        }
        return $this->_sortContent(
            $this->_filterItemContent(
                $this->_mapItems($items)
            )
        );
    }

    public function cacheTime() {
        return $this->_cacheTime;
    }

    abstract public function title();

}

?>