Skip to content

Instantly share code, notes, and snippets.

@chihiro-adachi
Created March 28, 2017 05:23
Show Gist options
  • Save chihiro-adachi/05531b854c3fb5835cd44232ee8d3790 to your computer and use it in GitHub Desktop.
Save chihiro-adachi/05531b854c3fb5835cd44232ee8d3790 to your computer and use it in GitHub Desktop.
RankServiceProvider
<?php
namespace Plugin\Rank\ServiceProvider;
use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Eccube\Entity\OrderDetail;
use Eccube\Entity\ProductClass;
use Eccube\Entity\ShipmentItem;
use Silex\Application as BaseApplication;
use Silex\ServiceProviderInterface;
use Symfony\Component\HttpFoundation\Request;
class RankServiceProvider implements ServiceProviderInterface
{
public function register(BaseApplication $app)
{
$app['rank.subscriber'] = $app->share(
function ($app) {
return new RankSubscriber();
}
);
$app['orm.em']->getEventManager()->addEventSubscriber($app['rank.subscriber']);
// request eventで起動
$app->before(
function (Request $request, BaseApplication $app) {
// ショップ画面
if ($app['front']) {
// ログイン状態や会員ランクなどで値引率を設定する
$app['rank.subscriber']->execute = true;
$app['rank.subscriber']->nebiki = 0.1;
}
}
);
}
public function boot(BaseApplication $app)
{
}
}
class RankSubscriber implements EventSubscriber
{
public $execute = false;
public $nebiki = 0.5;
public function getSubscribedEvents()
{
return array(
Events::prePersist,
Events::postLoad,
Events::postPersist,
Events::postUpdate,
);
}
public function prePersist(LifecycleEventArgs $args)
{
$this->calcPrice($args->getObject());
}
public function postLoad(LifecycleEventArgs $args)
{
$this->calcPrice($args->getObject());
}
public function postPersist(LifecycleEventArgs $args)
{
$this->calcPrice($args->getObject());
}
public function postUpdate(LifecycleEventArgs $args)
{
$this->calcPrice($args->getObject());
}
protected function calcPrice($entity)
{
if (!$this->execute) {
return;
}
if ($entity instanceof ProductClass) {
$entity->setPrice01IncTax($entity->getPrice02IncTax() * $this->nebiki);
$entity->setPrice02IncTax($entity->getPrice02IncTax() * $this->nebiki);
}
if ($entity instanceof OrderDetail) {
$entity->setPriceIncTax($entity->getPriceIncTax() * $this->nebiki);
}
if ($entity instanceof ShipmentItem) {
$entity->setPriceIncTax($entity->getPriceIncTax() * $this->nebiki);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment