Completed
Push — master ( c2cfef...1a5a57 )
by Angus
02:24
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 16
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 119
	public function __construct() {
6 119
		parent::__construct();
7 119
	}
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('
46
			    tracker_chapters.current_chapter,
47
			    tracker_chapters.category,
48
			    tracker_chapters.mal_id,
49
			    tracker_chapters.tags,
50
51
			    tracker_titles.title_url,
52
53
			    tracker_sites.site
54
			')
55
			->from('tracker_chapters')
56
			->join('tracker_titles', 'tracker_chapters.title_id = tracker_titles.`id', 'left')
57
			->join('tracker_sites', 'tracker_sites.id = tracker_titles.site_id', 'left')
58
			->where('tracker_chapters.user_id', $this->User->id)
59
			->where('tracker_chapters.active', 'Y')
60
			->get();
61
62
		$arr = [];
63
		if($query->num_rows() > 0) {
64
			foreach ($query->result() as $row) {
65
				$arr[$row->category][] = [
66
					'site'            => $row->site,
67
					'title_url'       => $row->title_url,
68
					'current_chapter' => $row->current_chapter,
69
70
					'tag_list'        => $row->tags,
71
					'mal_id'          => $row->mal_id
72
				];
73
			}
74
75
			return $arr;
76
		}
77
	}
78
}
79