Created
December 11, 2020 00:19
-
-
Save kurozumi/f7abfe2764e18a61b4df60c55aa2a15e to your computer and use it in GitHub Desktop.
RoutingExtension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This file is part of Customize | |
* | |
* Copyright(c) Akira Kurozumi <[email protected]> | |
* | |
* 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