Completed
Push — master ( c2cfef...1a5a57 )
by Angus
02:24
created

Tracker_Favourites_Model::get()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 37
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 27
nc 2
nop 1
dl 0
loc 37
ccs 0
cts 27
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 119
	public function __construct() {
5 119
		parent::__construct();
6 119
	}
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
46
	public function set(string $site, string $title, string $chapter, ?int $userID = NULL) : array {
47
		$success = array(
48
			'status' => 'Something went wrong',
49
			'bool'   => FALSE
50
		);
51
		if($siteData = $this->Tracker->title->getSiteDataFromURL($site)) {
52
			//Validate user input
53
			if(!$this->sites->{$siteData->site_class}->isValidTitleURL($title)) {
54
				//Error is already logged via isValidTitleURL
55
				$success['status'] = 'Title URL is not valid';
56
				return $success;
57
			}
58
			if(!$this->sites->{$siteData->site_class}->isValidChapter($chapter)) {
59
				//Error is already logged via isValidChapter
60
				$success['status'] = 'Chapter URL is not valid';
61
				return $success;
62
			}
63
64
			//NOTE: If the title doesn't exist it will be created. This maybe isn't perfect, but it works for now.
65
			$titleID = $this->Tracker->title->getID($title, (int) $siteData->id);
66
			if($titleID === 0) {
67
				//Something went wrong.
68
				log_message('error', "TitleID = 0 for {$title} @ {$siteData->id}");
69
				return $success;
70
			}
71
72
			////We need the series to be tracked
73
			$idCQuery = $this->db->select('id')
74
			                     ->where('user_id', $userID)
75
			                     ->where('title_id', $titleID)
76
			                     ->get('tracker_chapters');
77
			if(!($idCQuery->num_rows() > 0)) {
78
				//NOTE: This pretty much repeats a lot of what we already did above. Is there a better way to do this?
79
				$this->Tracker->list->update($userID, $site, $title, $chapter, FALSE);
80
81
				$idCQuery = $this->db->select('id')
82
				                     ->where('user_id', $userID)
83
				                     ->where('title_id', $titleID)
84
				                     ->get('tracker_chapters');
85
			}
86
			if($idCQuery->num_rows() > 0) {
87
				$idCQueryRow = $idCQuery->row();
88
89
				//Check if it is already favourited
90
				$idFQuery = $this->db->select('id')
91
				                     ->where('chapter_id', $idCQueryRow->id)
92
				                     ->get('tracker_favourites');
93
				if($idFQuery->num_rows() > 0) {
94
					//Chapter is already favourited, so remove it from DB
95
					$idFQueryRow = $idFQuery->row();
96
97
					$isSuccess = (bool) $this->db->where('id', $idFQueryRow->id)
98
					                             ->delete('tracker_favourites');
99
100
					if($isSuccess) {
101
						$success = array(
102
							'status' => 'Unfavourited',
103
							'bool'   => TRUE
104
						);
105
						$this->History->userRemoveFavourite((int) $idCQueryRow->id, $chapter);
106
					}
107
				} else {
108
					//Chapter is not favourited, so add to DB.
109
					$isSuccess = (bool) $this->db->insert('tracker_favourites', [
110
						'chapter_id'      => $idCQueryRow->id,
111
						'chapter'         => $chapter,
112
						'updated_at'      => date('Y-m-d H:i:s')
113
					]);
114
115
					if($isSuccess) {
116
						$success = array(
117
							'status' => 'Favourited',
118
							'bool'   => TRUE
119
						);
120
						$this->History->userAddFavourite((int) $idCQueryRow->id, $chapter);
121
					}
122
				}
123
			}
124
		}
125
		return $success;
126
	}
127
}
128