Completed
Push — master ( 71feda...776f21 )
by claudio
06:53
created

Sync::syncToTimeSlots()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 13.7937

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 29
ccs 5
cts 17
cp 0.2941
rs 8.439
cc 5
eloc 17
nc 5
nop 0
crap 13.7937
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Claudio Cardinale <[email protected]>
5
 * Date: 03/12/15
6
 * Time: 2.33
7
 * This program is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU General Public License
9
 * as published by the Free Software Foundation; either version 2
10
 * of the License, or (at your option) any later version.
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
 */
19
20
namespace plunner\Console\Commands\SyncCaldav;
21
22
use it\thecsea\caldav_client_adapter\EventInterface;
23
use it\thecsea\caldav_client_adapter\simple_caldav_client\SimpleCaldavAdapter;
24
use plunner\Caldav;
25
use plunner\Events\Caldav\ErrorEvent;
26
use plunner\Events\Caldav\OkEvent;
27
28
/**
29
 * Class Sync
30
 * @package plunner\Console\Commands
31
 * @author Claudio Cardinale <[email protected]>
32
 * @copyright 2015 Claudio Cardinale
33
 * @version 1.0.0
34
 */
35
class Sync
36
{
37
    /**
38
     * @var Caldav
39
     */
40
    private $calendar;
41
42
    /**
43
     * Sync constructor.
44
     * @param Caldav $calendar
45
     */
46 4
    public function __construct(Caldav $calendar)
47 2
    {
48 4
        $this->calendar = $calendar;
49 4
    }
50
51
    /**
52
     * @return Caldav
53
     */
54 2
    public function getCalendar()
55 2
    {
56
        return $this->calendar;
57
    }
58
59
    /**
60
     * perform the sync
61
     */
62 4
    public function sync()
63
    {
64 4
        $this->syncToTimeSlots();
65 4
    }
66
67
    /**
68
     *
69
     */
70 4
    private function syncToTimeSlots()
71
    {
72
        try {
73 4
            $events = $this->getEvents();
74 4
        } catch (\it\thecsea\caldav_client_adapter\CaldavException $e) {
75 4
            \Event::fire(new ErrorEvent($this->calendar, $e->getMessage()));
76 4
            return;
77
        } catch (\Illuminate\Contracts\Encryption\DecryptException $e) {
78
            \Event::fire(new ErrorEvent($this->calendar, $e->getMessage()));
79
            return;
80
        }
81
82
        /**
83
         * @var $calendarMain \plunner\Calendar
84
         */
85
        $calendarMain = $this->calendar->Calendar;
86
87
        //remove old timeslots
88
        $calendarMain->timeslots()->delete();
89
90
        //insert new timeslots
91
        foreach ($events as $event) {
92
            if (!($event = $this->parseEvent($event)))
93
                \Event::fire(new ErrorEvent($this->calendar, 'problem during the parsing an event'));
94
            else
95
                $calendarMain->timeslots()->create($event);
96
        }
97
        \Event::fire(new OkEvent($this->calendar));
98
    }
99
100
    /**
101
     * @return array|\it\thecsea\caldav_client_adapter\EventInterface[]
102
     * @throws \it\thecsea\caldav_client_adapter\CaldavException
103
     * @thorws \Illuminate\Contracts\Encryption\DecryptException
104
     */
105 4
    private function getEvents()
106
    {
107
        //TODO catch php errors like array key
108 4
        $caldavClient = new SimpleCaldavAdapter();
109 4
        $caldavClient->connect($this->calendar->url, $this->calendar->username, \Crypt::decrypt($this->calendar->password));
110
        $calendars = $caldavClient->findCalendars();
111
        $caldavClient->setCalendar($calendars[$this->calendar->calendar_name]);//TODO error if the calendar name is wrong
112
        /**
113
         * 26 hours before to avoid tiemezone problems and dst problems
114
         * 30 days after
115
         */
116
        return $caldavClient->getEvents(date('Ymd\THis\Z', time() - 93600), date('Ymd\THis\Z', time() + 2592000));
117
    }
118
119
    /**
120
     * @param EventInterface $event
121
     * @return \DateTime[]|null
122
     */
123
    private function parseEvent(EventInterface $event)
124
    {
125
        $pattern = "/^((DTSTART;)|(DTEND;))(.*)\$/m";
126
        if (preg_match_all($pattern, $event->getData(), $matches)) {
127
            if (!isset($matches[4]) || count($matches[4]) != 2)
128
                return null;
129
            $ret = [];
130
            if ($tmp = $this->parseDate($matches[4][0]))
131
                $ret['time_start'] = $tmp;
132
            else
133
                return null;
134
            if ($tmp = $this->parseDate($matches[4][1]))
135
                $ret['time_end'] = $tmp;
136
            else
137
                return null;
138
            return $ret;
139
        }
140
        return null;
141
    }
142
143
    /**
144
     * @param String $date
145
     * @return \DateTime|null|false
146
     */
147
    private function parseDate($date)
148
    {
149
        $pattern = "/^((TZID=)|(VALUE=))(.*):(.*)\$/m";
150
        if (preg_match_all($pattern, $date, $matches)) {
151
            if ($matches[1][0] == 'TZID=') {
152
                return \DateTime::createFromFormat('Ymd\THis', $matches[5][0], new \DateTimeZone($matches[4][0]));
153
            } else if ($matches[1][0] == 'VALUE=' && $matches[4][0] == 'DATE') {
154
                return \DateTime::createFromFormat('Ymd\THis', $matches[5][0] . 'T000000');
155
            }
156
        }
157
        return null;
158
    }
159
}