This repository has been archived on 2024-06-26. You can view files and clone it, but cannot push or open issues or pull requests.
sakura/app/Forum/ForumPerms.php

90 lines
2.2 KiB
PHP
Raw Normal View History

<?php
/**
* Holds the forum permission handler.
* @package Sakura
*/
namespace Sakura\Forum;
2016-12-04 19:12:39 +00:00
use Illuminate\Database\Query\Builder;
2016-11-02 18:58:51 +00:00
use Sakura\DB;
use Sakura\User;
2016-12-04 19:12:39 +00:00
use Traversable;
/**
* Forum permission handler.
* @package Sakura
* @author Julian van de Groep <me@flash.moe>
*/
class ForumPerms
{
2016-11-04 16:45:53 +00:00
private static $table = 'forum_perms';
2016-11-02 18:58:51 +00:00
private $forums = [];
private $user = 0;
private $ranks = [];
2016-11-04 16:45:53 +00:00
private $permCache = [];
private $validCache = [];
public function __construct(Forum $forum, User $user)
{
2016-12-04 19:12:39 +00:00
$this->forums = iterator_to_array($this->getForumIds($forum->id));
2016-11-02 18:58:51 +00:00
$this->user = $user->id;
$this->ranks = array_keys($user->ranks);
}
2016-12-04 19:12:39 +00:00
public function getForumIds(int $id): Traversable
{
// yield the initial id
yield $id;
while ($id > 0) {
$id = DB::table('forums')
->where('forum_id', $id)
->value('forum_category');
yield $id;
}
}
2016-12-04 16:33:52 +00:00
public function __get(string $name): bool
{
2016-11-04 16:45:53 +00:00
return $this->check($name);
}
2016-12-04 16:33:52 +00:00
public function __isset(string $name): bool
2016-11-04 16:45:53 +00:00
{
return $this->valid($name);
}
2016-12-04 16:33:52 +00:00
public function valid(string $name): bool
2016-11-04 16:45:53 +00:00
{
if (!array_key_exists($name, $this->validCache)) {
$column = 'perm_' . camel_to_snake($name);
$this->validCache[$name] = DB::getSchemaBuilder()->hasColumn(static::$table, $column);
}
return $this->validCache[$name];
}
2016-12-04 16:33:52 +00:00
public function check(string $name): bool
2016-11-04 16:45:53 +00:00
{
if (!array_key_exists($name, $this->permCache)) {
$column = 'perm_' . camel_to_snake($name);
2016-12-04 19:12:39 +00:00
$result = DB::table(static::$table)
2016-11-02 18:58:51 +00:00
->whereIn('forum_id', $this->forums)
2016-12-04 19:12:39 +00:00
->where(function (Builder $query) {
$query->whereIn('rank_id', $this->ranks)
->orWhere('user_id', $this->user);
})
2016-12-04 19:12:39 +00:00
->whereNotNull($column)
->groupBy($column)
->min($column);
2016-12-04 19:12:39 +00:00
$this->permCache[$name] = intval($result) === 1;
}
2016-11-04 16:45:53 +00:00
return $this->permCache[$name];
}
}