AuthItem.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace common\modules\rbac\models\searchs;
  3. use Yii;
  4. use yii\base\Model;
  5. use yii\data\ArrayDataProvider;
  6. use yii\rbac\Item;
  7. /**
  8. * AuthItemSearch represents the model behind the search form about AuthItem.
  9. *
  10. * @author Misbahul D Munir <misbahuldmunir@gmail.com>
  11. *
  12. * @since 1.0
  13. */
  14. class AuthItem extends Model
  15. {
  16. const TYPE_ROUTE = 101;
  17. public $name;
  18. public $type;
  19. public $description;
  20. public $rule;
  21. public $data;
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function rules()
  26. {
  27. return [
  28. [['name', 'description'], 'safe'],
  29. [['type'], 'integer'],
  30. ];
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function attributeLabels()
  36. {
  37. return [
  38. 'name' => Yii::t('rbac', 'Name'),
  39. 'item_name' => Yii::t('rbac', 'Name'),
  40. 'type' => Yii::t('rbac', 'Type'),
  41. 'description' => Yii::t('rbac', 'Description'),
  42. 'ruleName' => Yii::t('rbac', 'Rule Name'),
  43. 'data' => Yii::t('rbac', 'Data'),
  44. ];
  45. }
  46. /**
  47. * Search authitem.
  48. *
  49. * @param array $params
  50. *
  51. * @return \yii\data\ActiveDataProvider|\yii\data\ArrayDataProvider
  52. */
  53. public function search($params)
  54. {
  55. /* @var \yii\rbac\Manager $authManager */
  56. $authManager = Yii::$app->authManager;
  57. if ($this->type == Item::TYPE_ROLE) {
  58. $items = $authManager->getRoles();
  59. } else {
  60. $items = [];
  61. if ($this->type == Item::TYPE_PERMISSION) {
  62. foreach ($authManager->getPermissions() as $name => $item) {
  63. if ($name[0] !== '/') {
  64. $items[$name] = $item;
  65. }
  66. }
  67. } else {
  68. foreach ($authManager->getPermissions() as $name => $item) {
  69. if ($name[0] === '/') {
  70. $items[$name] = $item;
  71. }
  72. }
  73. }
  74. }
  75. if ($this->load($params) && $this->validate() && (trim($this->name) !== '' || trim($this->description) !== '')) {
  76. $search = strtolower(trim($this->name));
  77. $desc = strtolower(trim($this->description));
  78. $items = array_filter($items, function ($item) use ($search, $desc) {
  79. return (empty($search) || strpos(strtolower($item->name), $search) !== false) && (empty($desc) || strpos(strtolower($item->description), $desc) !== false);
  80. });
  81. }
  82. return new ArrayDataProvider([
  83. 'allModels' => $items,
  84. ]);
  85. }
  86. }