80 lines
2.7 KiB
PHP
80 lines
2.7 KiB
PHP
<?php
|
|
namespace Misuzu\Apps;
|
|
|
|
use InvalidArgumentException;
|
|
use RuntimeException;
|
|
use Index\Db\{DbConnection,DbStatementCache};
|
|
|
|
class ScopesData {
|
|
private DbStatementCache $cache;
|
|
|
|
public function __construct(DbConnection $dbConn) {
|
|
$this->cache = new DbStatementCache($dbConn);
|
|
}
|
|
|
|
public function getScopes(
|
|
?bool $restricted = null,
|
|
?bool $deprecated = null
|
|
): iterable {
|
|
$args = 0;
|
|
$query = <<<SQL
|
|
SELECT scope_id, scope_string, scope_restricted, scope_summary,
|
|
UNIX_TIMESTAMP(scope_created), UNIX_TIMESTAMP(scope_deprecated)
|
|
FROM msz_scopes
|
|
SQL;
|
|
if($restricted !== null) {
|
|
++$args;
|
|
$query .= sprintf(' WHERE scope_restricted %s 0', $restricted ? '<>' : '=');
|
|
}
|
|
if($deprecated !== null)
|
|
$query .= sprintf(' %s scope_deprecated %s NULL', ++$args > 1 ? 'AND' : 'WHERE', $deprecated ? 'IS NOT' : 'IS');
|
|
|
|
$stmt = $this->cache->get($query);
|
|
$stmt->execute();
|
|
|
|
return $stmt->getResultIterator(ScopeInfo::fromResult(...));
|
|
}
|
|
|
|
public function getScopeInfo(string $value, ScopeInfoGetField $field): ScopeInfo {
|
|
$stmt = $this->cache->get(sprintf(
|
|
<<<SQL
|
|
SELECT scope_id, scope_string, scope_restricted, scope_summary,
|
|
UNIX_TIMESTAMP(scope_created), UNIX_TIMESTAMP(scope_deprecated)
|
|
FROM msz_scopes
|
|
WHERE %s = ?
|
|
SQL,
|
|
match($field) {
|
|
ScopeInfoGetField::Id => 'scope_id',
|
|
ScopeInfoGetField::String => 'scope_string',
|
|
}
|
|
));
|
|
|
|
$stmt->nextParameter($value);
|
|
$stmt->execute();
|
|
|
|
$result = $stmt->getResult();
|
|
if(!$result->next())
|
|
throw new RuntimeException('Scope not found.');
|
|
|
|
return ScopeInfo::fromResult($result);
|
|
}
|
|
|
|
public function createScope(string $string, bool $restricted, string $summary = ''): ScopeInfo {
|
|
if(trim($string) === '')
|
|
throw new InvalidArgumentException('$string may not be empty');
|
|
if(preg_match('#[^A-Za-z0-9:-]#', $string))
|
|
throw new InvalidArgumentException('$string contains invalid characters');
|
|
|
|
$stmt = $this->cache->get(<<<SQL
|
|
INSERT INTO msz_scopes (
|
|
scope_string, scope_restricted, scope_summary
|
|
) VALUES (?, ?, ?)
|
|
SQL);
|
|
$stmt->nextParameter($string);
|
|
$stmt->nextParameter($restricted ? 1 : 0);
|
|
$stmt->nextParameter(trim($summary));
|
|
$stmt->execute();
|
|
|
|
return $this->getScopeInfo((string)$stmt->lastInsertId, ScopeInfoGetField::Id);
|
|
}
|
|
}
|