Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RoutingExtension
<?php
/**
* This file is part of Customize
*
* Copyright(c) Akira Kurozumi <info@a-zumi.net>
*
* https://a-zumi.net
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Customize\Twig\Extension;
use Eccube\Entity\Product;
use Eccube\Repository\ProductRepository;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Class RoutingExtension
* @package Customize\Twig\Extension
*/
class RoutingExtension extends \Symfony\Bridge\Twig\Extension\RoutingExtension
{
/**
* @var ProductRepository
*/
private $productRepository;
/**
* RoutingExtension constructor.
* @param UrlGeneratorInterface $generator
* @param ProductRepository $productRepository
*/
public function __construct(UrlGeneratorInterface $generator, ProductRepository $productRepository)
{
parent::__construct($generator);
$this->productRepository = $productRepository;
}
/**
* スラッグを持っている商品はスラッグのURLを生成、
* スラッグを持っていない商品は商品IDのURLを生成
*
* @param string $name
* @param array $parameters
* @param false $schemeRelative
* @return string
*/
public function getUrl($name, $parameters = [], $schemeRelative = false)
{
if ($name === "product_detail") {
/** @var Product $product */
$product = $this->productRepository->find($parameters["id"]);
if($product->getSlug()) {
// スラッグを持っている商品はスラッグのURLを生成
return parent::getUrl("product_detail", ["id" => $product->getSlug()], $schemeRelative);
} else {
// スラッグを持っていない商品は商品IDのURLを生成
return parent::getUrl("product_detail", ["id" => $parameters["id"]], $schemeRelative);
}
}
return parent::getUrl($name, $parameters, $schemeRelative);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment