Completed
Push — master ( 4cce5c...a326e6 )
by Angus
02:27
created

Tracker_Favourites_Model   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 126
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 4.05%

Importance

Changes 0
Metric Value
dl 0
loc 126
ccs 3
cts 74
cp 0.0405
rs 10
c 0
b 0
f 0
wmc 14
lcom 1
cbo 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B get() 0 37 3
C set() 0 82 10
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
				                     ->where('chapter', $chapter)
93
				                     ->get('tracker_favourites');
94
				if($idFQuery->num_rows() > 0) {
95
					//Chapter is already favourited, so remove it from DB
96
					$idFQueryRow = $idFQuery->row();
97
98
					$isSuccess = (bool) $this->db->where('id', $idFQueryRow->id)
99
					                             ->delete('tracker_favourites');
100
101
					if($isSuccess) {
102
						$success = array(
103
							'status' => 'Unfavourited',
104
							'bool'   => TRUE
105
						);
106
						$this->History->userRemoveFavourite((int) $idCQueryRow->id, $chapter);
107
					}
108
				} else {
109
					//Chapter is not favourited, so add to DB.
110
					$isSuccess = (bool) $this->db->insert('tracker_favourites', [
111
						'chapter_id'      => $idCQueryRow->id,
112
						'chapter'         => $chapter,
113
						'updated_at'      => date('Y-m-d H:i:s')
114
					]);
115
116
					if($isSuccess) {
117
						$success = array(
118
							'status' => 'Favourited',
119
							'bool'   => TRUE
120
						);
121
						$this->History->userAddFavourite((int) $idCQueryRow->id, $chapter);
122
					}
123
				}
124
			}
125
		}
126
		return $success;
127
	}
128
}
129