Completed
Push — develop ( b91125...52c290 )
by Seth
03:00
created

Calendar::load()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 8
nc 2
nop 1
1
<?php
2
3
namespace smtech\CanvasICSSync\SyncIntoCanvas;
4
5
class Calendar
6
{
7
    /**
8
     * Canvas calendar context
9
     * @var CalendarContext
10
     */
11
    protected $context;
12
13
    /**
14
     * ICS or webcal feed URL
15
     * @var string
16
     */
17
    protected $feedUrl;
18
19
    /**
20
     * Name of this calendar (extracted from feed)
21
     * @var string
22
     */
23
    protected $name;
24
25
    /**
26
     * Filter for events in this calendar
27
     * @var Filter
28
     */
29
    protected $filter;
30
31
    /**
32
     * Construct a Calendar object
33
     *
34
     * @param string $canvasUrl URL of a Canvas calendar context
35
     * @param string $feedUrl URL of a webcal or ICS calendar feed
36
     * @param boolean $enableFilter (Optional, default `false`)
37
     * @param string $include (Optional) Regular expression to select events
38
     *     for inclusion in the calendar sync
39
     * @param string $exclude (Optional) Regular expression to select events
40
     *     for exclusion from the calendar sync
41
     */
42
    public function __construct($canvasUrl, $feedUrl, $enableFilter = false, $include = null, $exclude = null)
43
    {
44
        $this->setContext(new CalendarContext($canvasUrl));
45
        $this->setFeed($feedUrl);
0 ignored issues
show
Bug introduced by
The method setFeed() does not exist on smtech\CanvasICSSync\SyncIntoCanvas\Calendar. Did you maybe mean setFeedUrl()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
46
        $this->setFilter(new Filter(
47
            $enableFilter,
48
            $include,
49
            $exclude
50
        ));
51
    }
52
53
    /**
54
     * Set the Canvas calendar context
55
     *
56
     * @param CalendarContext $context
57
     * @throws Exception If `$context` is null
58
     */
59
    public function setContext(CalendarContext $context)
60
    {
61
        if (!empty($context)) {
62
            $this->context = $context;
63
        } else {
64
            throw new Exception(
65
                'Context cannot be null'
66
            );
67
        }
68
    }
69
70
    /**
71
     * Get the Canvas calendar context
72
     *
73
     * @return CalendarContext
74
     */
75
    public function getContext()
76
    {
77
        return $this->context;
78
    }
79
80
    /**
81
     * Set the webcal or ICS feed URl for this calendar
82
     *
83
     * @param string $feedUrl
84
     * @throws Exception If `$feedUrl` is not a valid URL
85
     */
86
    public function setFeedUrl($feedUrl)
87
    {
88
        if (!empty($feedUrl)) {
89
            /* crude test to see if the feed is a valid URL */
90
            $handle = fopen($feedUrl, 'r');
91
            if ($handle !== false) {
92
                $this->feedUrl = $feedUrl;
93
            }
94
        }
95
        throw new Exception(
96
            'Feed must be a valid URL'
97
        );
98
    }
99
100
    /**
101
     * Get the feed URL for this calendar
102
     *
103
     * @return string
104
     */
105
    public function getFeedUrl()
106
    {
107
        return $this->feedUrl;
108
    }
109
110
    /**
111
     * Set the name of the calendar
112
     *
113
     * @param string $name
114
     */
115
    public function setName($name)
116
    {
117
        $this->name = (string) $name;
118
    }
119
120
    /**
121
     * Get the name of the calendar
122
     *
123
     * @return string
124
     */
125
    public function getName()
126
    {
127
        return $this->name;
128
    }
129
130
    /**
131
     * Set the regular expression filter for this calendar
132
     *
133
     * @param Filter $filter
134
     */
135
    public function setFilter(Filter $filter)
136
    {
137
        $this->filter = $filter;
138
    }
139
140
    /**
141
     * Get the regular expression filter for this calendar
142
     *
143
     * @return Filter
144
     */
145
    public function getFilter()
146
    {
147
        return $this->filter;
148
    }
149
150
    /**
151
     * Generate a unique ID to identify this particular pairing of ICS feed and
152
     * Canvas calendar
153
     **/
154
    protected function getPairingHash()
155
    {
156
        global $metadata;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
157
        return md5($this->getContext() . $this->getFeedUrl());
158
    }
159
160
    public function save()
161
    {
162
        $sql = static::getMySql();
0 ignored issues
show
Bug introduced by
The method getMySql() does not seem to exist on object<smtech\CanvasICSS...yncIntoCanvas\Calendar>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
163
164
        $params = [
165
            'id' => $sql->escape_string($this->getPairingHash()),
166
            'name' => $sql->escape_string($this->getName()),
167
            'canvas_url' => $sql->escape_string($this->getContext()->getCanonicalUrl()),
168
            'ics_url' => $sql->escape_string($this->getFeedUrl()),
169
            'enable_regex_filter' => $this->getFilter()->isEnabled(),
170
            'include_regexp' => $sql->escape_string($this->getFilter()->getIncludeExpression()),
171
            'exclude_regexp' => $sql->escape_string($this->getFilter()->getExcludeExpression())
172
        ];
173
        foreach ($params as $field => $value) {
174
            if (empty($value)) {
175
                $params[$field] = 'NULL';
176
            } else {
177
                $params[$field] = "'$value'";
178
            }
179
        }
180
        $response = static::getMySql()->query("
0 ignored issues
show
Bug introduced by
The method getMySql() does not seem to exist on object<smtech\CanvasICSS...yncIntoCanvas\Calendar>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
181
            SELECT * FROM `calendars` WHERE `id` = '$_id'
0 ignored issues
show
Bug introduced by
The variable $_id does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
182
        ");
183
        $previous = $response->fetch_assoc();
184
        if ($previous) {
185
            $query = "UPDATE `calendars` SET\n";
186
            foreach ($params as $field => $value) {
187
                if ($key != 'id') {
0 ignored issues
show
Bug introduced by
The variable $key does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
188
                    $query .= "`$field` = $value\n";
189
                }
190
            }
191
            $query .= "WHERE `id` = '{$params['id']}'";
192
        } else {
193
            $query = "INSERT INTO `calendars` (\n`";
194
            $query .= implode('`, `', array_keys($params));
195
            $query .= "`) VALUES (";
196
            $query .= implode(', ', $params);
197
            $query .= ')';
198
        }
199
        if (static::getMySql($query)->query() === false) {
0 ignored issues
show
Bug introduced by
The method getMySql() does not seem to exist on object<smtech\CanvasICSS...yncIntoCanvas\Calendar>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
200
            throw new Exception(
201
                "Failed to store calendar ID {$this->id} to database"
0 ignored issues
show
Bug introduced by
The property id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
202
            );
203
        }
204
    }
205
206
    /**
207
     * Load a Calendar from the MySQL database
208
     *
209
     * @param int $id
210
     * @return Calendar
211
     */
212
    public static function load($id)
213
    {
214
        $sql = static::getMySql();
0 ignored issues
show
Bug introduced by
The method getMySql() does not seem to exist on object<smtech\CanvasICSS...yncIntoCanvas\Calendar>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
215
        $query = "SELECT * FROM `calendars` WHERE `id` = '" . $sql->escape_string($id) . "'";
216
        $response = $sql->query($query);
217
        if ($response) {
218
            $calendar = $response->fetch_assoc();
219
            return new Calendar($calendar['canvas_url'], $calendar['ics_url'], $calendar['enable_regex_filter'], $calendar['include_regexp'], $calendar['exclude_regexp']);
220
        }
221
        return null;
222
    }
223
}
224