Completed
Push — master ( 5ee431...89a822 )
by Angus
09:05
created

Tracker_Favourites_Model::getAll()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 36
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 25
nc 2
nop 0
dl 0
loc 36
ccs 0
cts 19
cp 0
crap 12
rs 8.8571
c 0
b 0
f 0
1
<?php declare(strict_types=1); defined('BASEPATH') OR exit('No direct script access allowed');
2
3
class Tracker_Favourites_Model extends Tracker_Base_Model {
4 127
	public function __construct() {
5 127
		parent::__construct();
6 127
	}
7
8
	public function get(int $page) : array {
9
		$rowsPerPage = 50;
10
		$query = $this->db
11
			->select('SQL_CALC_FOUND_ROWS
12
			          tt.title, tt.title_url,
13
			          ts.site, ts.site_class,
14
			          tf.chapter, tf.updated_at', FALSE)
15
			->from('tracker_favourites AS tf')
16
			->join('tracker_chapters AS tc', 'tf.chapter_id = tc.id', 'left')
17
			->join('tracker_titles AS tt',   'tc.title_id = tt.id',   'left')
18
			->join('tracker_sites AS ts',    'tt.site_id = ts.id',    'left')
19
			->where('tc.user_id', $this->User->id) //CHECK: Is this inefficient? Would it be better to have a user_id column in tracker_favourites?
20
			->order_by('tf.id DESC')
21
			->limit($rowsPerPage, ($rowsPerPage * ($page - 1)))
22
			->get();
23
24
		$favourites = ['rows' => [], 'totalPages' => 1];
25
		if($query->num_rows() > 0) {
26
			foreach($query->result() as $row) {
27
				$arrRow = [];
28
29
				$arrRow['updated_at'] = $row->updated_at;
30
				$arrRow['title']      = $row->title;
31
				$arrRow['title_url']  = $this->Tracker->sites->{$row->site_class}->getFullTitleURL($row->title_url);
32
33
				$arrRow['site']        = $row->site;
34
				$arrRow['site_sprite'] = str_replace('.', '-', $row->site);
35
36
				$chapterData = $this->Tracker->sites->{$row->site_class}->getChapterData($row->title_url, $row->chapter);
37
				$arrRow['chapter'] = "<a href=\"{$chapterData['url']}\">{$chapterData['number']}</a>";
38
				$favourites['rows'][] = $arrRow;
39
			}
40
			$favourites['totalPages'] = ceil($this->db->query('SELECT FOUND_ROWS() count;')->row()->count / $rowsPerPage);
41
		}
42
43
		return $favourites;
44
	}
45
	public function getAll() : array {
46
		$query = $this->db
47
			->select('SQL_CALC_FOUND_ROWS
48
			          tt.title, tt.title_url,
49
			          ts.site, ts.site_class,
50
			          tf.chapter, tf.updated_at', FALSE)
51
			->from('tracker_favourites AS tf')
52
			->join('tracker_chapters AS tc', 'tf.chapter_id = tc.id', 'left')
53
			->join('tracker_titles AS tt',   'tc.title_id = tt.id',   'left')
54
			->join('tracker_sites AS ts',    'tt.site_id = ts.id',    'left')
55
			->where('tc.user_id', $this->User->id) //CHECK: Is this inefficient? Would it be better to have a user_id column in tracker_favourites?
56
			->order_by('tf.id DESC')
57
			->get();
58
59
		$favourites = [];
60
		if($query->num_rows() > 0) {
61
			foreach($query->result() as $row) {
62
				$arrRow = [];
63
64
				$arrRow['updated_at'] = $row->updated_at;
65
				$arrRow['title']      = $row->title;
66
				$arrRow['title_url']  = $this->Tracker->sites->{$row->site_class}->getFullTitleURL($row->title_url);
67
68
				$arrRow['site']        = $row->site;
69
				$arrRow['chapter']     = $row->chapter;
70
71
				$chapterData = $this->Tracker->sites->{$row->site_class}->getChapterData($row->title_url, $row->chapter);
72
				$arrRow['chapter_number'] = $chapterData['number'];
73
				$arrRow['chapter_url'] = $chapterData['url'];
74
75
				$favourites[] = $arrRow;
76
			}
77
		}
78
79
		return $favourites;
80
	}
81
82
	public function set(string $site, string $title, string $chapter, ?int $userID = NULL) : array {
83
		$success = array(
84
			'status' => 'Something went wrong',
85
			'bool'   => FALSE
86
		);
87
		if($siteData = $this->Tracker->title->getSiteDataFromURL($site)) {
88
			//Validate user input
89
			if(!$this->sites->{$siteData->site_class}->isValidTitleURL($title)) {
90
				//Error is already logged via isValidTitleURL
91
				$success['status'] = 'Title URL is not valid';
92
				return $success;
93
			}
94
			if(!$this->sites->{$siteData->site_class}->isValidChapter($chapter)) {
95
				//Error is already logged via isValidChapter
96
				$success['status'] = 'Chapter URL is not valid';
97
				return $success;
98
			}
99
100
			//NOTE: If the title doesn't exist it will be created. This maybe isn't perfect, but it works for now.
101
			$titleID = $this->Tracker->title->getID($title, (int) $siteData->id);
102
			if($titleID === 0) {
103
				//Something went wrong.
104
				log_message('error', "TitleID = 0 for {$title} @ {$siteData->id}");
105
				return $success;
106
			}
107
108
			////We need the series to be tracked
109
			$idCQuery = $this->db->select('id')
110
			                     ->where('user_id', $userID)
111
			                     ->where('title_id', $titleID)
112
			                     ->get('tracker_chapters');
113
			if(!($idCQuery->num_rows() > 0)) {
114
				//NOTE: This pretty much repeats a lot of what we already did above. Is there a better way to do this?
115
				$this->Tracker->list->update($userID, $site, $title, $chapter, FALSE);
116
117
				$idCQuery = $this->db->select('id')
118
				                     ->where('user_id', $userID)
119
				                     ->where('title_id', $titleID)
120
				                     ->get('tracker_chapters');
121
			}
122
			if($idCQuery->num_rows() > 0) {
123
				$idCQueryRow = $idCQuery->row();
124
125
				//Check if it is already favourited
126
				$idFQuery = $this->db->select('id')
127
				                     ->where('chapter_id', $idCQueryRow->id)
128
				                     ->where('chapter', $chapter)
129
				                     ->get('tracker_favourites');
130
				if($idFQuery->num_rows() > 0) {
131
					//Chapter is already favourited, so remove it from DB
132
					$idFQueryRow = $idFQuery->row();
133
134
					$isSuccess = (bool) $this->db->where('id', $idFQueryRow->id)
135
					                             ->delete('tracker_favourites');
136
137
					if($isSuccess) {
138
						$success = array(
139
							'status' => 'Unfavourited',
140
							'bool'   => TRUE
141
						);
142
						$this->History->userRemoveFavourite((int) $idCQueryRow->id, $chapter);
143
					}
144
				} else {
145
					//Chapter is not favourited, so add to DB.
146
					$isSuccess = (bool) $this->db->insert('tracker_favourites', [
147
						'chapter_id'      => $idCQueryRow->id,
148
						'chapter'         => $chapter,
149
						'updated_at'      => date('Y-m-d H:i:s')
150
					]);
151
152
					if($isSuccess) {
153
						$success = array(
154
							'status' => 'Favourited',
155
							'bool'   => TRUE
156
						);
157
						$this->History->userAddFavourite((int) $idCQueryRow->id, $chapter);
158
					}
159
				}
160
			}
161
		}
162
		return $success;
163
	}
164
}
165