<?php
declare(strict_types=1);
namespace App\Twig\Functions;
use App\Exception\ResourceNotFoundException;
use App\Module\Api\UrlProvider;
use App\Provider\ProductProvider;
use Exception;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Class JsonExtension
*
* @package App\Twig\Functions
*/
class UrlProviderExtension extends AbstractExtension
{
/**
* @var ProductProvider
*/
private ProductProvider $productProvider;
/**
* @var UrlProvider
*/
private UrlProvider $urlProvider;
/**
* JsonExtension constructor.
*
* @param UrlProvider $urlProvider
*/
public function __construct(UrlProvider $urlProvider, ProductProvider $productProvider)
{
$this->urlProvider = $urlProvider;
$this->productProvider = $productProvider;
}
/**
* @return TwigFunction[]
*/
public function getFunctions(): array
{
return [
new TwigFunction(
'getProductUrlBySku',
[
$this,
'getProductUrlBySku',
]
),
new TwigFunction(
'getVariantUrlBySku',
[
$this,
'getVariantUrlBySku',
]
),
];
}
/**
* @param mixed $sku
* @return string|null
* @throws Exception
*/
public function getProductUrlBySku($sku): ?string
{
try {
return $this->urlProvider->getProductUrlBySku((int) $sku);
} catch (ResourceNotFoundException $e) {
return null;
}
}
/**
* @param mixed $sku
* @return string|null
* @throws Exception
*/
public function getVariantUrlBySku($sku): ?string
{
try {
return $this->urlProvider->getVariantUrlBySku((int) $sku);
} catch (ResourceNotFoundException $e) {
return null;
}
}
}