Completed
Push — master ( 45893c...373238 )
by Angus
02:39
created

Tracker_Portation_Model::importFromJSON()   C

Complexity

Conditions 7
Paths 3

Size

Total Lines 33
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 18
nc 3
nop 1
dl 0
loc 33
ccs 0
cts 0
cp 0
crap 56
rs 6.7272
c 0
b 0
f 0
1
<?php declare(strict_types=1); defined('BASEPATH') OR exit('No direct script access allowed');
2
3
//http://english.stackexchange.com/a/141735
4
class Tracker_Portation_Model extends Tracker_Base_Model {
5 112
	public function __construct() {
6 112
		parent::__construct();
7 112
	}
8
9
	public function importFromJSON(string $json_string) : array {
10
		//We already know the this is a valid JSON string as it was validated by form_validator.
11
		$json = json_decode($json_string, TRUE);
12
13
		/*
14
		 * 0 = Success
15
		 * 1 = Invalid keys.
16
		 * 2 = Has failed rows
17
		 */
18
		$status = ['code' => 0, 'failed_rows' => []];
19
20
		$categories = array_keys($json);
21
		if(count($categories) === count(array_intersect(['reading', 'on-hold', 'plan-to-read', 'custom1', 'custom2', 'custom3'], $categories))) {
22
			$json_keys = array_keys(call_user_func_array('array_merge', call_user_func_array('array_merge', $json)));
23
24
			if(count($json_keys) === 3 && !array_diff(array('site', 'title_url', 'current_chapter'), $json_keys)) {
25
				foreach($categories as $category) {
26
					foreach($json[$category] as $row) {
27
						$success = $this->Tracker->list->update($this->User->id, $row['site'], $row['title_url'], $row['current_chapter']);
28
						if(!$success) {
29
							$status['code']          = 2;
30
							$status['failed_rows'][] = $row;
31
						}
32
					}
33
				}
34
			} else {
35
				$status['code'] = 1;
36
			}
37
		} else {
38
			$status['code'] = 1;
39
		}
40
		return $status;
41
	}
42
43
	public function export() {
44
		$query = $this->db
45
			->select('tracker_chapters.current_chapter,
46
			          tracker_chapters.category,
47
			          tracker_titles.title_url,
48
			          tracker_sites.site')
49
			->from('tracker_chapters')
50
			->join('tracker_titles', 'tracker_chapters.title_id = tracker_titles.`id', 'left')
51
			->join('tracker_sites', 'tracker_sites.id = tracker_titles.site_id', 'left')
52
			->where('tracker_chapters.user_id', $this->User->id)
53
			->where('tracker_chapters.active', 'Y')
54
			->get();
55
56
		$arr = [];
57
		if($query->num_rows() > 0) {
58
			foreach ($query->result() as $row) {
59
				$arr[$row->category][] = [
60
					'site'            => $row->site,
61
					'title_url'       => $row->title_url,
62
					'current_chapter' => $row->current_chapter
63
				];
64
			}
65
66
			return $arr;
67
		}
68
	}
69
70
}
71