@@ -53,20 +53,26 @@ public function __construct(CacheInterface $cache, HttpClient $http)
53
53
*
54
54
* @param string $source_url the Public Suffix List URL
55
55
*
56
+ * @throws Exception If the PSL can not be fetch from the source URL and its cache backend
57
+ * @throws Exception If the PSL cache copy is corrupted
58
+ *
56
59
* @return Rules
57
60
*/
58
61
public function getRules (string $ source_url = self ::PSL_URL ): Rules
59
62
{
60
63
$ cacheKey = $ this ->getCacheKey ($ source_url );
61
- if (null !== ($ rules = $ this ->cache ->get ($ cacheKey ))) {
62
- return new Rules (json_decode ($ rules , true ));
63
- }
64
+ $ rules = $ this ->cache ->get ($ cacheKey );
64
65
65
- if (!$ this ->refreshRules ($ source_url )) {
66
+ if (null === $ rules && !$ this ->refreshRules ($ source_url )) {
66
67
throw new Exception (sprintf ('Unable to load the public suffix list rules for %s ' , $ source_url ));
67
68
}
68
69
69
- return new Rules (json_decode ($ this ->cache ->get ($ cacheKey ), true ));
70
+ $ rules = json_decode ($ rules ?? $ this ->cache ->get ($ cacheKey ), true );
71
+ if (JSON_ERROR_NONE === json_last_error ()) {
72
+ return new Rules ($ rules );
73
+ }
74
+
75
+ throw new Exception ('The public suffix list cache is corrupted: ' .json_last_error_msg (), json_last_error ());
70
76
}
71
77
72
78
/**
@@ -92,16 +98,18 @@ private function getCacheKey(string $str): string
92
98
*
93
99
* @param string $source_url the Public Suffix List URL
94
100
*
101
+ * @throws If the PSL can not be converted to JSON format
102
+ *
95
103
* @return bool
96
104
*/
97
105
public function refreshRules (string $ source_url = self ::PSL_URL ): bool
98
106
{
99
107
$ content = $ this ->http ->getContent ($ source_url );
100
- $ rules = ( new Converter ())->convert ($ content );
101
- if (empty ( $ rules [Rules:: ICANN_DOMAINS ]) || empty ( $ rules [Rules:: PRIVATE_DOMAINS ] )) {
102
- return false ;
108
+ $ rules = json_encode (( new Converter ())->convert ($ content) );
109
+ if (JSON_ERROR_NONE === json_last_error ( )) {
110
+ return $ this -> cache -> set ( $ this -> getCacheKey ( $ source_url ), $ rules ) ;
103
111
}
104
112
105
- return $ this -> cache -> set ( $ this -> getCacheKey ( $ source_url ), json_encode ( $ rules ));
113
+ throw new Exception ( ' The public suffix list JSON conversion failed: ' . json_last_error_msg ( ), json_last_error ( ));
106
114
}
107
115
}
0 commit comments