-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReader.php
More file actions
94 lines (78 loc) · 2.31 KB
/
Reader.php
File metadata and controls
94 lines (78 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace Meta;
use BadUrlException;
use FileNotFoundException;
use FileNotReadableException;
use UnknownTypeException;
/**
* Created by PhpStorm.
* User: 731MY
* Date: 6/29/18
* Time: 9:29 AM
*/
class Reader {
private $Config;
private $PathOrData;
private $Type;
/**
* Reader constructor.
* @param $pathOrData
* @param Type $type
* @param Config|null $config
*/
public function __construct($pathOrData, int $type = Type::URL, Config $config = null){
$this->PathOrData = $pathOrData;
$this->Type = $type;
if($type == Type::URL){
if(is_null($config)){
$this->Config = new Config();
}else{
$this->Config = $config;
}
}
}
/**
* @param $url
* @return mixed
*/
private function call($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->Config->getTimeout());
curl_setopt($ch, CURLOPT_USERAGENT, $this->Config->getUserAgent());
if(!is_null($this->Config->getReferer())){
curl_setopt($ch, CURLOPT_REFERER, $this->Config->getReferer());
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
/**
* @return mixed
* @throws FileNotFoundException
* @throws FileNotReadableException
* @throws BadUrlException
* @throws UnknownTypeException
*/
public function get() {
if($this->Type === Type::URL){
if(!filter_var($this->PathOrData, FILTER_VALIDATE_URL)){
throw new BadUrlException();
}
return $this->call($this->PathOrData);
} else if($this->Type === Type::FILE){
if(!is_file($this->PathOrData)){
throw new FileNotFoundException();
} else if(is_readable($this->PathOrData)){
throw new FileNotReadableException();
}
return file_get_contents($this->PathOrData);
}else if($this->Type === Type::DATA){
return $this->PathOrData;
}
throw new UnknownTypeException();
}
}