1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace App\Model;
13:
14: use Nette,
15: Nette\Object,
16: App\Lib\Tree,
17: App\Lib\Statics\Cons;
18:
19: 20: 21:
22: class Roles extends Object {
23:
24: 25: 26: 27:
28: private $roles = array();
29:
30: 31: 32: 33:
34: private $source;
35:
36: 37: 38: 39:
40: public function __construct(Database $database) {
41: $this->source = (new Tree(Cons::TABLE_ACL . '_' . Cons::TABLE_ROLES, $database))
42: ->data
43: ->where(Cons::COLUMN_PARENT . ' NOT', NULL);
44: foreach ($this->source as $activeRow) {
45: $parent = $activeRow->ref(Cons::COLUMN_PARENT)[Cons::COLUMN_PATH];
46: $this->addRole($activeRow[Cons::COLUMN_PATH], ($parent === NULL || $parent === '') ? NULL : $parent);
47: }
48: }
49:
50: 51: 52: 53: 54: 55:
56: public function setRole($role, $parent = NULL, $parentName = NULL) {
57: $data = array(Cons::COLUMN_NAME => $role);
58: if ($parent !== NULL) {
59: $parent = $this->source->findById($parent);
60: $data[Cons::COLUMN_PARENT] = $parent[Cons::COLUMN_ID];
61: $parentName = $parent[Cons::COLUMN_PATH];
62: }
63: $this->addRole($role, $parentName);
64: $this->source->insert($data);
65: }
66:
67: 68: 69: 70: 71:
72: public function hasRole($role) {
73: $this->checkRole($role, FALSE);
74: return isset($this->roles[$role]);
75: }
76:
77: 78: 79: 80:
81: public function getRoles() {
82: return $this->roles;
83: }
84:
85: 86: 87: 88: 89: 90: 91: 92:
93: private function addRole($role, $parent = NULL) {
94: $this->checkRole($role, FALSE);
95: if (isset($this->roles[$role])) {
96: throw new Nette\InvalidStateException("Role '$role' již v seznamu existuje.");
97: }
98: if ($parent !== NULL) {
99: $this->checkRole($parent);
100: $this->roles[$parent]['childs'][] = $role;
101: }
102: $this->roles[$role] = array('parent' => $parent, 'childs' => array());
103: return $this;
104: }
105:
106: 107: 108: 109: 110: 111: 112:
113: private function checkRole($role, $need = TRUE) {
114: if (!is_string($role) || $role === '') {
115: throw new Nette\InvalidArgumentException('Role musí být řetězec a nesmí být prázdný.');
116: } elseif ($need && !isset($this->roles[$role])) {
117: throw new Nette\InvalidStateException("Role '$role' neexistuje.");
118: }
119: }
120: }
121: