Skip to content

Commit

Permalink
Fix the PHPStan errors
Browse files Browse the repository at this point in the history
  • Loading branch information
marienfressinaud committed Jul 14, 2023
1 parent 4d01f60 commit 29cd174
Show file tree
Hide file tree
Showing 319 changed files with 4,937 additions and 3,349 deletions.
56 changes: 19 additions & 37 deletions lib/SpiderBits/src/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,38 +10,31 @@
*/
class Cache
{
/** @var string */
private $path;
private string $path;

/**
* @param string $path
*
* @throws RuntimeException if the path doesn't exist or if it's not a
* directory
* @throws \RuntimeException
* If the path doesn't exist or if it's not a directory.
*/
public function __construct($path)
public function __construct(string $path)
{
$this->path = realpath($path);
$path = realpath($path);

if ($this->path === false) {
if ($path === false) {
throw new \RuntimeException('The cache path does not exist');
}

if (!is_dir($this->path)) {
if (!is_dir($path)) {
throw new \RuntimeException('The cache path is not a directory');
}

$this->path = $path;
}

/**
* Return text from the cache
*
* @param string $key
* @param integer $validity_interval How many seconds the cache is valid,
* default is 1 day
*
* @return string|null
*/
public function get($key, $validity_interval = 24 * 60 * 60)
public function get(string $key, int $validity_interval = 24 * 60 * 60): ?string
{
$cached_text_path = $this->path . '/' . $key;
$mtime = @filemtime($cached_text_path);
Expand All @@ -64,13 +57,8 @@ public function get($key, $validity_interval = 24 * 60 * 60)

/**
* Save text in cache
*
* @param string $key
* @param string $text
*
* @return boolean
*/
public function save($key, $text)
public function save(string $key, string $text): bool
{
$cached_text_path = $this->path . '/' . $key;
$compressed_text = @gzencode($text);
Expand All @@ -80,12 +68,8 @@ public function save($key, $text)

/**
* Clear the cache of the given key.
*
* @param string $key
*
* @return boolean Return true on success or false on failure
*/
public function remove($key)
public function remove(string $key): bool
{
$filepath = $this->path . '/' . $key;
if (file_exists($filepath)) {
Expand All @@ -97,25 +81,23 @@ public function remove($key)

/**
* Returns a hash of the given string.
*
* @param string $string
*
* @return string
*/
public static function hash($string)
public static function hash(string $string): string
{
return hash('sha256', $string);
}

/**
* Clean the cache
*
* @param integer $validity_interval
* How many seconds the cache is valid, default is 7 days
*/
public function clean($validity_interval = 7 * 24 * 60 * 60)
public function clean(int $validity_interval = 7 * 24 * 60 * 60): void
{
$files = scandir($this->path);

if ($files === false) {
return;
}

foreach ($files as $file) {
if ($file === '.' || $file === '..' || $file === '.keep') {
continue;
Expand Down
77 changes: 53 additions & 24 deletions lib/SpiderBits/src/ClearUrls.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,28 @@
namespace SpiderBits;

/**
* @phpstan-type ClearUrlsProvider array{
* 'urlPattern': string,
* 'completeProvider': bool,
* 'rules': string[],
* 'referralMarketing': string[],
* 'rawRules': string[],
* 'exceptions': string[],
* 'redirections': string[],
* 'forceRedirection': bool,
* }
*
* @phpstan-type ClearUrlsData array{
* 'providers': array<string, ClearUrlsProvider>,
* }
*
* @author Marien Fressinaud <dev@marienfressinaud.fr>
* @license http://www.gnu.org/licenses/agpl-3.0.en.html AGPL
*/
class ClearUrls
{
private static $clear_urls_data = null;
/** @var ?ClearUrlsData */
private static ?array $clear_urls_data = null;

/**
* Clear a URL from its tracker parameters.
Expand All @@ -24,15 +40,11 @@ class ClearUrls
*
* @see https://docs.clearurls.xyz/1.23.0/specs/rules/
*
* @param string $url
*
* @throws \Exception
* Raised if the clearurls-data.minify.json file cannot be read, or
* cannot be parsed to JSON.
*
* @return string
*/
public static function clear($url)
public static function clear(string $url): string
{
// A note about the regex used in this method: PCRE patterns must be
// enclosed by delimiters. They are generally "/", "#" or "~". Problem:
Expand Down Expand Up @@ -63,7 +75,7 @@ public static function clear($url)
// Secondly, verify the URL is not in the exceptions list (if it
// is, skip it).
$is_exception = false;
foreach ($provider['exceptions'] ?? [] as $exception_pattern) {
foreach ($provider['exceptions'] as $exception_pattern) {
if (preg_match("@{$exception_pattern}@i", $url)) {
$is_exception = true;
break;
Expand All @@ -76,15 +88,15 @@ public static function clear($url)

// If the provider is "completeProvider", the URL should be blocked
// (i.e. an empty string in flusio context).
if (isset($provider['completeProvider']) && $provider['completeProvider']) {
if ($provider['completeProvider']) {
return '';
}

// Extract redirections from the URL if any (e.g.
// https://google.com/url?q=https://example.com)
// If we find a redirection, we call clear() recursively (but
// the current call ends here)
foreach ($provider['redirections'] ?? [] as $redirection_pattern) {
foreach ($provider['redirections'] as $redirection_pattern) {
$result = preg_match("@{$redirection_pattern}@i", $url, $matches);
if ($result && count($matches) >= 2) {
// the redirected URL is in the first Regex group (index 0
Expand All @@ -96,19 +108,30 @@ public static function clear($url)
}

// Directly remove matching rawRules from the URL
foreach ($provider['rawRules'] ?? [] as $raw_rule_pattern) {
foreach ($provider['rawRules'] as $raw_rule_pattern) {
$url = preg_replace("@{$raw_rule_pattern}@i", '', $url);

if ($url === null) {
return '';
}
}

// Apply rules and referralMarketing rules to query parameters.
// Since trackers can also be inserted in the URL fragment, we
// clear it as well.
$rules = array_merge(
$provider['rules'] ?? [],
$provider['referralMarketing'] ?? []
$provider['rules'],
$provider['referralMarketing']
);

$parsed_url = parse_url($url);

if ($parsed_url === false) {
return '';
}

$parsed_url['scheme'] = $parsed_url['scheme'] ?? 'http';
$parsed_url['host'] = $parsed_url['host'] ?? '';
$parsed_url['query'] = $parsed_url['query'] ?? '';
$parsed_url['fragment'] = $parsed_url['fragment'] ?? '';

Expand Down Expand Up @@ -149,25 +172,34 @@ public static function clear($url)
* Raised if the clearurls-data.minify.json file cannot be read, or
* cannot be parsed to JSON.
*
* @return array
* @return array<string, ClearUrlsProvider>
*/
private static function loadClearUrlsProviders()
private static function loadClearUrlsProviders(): array
{
if (self::$clear_urls_data === null) {
$rules_path = realpath(__DIR__ . '/../lib/ClearUrlsRules/data.min.json');
$clear_urls_file_content = file_get_contents($rules_path);

if ($rules_path === false) {
throw new \Exception('ClearUrlsRules file does not exist.');
}

$clear_urls_file_content = @file_get_contents($rules_path);

if ($clear_urls_file_content === false) {
throw new \Exception(
$rules_path . ' file cannot be found.'
);
throw new \Exception($rules_path . ' file cannot be found.');
}

self::$clear_urls_data = json_decode($clear_urls_file_content, true);
if (self::$clear_urls_data === null) {
$clear_urls_data = json_decode($clear_urls_file_content, true);

if (!is_array($clear_urls_data) || !isset($clear_urls_data['providers'])) {
throw new \Exception(
$rules_path . ' file does not contain valid JSON.'
);
}

/** @var ClearUrlsData */
$clear_urls_data = $clear_urls_data;
self::$clear_urls_data = $clear_urls_data;
}

return self::$clear_urls_data['providers'];
Expand All @@ -179,12 +211,9 @@ private static function loadClearUrlsProviders()
* Parameters are removed from the string if their names match any of the
* provided rules patterns.
*
* @param string $query
* @param string[] $rules
*
* @return string
*/
private static function clearQuery($query, $rules)
private static function clearQuery(string $query, array $rules): string
{
$parameters = Url::parseQuery($query);

Expand Down
Loading

0 comments on commit 29cd174

Please sign in to comment.