AuthorPostUrl.php
3 months ago
CommentCount.php
3 months ago
FirstPost.php
3 months ago
FullName.php
3 months ago
HasRichEditing.php
3 months ago
LastPost.php
3 months ago
Meta.php
3 months ago
PostCount.php
3 months ago
PostCountOriginal.php
3 months ago
Property.php
3 months ago
Roles.php
3 months ago
ShowToolbar.php
3 months ago
TranslatedRoles.php
3 months ago
UserFilteredPostLink.php
3 months ago
UserLink.php
3 months ago
UserName.php
3 months ago
Roles.php
69 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AC\Formatter\User; |
| 6 | |
| 7 | use AC; |
| 8 | use AC\Exception\ValueNotFoundException; |
| 9 | use AC\Helper\UserRoles; |
| 10 | use AC\Type\Value; |
| 11 | |
| 12 | class Roles implements AC\Formatter |
| 13 | { |
| 14 | |
| 15 | private bool $allow_non_editable_roles; |
| 16 | |
| 17 | public function __construct(bool $allow_non_editable_roles) |
| 18 | { |
| 19 | $this->allow_non_editable_roles = $allow_non_editable_roles; |
| 20 | } |
| 21 | |
| 22 | public function format(Value $value) |
| 23 | { |
| 24 | $user = get_userdata($value->get_id()); |
| 25 | |
| 26 | if ( ! $user) { |
| 27 | throw ValueNotFoundException::from_id($value->get_id()); |
| 28 | } |
| 29 | |
| 30 | $labels = []; |
| 31 | |
| 32 | foreach ($user->roles as $role_name) { |
| 33 | $role_object = $this->get_allowed_role($role_name); |
| 34 | |
| 35 | if ( ! $role_object) { |
| 36 | continue; |
| 37 | } |
| 38 | |
| 39 | $labels[] = $role_object->get_translate_label(); |
| 40 | } |
| 41 | |
| 42 | return $value->with_value( |
| 43 | implode(', ', $labels) |
| 44 | ); |
| 45 | } |
| 46 | |
| 47 | private function get_allowed_roles(): AC\Type\UserRoles |
| 48 | { |
| 49 | static $editable_roles; |
| 50 | |
| 51 | if (null === $editable_roles) { |
| 52 | $editable_roles = UserRoles::create()->find_all($this->allow_non_editable_roles); |
| 53 | } |
| 54 | |
| 55 | return $editable_roles; |
| 56 | } |
| 57 | |
| 58 | private function get_allowed_role(string $role): ?AC\Type\UserRole |
| 59 | { |
| 60 | foreach ($this->get_allowed_roles() as $editable_role) { |
| 61 | if ($role === $editable_role->get_name()) { |
| 62 | return $editable_role; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | return null; |
| 67 | } |
| 68 | |
| 69 | } |