Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
AbstractSwitcher.php
1<?php
2
4
9use Exception;
10
11abstract class AbstractSwitcher implements SwitcherInterface
12{
13 use CacheTrait;
14
15 public const TYPE_ON = 'Y';
16 public const TYPE_OFF = 'N';
17
18 protected ?int $spaceId = null;
19 protected int $userId;
20 protected string $value;
21 protected string $code = '';
22 protected bool $isInitialized = false;
23
24 abstract public function getValue(): string;
25
26 abstract public static function getDefaultCode(): string;
27
28 public function __construct(int $userId, ?int $spaceId, string $code)
29 {
30 $this->userId = $userId;
31 $this->spaceId = $spaceId;
32 $this->code = $code;
33 }
34
35 public function switch(): Result
36 {
37 $result = new Result();
38 if (!$this->canSwitch())
39 {
40 $result->addError(new Error('No permissions.'));
41 return $result;
42 }
43
44 $result = $this->isEnabled() ? $this->disable() : $this->enable();
45 $result->setData([
46 'value' => $this->getValue(),
47 'message' => $this->getMessage(),
48 ]);
49
50 return $result;
51 }
52
53 public function isEnabled(): bool
54 {
55 return $this->getValue() === static::TYPE_ON;
56 }
57
58 public function getUserId(): int
59 {
60 return $this->userId;
61 }
62
63 public function getSpaceId(): ?int
64 {
65 return $this->spaceId;
66 }
67
68 public function getCode(): string
69 {
70 return $this->code;
71 }
72
73 public function getMessage(): ?string
74 {
75 return null;
76 }
77
78 protected function canSwitch(): bool
79 {
80 return $this->isSpaceExists() && $this->isMember();
81 }
82
83 protected function isSpaceExists(): bool
84 {
85 if (is_null($this->spaceId))
86 {
87 return true;
88 }
89
90 try
91 {
92 return !is_null(WorkgroupTable::getByPrimary($this->spaceId)->fetchObject());
93 }
94 catch (Exception)
95 {
96 return false;
97 }
98 }
99
100 protected function isMember(): bool
101 {
102 $userSpaces = UserRegistry::getInstance($this->userId)->getUserGroups();
103 if (empty($userSpaces))
104 {
105 return false;
106 }
107
108 return in_array($this->spaceId, array_keys($userSpaces), true);
109 }
110}
__construct(int $userId, ?int $spaceId, string $code)