UrlGenerator.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Backend\Model\Widget\Grid\Row;
  7. /**
  8. * Grid row url generator
  9. * @api
  10. * @since 100.0.2
  11. */
  12. class UrlGenerator implements \Magento\Backend\Model\Widget\Grid\Row\GeneratorInterface
  13. {
  14. /**
  15. * @var \Magento\Backend\Model\UrlInterface
  16. */
  17. protected $_urlModel;
  18. /**
  19. * @var string
  20. */
  21. protected $_path;
  22. /**
  23. * @var array
  24. */
  25. protected $_params = [];
  26. /**
  27. * @var array
  28. */
  29. protected $_extraParamsTemplate = [];
  30. /**
  31. * @param \Magento\Backend\Model\UrlInterface $backendUrl
  32. * @param array $args
  33. * @throws \InvalidArgumentException
  34. */
  35. public function __construct(\Magento\Backend\Model\UrlInterface $backendUrl, array $args = [])
  36. {
  37. if (!isset($args['path'])) {
  38. throw new \InvalidArgumentException('Not all required parameters passed');
  39. }
  40. $this->_urlModel = isset($args['urlModel']) ? $args['urlModel'] : $backendUrl;
  41. $this->_path = (string)$args['path'];
  42. if (isset($args['params'])) {
  43. $this->_params = (array)$args['params'];
  44. }
  45. if (isset($args['extraParamsTemplate'])) {
  46. $this->_extraParamsTemplate = (array)$args['extraParamsTemplate'];
  47. }
  48. }
  49. /**
  50. * Create url for passed item using passed url model
  51. *
  52. * @param \Magento\Framework\DataObject $item
  53. * @return string
  54. */
  55. public function getUrl($item)
  56. {
  57. if (!empty($this->_path)) {
  58. $params = $this->_prepareParameters($item);
  59. return $this->_urlModel->getUrl($this->_path, $params);
  60. }
  61. return '';
  62. }
  63. /**
  64. * Convert template params array and merge with preselected params
  65. *
  66. * @param \Magento\Framework\DataObject $item
  67. * @return array
  68. */
  69. protected function _prepareParameters($item)
  70. {
  71. $params = [];
  72. foreach ($this->_extraParamsTemplate as $paramKey => $paramValueMethod) {
  73. $params[$paramKey] = $item->{$paramValueMethod}();
  74. }
  75. return array_merge($this->_params, $params);
  76. }
  77. }