Completed
Push — master ( 3560ba...257e65 )
by Angus
03:23
created

MangaFox::doCustomUpdate()   C

Complexity

Conditions 12
Paths 5

Size

Total Lines 66
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 0
Metric Value
cc 12
eloc 47
nc 5
nop 0
dl 0
loc 66
ccs 0
cts 54
cp 0
crap 156
rs 5.9123
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php declare(strict_types=1); defined('BASEPATH') OR exit('No direct script access allowed');
2
3
class MangaFox extends Base_Site_Model {
4
	public $titleFormat   = '/^[a-z0-9_]+$/';
5
	public $chapterFormat = '/^(?:v[0-9a-zA-Z]+\/)?c[0-9\.]+$/';
6
7
	public function getFullTitleURL(string $title_url) : string {
8
		return "http://mangafox.me/manga/{$title_url}/";
9
	}
10
11
	public function getChapterData(string $title_url, string $chapter) : array {
12
		return [
13
			'url'    => "http://mangafox.me/manga/{$title_url}/{$chapter}/1.html",
14
			'number' => $chapter
15
		];
16
	}
17
18
	public function getTitleData(string $title_url, bool $firstGet = FALSE) {
19
		$titleData = [];
20
21
		$fullURL = $this->getFullTitleURL($title_url);
22
		$content = $this->get_content($fullURL);
23
24
		$data = $this->parseTitleDataDOM(
25
			$content,
0 ignored issues
show
Security Bug introduced by
It seems like $content defined by $this->get_content($fullURL) on line 22 can also be of type false; however, Base_Site_Model::parseTitleDataDOM() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
26
			$title_url,
27
			"//title",
28
			"//body/div[@id='page']/div[@class='left']/div[@id='chapters']/ul[1]/li[1]",
29
			"div/span[@class='date']",
30
			"div/h3/a"
31
		);
32
		if($data) {
33
			$titleData['title'] = html_entity_decode(explode(' Manga - Read ', $data['nodes_title']->textContent)[0]);
34
35
			$link = preg_replace('/^(.*\/)(?:[0-9]+\.html)?$/', '$1', (string) $data['nodes_chapter']->getAttribute('href'));
36
			$chapterURLSegments = explode('/', $link);
37
			$titleData['latest_chapter'] = $chapterURLSegments[5] . (isset($chapterURLSegments[6]) && !empty($chapterURLSegments[6]) ? "/{$chapterURLSegments[6]}" : "");
38
			$titleData['last_updated'] =  date("Y-m-d H:i:s", strtotime((string) $data['nodes_latest']->nodeValue));
39
40
			if($firstGet) {
41
				$titleData = array_merge($titleData, $this->doCustomFollow($content['body']));
42
			}
43
		}
44
45
		return (!empty($titleData) ? $titleData : NULL);
46
	}
47
48
	//FIXME: This entire thing feels like an awful implementation....BUT IT WORKS FOR NOW.
49
	public function handleCustomFollow(callable $callback, string $data = "", array $extra = []) {
50
		preg_match('/var sid=(?<id>[0-9]+);/', $data, $matches);
51
52
		$formData = [
53
			'action' => 'add',
54
			'sid'    => $matches['id']
55
		];
56
57
		$cookies = [
58
			"mfvb_userid={$this->config->item('mangafox_userid')}",
59
			"mfvb_password={$this->config->item('mangafox_password')}",
60
			"bmsort=last_chapter"
61
		];
62
		$content = $this->get_content('http://mangafox.me/ajax/bookmark.php', implode("; ", $cookies), "", TRUE, TRUE, $formData);
63
64
		$callback($content, $matches['id'], function($body) {
65
			return $body == 'true';
66
		});
67
	}
68
	public function doCustomUpdate() {
69
		$titleDataList = [];
70
71
		$cookies = [
72
			"mfvb_userid={$this->config->item('mangafox_userid')}",
73
			"mfvb_password={$this->config->item('mangafox_password')}",
74
			"bmsort=last_chapter",
75
			"bmorder=za"
76
		];
77
		$content = $this->get_content('http://mangafox.me/bookmark/?status=currentreading&sort=last_chapter&order=za', implode("; ", $cookies), "", TRUE);
78
79
		if(!is_array($content)) {
80
			log_message('error', "{$this->site} /bookmark | Failed to grab URL (See above curl error)");
81
		} else {
82
			$headers     = $content['headers'];
0 ignored issues
show
Unused Code introduced by
$headers is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
83
			$status_code = $content['status_code'];
84
			$data        = $content['body'];
85
86
			if(!($status_code >= 200 && $status_code < 300)) {
87
				log_message('error', "{$this->site} /bookmark | Bad Status Code ({$status_code})");
88
			} else if(empty($data)) {
89
				log_message('error', "{$this->site} /bookmark | Data is empty? (Status code: {$status_code})");
90
			} else {
91
				$data = preg_replace('/^[\s\S]+<ul id="bmlist">/', '<ul id="bmlist">', $data);
92
				$data = preg_replace('/<!-- end of bookmark -->[\s\S]+$/', '<!-- end of bookmark -->', $data);
93
94
				$dom = new DOMDocument();
95
				libxml_use_internal_errors(TRUE);
96
				$dom->loadHTML($data);
97
				libxml_use_internal_errors(FALSE);
98
99
				$xpath      = new DOMXPath($dom);
100
				$nodes_rows = $xpath->query("//ul[@id='bmlist']/li/div[@class='series_grp' and h2[@class='title']/span[@class='updatedch'] and dl]");
101
				if($nodes_rows->length > 0) {
102
					foreach($nodes_rows as $row) {
103
						$titleData = [];
104
105
						$nodes_title   = $xpath->query("h2[@class='title']/a[contains(@class, 'title')]", $row);
106
						$nodes_chapter = $xpath->query("dl/dt[1]/a[@class='chapter']", $row);
107
						$nodes_latest  = $xpath->query("dl/dt[1]/em/span[@class='timing']", $row);
108
109
						if($nodes_title->length === 1 && $nodes_chapter->length === 1 && $nodes_latest->length === 1) {
110
							$title = $nodes_title->item(0);
111
112
							$titleData['title'] = trim($title->textContent);
113
114
115
							$link = preg_replace('/^(.*\/)(?:[0-9]+\.html)?$/', '$1', (string) $nodes_chapter->item(0)->getAttribute('href'));
116
							$chapterURLSegments = explode('/', $link);
117
							$titleData['latest_chapter'] = $chapterURLSegments[5] . (isset($chapterURLSegments[6]) && !empty($chapterURLSegments[6]) ? "/{$chapterURLSegments[6]}" : "");
118
119
							$titleData['last_updated'] =  date("Y-m-d H:i:s", strtotime((string) $nodes_latest->item(0)->nodeValue));
120
121
							$title_url = explode('/', $title->getAttribute('href'))[4];
122
							$titleDataList[$title_url] = $titleData;
123
						} else {
124
							log_message('error', "{$this->site}/Custom | Invalid amount of nodes (TITLE: {$nodes_title->length} | CHAPTER: {$nodes_chapter->length}) | LATEST: {$nodes_latest->length})");
125
						}
126
					}
127
				} else {
128
					log_message('error', '{$this->site} | Following list is empty?');
129
				}
130
			}
131
		}
132
		return $titleDataList;
133
	}
134
	public function doCustomCheck(string $oldChapterString, string $newChapterString) {
135
		$oldChapterSegments = explode('/', $oldChapterString);
136
		$newChapterSegments = explode('/', $newChapterString);
137
138
		$status = $this->doCustomCheckCompare($oldChapterSegments, $newChapterSegments);
139
140
		return $status;
141
	}
142
}
143