<?php
namespace Plugin\NZRecaptcha42\Event;
use Plugin\NZRecaptcha42\Service\RecaptchaService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Eccube\Event\TemplateEvent;
class TemplateEventSubscriber implements EventSubscriberInterface
{
/**
* @var RecaptchaService
*/
private $recaptchaService;
public function __construct(RecaptchaService $recaptchaService)
{
$this->recaptchaService = $recaptchaService;
}
public static function getSubscribedEvents()
{
return [
'Entry/index.twig' => 'onEntryIndex',
'Mypage/login.twig' => 'onMypageLogin',
'Contact/index.twig' => 'onContactIndex',
];
}
public function onEntryIndex(TemplateEvent $event)
{
if (!$this->recaptchaService->isEnabledForEntry()) {
return;
}
$this->addRecaptchaScript($event, 'entry', 'eccube_entry');
}
public function onMypageLogin(TemplateEvent $event)
{
if (!$this->recaptchaService->isEnabledForLogin()) {
return;
}
$this->addRecaptchaScript($event, 'login', 'login_mypage');
}
public function onContactIndex(TemplateEvent $event)
{
if (!$this->recaptchaService->isEnabledForContact()) {
return;
}
$this->addRecaptchaScript($event, 'contact', 'contact');
}
private function addRecaptchaScript(TemplateEvent $event, string $action, string $formName)
{
$siteKey = $this->recaptchaService->getSiteKey();
if (!$siteKey) {
return;
}
$script = <<<HTML
<script src="https://www.google.com/recaptcha/api.js?render={$siteKey}"></script>
<script>
(function() {
'use strict';
function addRecaptchaToken() {
var form = document.querySelector('form[name="{$formName}"]');
if (!form) form = document.getElementById('{$formName}');
if (!form) return;
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'g-recaptcha-response';
form.appendChild(input);
form.addEventListener('submit', function(e) {
if (input.value) return true;
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('{$siteKey}', {action: '{$action}'}).then(function(token) {
input.value = token;
form.submit();
});
});
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', addRecaptchaToken);
} else {
addRecaptchaToken();
}
})();
</script>
HTML;
// 第2引数をfalseにしてtemplate_from_stringを使用
$event->addSnippet($script, false);
}
}