src/Twig/Functions/UrlProviderExtension.php line 70

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Twig\Functions;
  4. use App\Exception\ResourceNotFoundException;
  5. use App\Module\Api\UrlProvider;
  6. use App\Provider\ProductProvider;
  7. use Exception;
  8. use Twig\Extension\AbstractExtension;
  9. use Twig\TwigFunction;
  10. /**
  11. * Class JsonExtension
  12. *
  13. * @package App\Twig\Functions
  14. */
  15. class UrlProviderExtension extends AbstractExtension
  16. {
  17. /**
  18. * @var ProductProvider
  19. */
  20. private ProductProvider $productProvider;
  21. /**
  22. * @var UrlProvider
  23. */
  24. private UrlProvider $urlProvider;
  25. /**
  26. * JsonExtension constructor.
  27. *
  28. * @param UrlProvider $urlProvider
  29. */
  30. public function __construct(UrlProvider $urlProvider, ProductProvider $productProvider)
  31. {
  32. $this->urlProvider = $urlProvider;
  33. $this->productProvider = $productProvider;
  34. }
  35. /**
  36. * @return TwigFunction[]
  37. */
  38. public function getFunctions(): array
  39. {
  40. return [
  41. new TwigFunction(
  42. 'getProductUrlBySku',
  43. [
  44. $this,
  45. 'getProductUrlBySku',
  46. ]
  47. ),
  48. new TwigFunction(
  49. 'getVariantUrlBySku',
  50. [
  51. $this,
  52. 'getVariantUrlBySku',
  53. ]
  54. ),
  55. ];
  56. }
  57. /**
  58. * @param mixed $sku
  59. * @return string|null
  60. * @throws Exception
  61. */
  62. public function getProductUrlBySku($sku): ?string
  63. {
  64. try {
  65. return $this->urlProvider->getProductUrlBySku((int) $sku);
  66. } catch (ResourceNotFoundException $e) {
  67. return null;
  68. }
  69. }
  70. /**
  71. * @param mixed $sku
  72. * @return string|null
  73. * @throws Exception
  74. */
  75. public function getVariantUrlBySku($sku): ?string
  76. {
  77. try {
  78. return $this->urlProvider->getVariantUrlBySku((int) $sku);
  79. } catch (ResourceNotFoundException $e) {
  80. return null;
  81. }
  82. }
  83. }