67 lines
2.2 KiB
PHP
67 lines
2.2 KiB
PHP
<?php
|
|
namespace Misuzu\Redirects;
|
|
|
|
use RuntimeException;
|
|
use Index\Db\{DbConnection,DbStatementCache};
|
|
|
|
class IncrementalRedirectsData {
|
|
private DbStatementCache $cache;
|
|
|
|
public function __construct(DbConnection $dbConn) {
|
|
$this->cache = new DbStatementCache($dbConn);
|
|
}
|
|
|
|
public function getIncrementalRedirects(): iterable {
|
|
$query = <<<SQL
|
|
SELECT redir_id, redir_url, UNIX_TIMESTAMP(redir_created)
|
|
FROM msz_redirects_incremental
|
|
SQL;
|
|
|
|
$stmt = $this->cache->get($query);
|
|
$stmt->execute();
|
|
|
|
return $stmt->getResult()->getIterator(IncrementalRedirectInfo::fromResult(...));
|
|
}
|
|
|
|
public const int INC_BY_ID = 1;
|
|
public const int INC_BY_URL = 2;
|
|
|
|
public function getIncrementalRedirect(string $value, int $field = self::INC_BY_ID): IncrementalRedirectInfo {
|
|
$args = 0;
|
|
$query = <<<SQL
|
|
SELECT redir_id, redir_url, UNIX_TIMESTAMP(redir_created)
|
|
FROM msz_redirects_incremental
|
|
SQL;
|
|
if(($field & self::INC_BY_ID) > 0) {
|
|
++$args;
|
|
$query .= ' WHERE redir_id = ?';
|
|
}
|
|
if(($field & self::INC_BY_URL) > 0)
|
|
$query .= sprintf(' %s redir_url = ?', ++$args > 1 ? 'OR' : 'WHERE');
|
|
|
|
$stmt = $this->cache->get($query);
|
|
while(--$args >= 0)
|
|
$stmt->nextParameter($value);
|
|
$stmt->execute();
|
|
|
|
$result = $stmt->getResult();
|
|
if(!$result->next())
|
|
throw new RuntimeException('incremental redirect not found');
|
|
|
|
return IncrementalRedirectInfo::fromResult($result);
|
|
}
|
|
|
|
public function createIncrementalRedirect(string $url): IncrementalRedirectInfo {
|
|
$stmt = $this->cache->get('INSERT INTO msz_redirects_incremental (redir_url) VALUES (?)');
|
|
$stmt->nextParameter($url);
|
|
$stmt->execute();
|
|
|
|
return $this->getIncrementalRedirect((string)$stmt->getLastInsertId());
|
|
}
|
|
|
|
public function deleteIncrementalRedirect(IncrementalRedirectInfo|string $redirectInfo): void {
|
|
$stmt = $this->cache->get('DELETE msz_redirects_incremental WHERE redir_id = ?');
|
|
$stmt->nextParameter($redirectInfo instanceof IncrementalRedirectInfo ? $redirectInfo->id : $redirectInfo);
|
|
$stmt->execute();
|
|
}
|
|
}
|