<?php
/**
 * Created by PhpStorm.
 * User: Olyanren
 * Date: 30.10.2016
 * Time: 09:56
 */

namespace AppBundle\Utils;

use Monolog\Logger;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManager;

class CsrfUtil
{
    private $session;
    private $logger;
    private $tokenManager;

    public function __construct(Session $session, Logger $logger, CsrfTokenManager $tokenManager)
    {
        $this->tokenManager = $tokenManager;
        $this->session = $session;
        $this->logger = $logger;
    }
    public function getToken(){
        return $this->tokenManager->getToken('token');
    }
    public function checkCsrfValid(Request $request)
    {
        $token = new CsrfToken("token", $request->request->get('_token'));
        if (!$this->tokenManager->isTokenValid($token)) {
            $this->session->getFlashBag()->add('error', 'Geçersiz Token. Yöneticiye başvurunuz');
            $this->logger->error('Woops! Token invalid!');
            return false;
        }
        return true;
    }
}