CompositeUserContext.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Authorization\Model;
  7. use Magento\Framework\ObjectManager\Helper\Composite as CompositeHelper;
  8. /**
  9. * User context.
  10. *
  11. * This class is not implementing standard composite pattern and will not invoke all of its children.
  12. * Instead, it will try to find the first suitable child and return its result.
  13. *
  14. * @api
  15. * @since 100.0.2
  16. */
  17. class CompositeUserContext implements \Magento\Authorization\Model\UserContextInterface
  18. {
  19. /**
  20. * @var UserContextInterface[]
  21. */
  22. protected $userContexts = [];
  23. /**
  24. * @var UserContextInterface|bool
  25. */
  26. protected $chosenUserContext;
  27. /**
  28. * Register user contexts.
  29. *
  30. * @param CompositeHelper $compositeHelper
  31. * @param UserContextInterface[] $userContexts
  32. */
  33. public function __construct(CompositeHelper $compositeHelper, $userContexts = [])
  34. {
  35. $userContexts = $compositeHelper->filterAndSortDeclaredComponents($userContexts);
  36. foreach ($userContexts as $userContext) {
  37. $this->add($userContext['type']);
  38. }
  39. }
  40. /**
  41. * Add user context.
  42. *
  43. * @param UserContextInterface $userContext
  44. * @return CompositeUserContext
  45. */
  46. protected function add(UserContextInterface $userContext)
  47. {
  48. $this->userContexts[] = $userContext;
  49. return $this;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function getUserId()
  55. {
  56. return $this->getUserContext() ? $this->getUserContext()->getUserId() : null;
  57. }
  58. /**
  59. * {@inheritdoc}
  60. */
  61. public function getUserType()
  62. {
  63. return $this->getUserContext() ? $this->getUserContext()->getUserType() : null;
  64. }
  65. /**
  66. * Retrieve user context
  67. *
  68. * @return UserContextInterface|bool False if none of the registered user contexts can identify user type
  69. */
  70. protected function getUserContext()
  71. {
  72. if ($this->chosenUserContext === null) {
  73. /** @var UserContextInterface $userContext */
  74. foreach ($this->userContexts as $userContext) {
  75. if ($userContext->getUserType() && $userContext->getUserId() !== null) {
  76. $this->chosenUserContext = $userContext;
  77. break;
  78. }
  79. }
  80. if ($this->chosenUserContext === null) {
  81. $this->chosenUserContext = false;
  82. }
  83. }
  84. return $this->chosenUserContext;
  85. }
  86. }