UserGroupObject.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @package Grav\Common\Flex
  5. *
  6. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  7. * @license MIT License; see LICENSE file for details.
  8. */
  9. namespace Grav\Common\Flex\Types\UserGroups;
  10. use Grav\Common\Flex\FlexObject;
  11. use Grav\Common\User\Access;
  12. use Grav\Common\User\Interfaces\UserGroupInterface;
  13. use function is_bool;
  14. /**
  15. * Flex User Group
  16. *
  17. * @package Grav\Common\User
  18. *
  19. * @property string $groupname
  20. * @property Access $access
  21. */
  22. class UserGroupObject extends FlexObject implements UserGroupInterface
  23. {
  24. /** @var Access */
  25. protected $_access;
  26. /** @var array|null */
  27. protected $access;
  28. /**
  29. * @return array
  30. */
  31. public static function getCachedMethods(): array
  32. {
  33. return [
  34. 'authorize' => false,
  35. ] + parent::getCachedMethods();
  36. }
  37. /**
  38. * @return string
  39. */
  40. public function getTitle(): string
  41. {
  42. return $this->getProperty('readableName');
  43. }
  44. /**
  45. * Checks user authorization to the action.
  46. *
  47. * @param string $action
  48. * @param string|null $scope
  49. * @return bool|null
  50. */
  51. public function authorize(string $action, string $scope = null): ?bool
  52. {
  53. if ($scope === 'test') {
  54. $scope = null;
  55. } elseif (!$this->getProperty('enabled', true)) {
  56. return null;
  57. }
  58. $access = $this->getAccess();
  59. $authorized = $access->authorize($action, $scope);
  60. if (is_bool($authorized)) {
  61. return $authorized;
  62. }
  63. return $access->authorize('admin.super') ? true : null;
  64. }
  65. /**
  66. * @return Access
  67. */
  68. protected function getAccess(): Access
  69. {
  70. if (null === $this->_access) {
  71. $this->getProperty('access');
  72. }
  73. return $this->_access;
  74. }
  75. /**
  76. * @param mixed $value
  77. * @return array
  78. */
  79. protected function offsetLoad_access($value): array
  80. {
  81. if (!$value instanceof Access) {
  82. $value = new Access($value);
  83. }
  84. $this->_access = $value;
  85. return $value->jsonSerialize();
  86. }
  87. /**
  88. * @param mixed $value
  89. * @return array
  90. */
  91. protected function offsetPrepare_access($value): array
  92. {
  93. return $this->offsetLoad_access($value);
  94. }
  95. /**
  96. * @param array|null $value
  97. * @return array|null
  98. */
  99. protected function offsetSerialize_access(?array $value): ?array
  100. {
  101. return $value;
  102. }
  103. }