1
|
|
|
<?php |
2
|
|
|
namespace Katapoka\Ahgora; |
3
|
|
|
|
4
|
|
|
use DOMDocument; |
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
use Katapoka\Ahgora\Contracts\IHttpResponse; |
7
|
|
|
|
8
|
|
|
class HtmlPageParser |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @param \Katapoka\Ahgora\Contracts\IHttpResponse $punchsPageResponse |
12
|
|
|
* |
13
|
|
|
* @return mixed |
14
|
|
|
*/ |
15
|
|
|
public function getPunchsTableHtml(IHttpResponse $punchsPageResponse) |
16
|
|
|
{ |
17
|
|
|
$tables = $this->getPageTables($punchsPageResponse); |
18
|
|
|
|
19
|
|
|
//The first table is the data summary |
20
|
|
|
return $tables['punchs']; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function getPunchsRows($punchsPageResponse) |
24
|
|
|
{ |
25
|
|
|
$punchsTableHtml = $this->getPunchsTableHtml($punchsPageResponse); |
26
|
|
|
|
27
|
|
|
$dom = new DOMDocument(); |
28
|
|
|
if (!@$dom->loadHTML($punchsTableHtml)) { |
29
|
|
|
throw new InvalidArgumentException('Failed to parse punchsTable'); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$rows = $dom->getElementsByTagName('tr'); |
33
|
|
|
$rowsCollection = []; |
34
|
|
|
/** @var \DOMElement $row */ |
35
|
|
|
foreach ($rows as $row) { |
36
|
|
|
$cols = $row->getElementsByTagName('td'); |
37
|
|
|
if ($cols->length !== 8) { |
38
|
|
|
continue; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$rowsCollection[] = [ |
42
|
|
|
'date' => trim($cols->item(0)->nodeValue), |
43
|
|
|
'punchs' => trim($cols->item(2)->nodeValue), |
44
|
|
|
]; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return $rowsCollection; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Get both tables and return the strings into an array with the properties 'summary' and 'punchs'. |
52
|
|
|
* |
53
|
|
|
* @param IHttpResponse $punchsPageResponse |
54
|
|
|
* |
55
|
|
|
* @return array |
56
|
|
|
*/ |
57
|
|
|
private function getPageTables(IHttpResponse $punchsPageResponse) |
58
|
|
|
{ |
59
|
|
|
$regex = '/<table.*?>.*?<\/table>/si'; |
60
|
|
|
|
61
|
|
|
if (!preg_match_all($regex, $punchsPageResponse->getBody(), $matches)) { |
62
|
|
|
throw new InvalidArgumentException('Pattern not found in the response'); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return [ |
66
|
|
|
'summary' => $matches[0][0], |
67
|
|
|
'punchs' => $matches[0][1], |
68
|
|
|
]; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
} |
72
|
|
|
|