openvk/Web/Models/Repositories/BannedLinks.php

83 lines
2.1 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
2022-09-05 18:57:41 +03:00
namespace openvk\Web\Models\Repositories;
2022-09-05 18:57:41 +03:00
use Chandler\Database\DatabaseConnection as DB;
use Nette\Database\Table\{ActiveRow, Selection};
use openvk\Web\Models\Entities\BannedLink;
class BannedLinks
{
private $context;
private $bannedLinks;
public function __construct()
2022-09-05 18:57:41 +03:00
{
$this->context = DB::i()->getContext();
$this->bannedLinks = $this->context->table("links_banned");
}
public function toBannedLink(?ActiveRow $ar): ?BannedLink
2022-09-05 18:57:41 +03:00
{
return is_null($ar) ? null : new BannedLink($ar);
2022-09-05 18:57:41 +03:00
}
public function get(int $id): ?BannedLink
2022-09-05 18:57:41 +03:00
{
return $this->toBannedLink($this->bannedLinks->get($id));
}
public function getList(?int $page = 1): \Traversable
2022-09-05 18:57:41 +03:00
{
foreach ($this->bannedLinks->order("id DESC")->page($page, OPENVK_DEFAULT_PER_PAGE) as $link) {
2022-09-05 18:57:41 +03:00
yield new BannedLink($link);
}
2022-09-05 18:57:41 +03:00
}
public function getCount(int $page = 1): int
2022-09-05 18:57:41 +03:00
{
return sizeof($this->bannedLinks->fetch());
}
public function getByDomain(string $domain): ?Selection
2022-09-05 18:57:41 +03:00
{
return $this->bannedLinks->where("domain", $domain);
}
public function isDomainBanned(string $domain): bool
2022-09-05 18:57:41 +03:00
{
return sizeof($this->bannedLinks->where(["link" => $domain, "regexp_rule" => ""])) > 0;
}
public function genLinks($rules): \Traversable
2022-09-05 18:57:41 +03:00
{
foreach ($rules as $rule) {
2022-09-05 18:57:41 +03:00
yield $this->get($rule->id);
}
2022-09-05 18:57:41 +03:00
}
public function genEntries($links, $uri): \Traversable
2022-09-05 18:57:41 +03:00
{
foreach ($links as $link) {
if (preg_match($link->getRegexpRule(), $uri)) {
2022-09-05 18:57:41 +03:00
yield $link->getId();
}
}
2022-09-05 18:57:41 +03:00
}
public function check(string $url): ?array
2022-09-05 18:57:41 +03:00
{
$uri = strstr(str_replace(["https://", "http://"], "", $url), "/", true);
$domain = str_replace("www.", "", $uri);
$rules = $this->getByDomain($domain);
if (is_null($rules)) {
return null;
}
2022-09-05 18:57:41 +03:00
return iterator_to_array($this->genEntries($this->genLinks($rules), $uri));
}
}