EmulatedAdminhtmlAreaProcessor.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Config\Console\Command;
  7. use Magento\Framework\App\Area;
  8. use Magento\Framework\App\State;
  9. use Magento\Framework\Config\ScopeInterface;
  10. /**
  11. * Emulates callback inside adminhtml area code and adminhtml scope.
  12. * It is used for CLI commands which should work with data available only in adminhtml scope.
  13. */
  14. class EmulatedAdminhtmlAreaProcessor
  15. {
  16. /**
  17. * The application scope manager.
  18. *
  19. * @var ScopeInterface
  20. */
  21. private $scope;
  22. /**
  23. * The application state manager.
  24. *
  25. * @var State
  26. */
  27. private $state;
  28. /**
  29. * @param ScopeInterface $scope The application scope manager
  30. * @param State $state The application state manager
  31. */
  32. public function __construct(ScopeInterface $scope, State $state)
  33. {
  34. $this->scope = $scope;
  35. $this->state = $state;
  36. }
  37. /**
  38. * Emulates callback inside adminhtml area code and adminhtml scope.
  39. *
  40. * Returns the return value of the callback.
  41. *
  42. * @param callable $callback The callable to be called
  43. * @param array $params The parameters to be passed to the callback, as an indexed array
  44. * @return bool|int|float|string|array|null - as the result of this method is the result of callback,
  45. * you can use callback only with specified in this method return types
  46. * @throws \Exception The exception is thrown if the parameter $callback throws an exception
  47. */
  48. public function process(callable $callback, array $params = [])
  49. {
  50. $currentScope = $this->scope->getCurrentScope();
  51. try {
  52. return $this->state->emulateAreaCode(Area::AREA_ADMINHTML, function () use ($callback, $params) {
  53. $this->scope->setCurrentScope(Area::AREA_ADMINHTML);
  54. return call_user_func_array($callback, $params);
  55. });
  56. } catch (\Exception $exception) {
  57. throw $exception;
  58. } finally {
  59. $this->scope->setCurrentScope($currentScope);
  60. }
  61. }
  62. }