Skip to content

Instantly share code, notes, and snippets.

@kurozumi
Created December 11, 2020 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurozumi/f7abfe2764e18a61b4df60c55aa2a15e to your computer and use it in GitHub Desktop.
Save kurozumi/f7abfe2764e18a61b4df60c55aa2a15e to your computer and use it in GitHub Desktop.
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