<?php 

namespace NPS\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RequestStack;


/**
 * Base controller for every application instance
 * @author Lukas Korinek
 */
abstract class AbstractController extends Controller
{
    /** @var Request $request Current request */
    private $request;

    public function __construct(RequestStack $stack)
    {
        $this->debug = [];
        $this->request = $stack->getCurrentRequest();
    }

    /**
     * Flushes any doctrine related changes
     */
    protected function flush()
    {
        $this->getDoctrine()->getManager()->flush();
    }

    /**
     * Creates a response
     * @param array $data
     * @return Response
     */
    protected function response(array $data = [])
    {
        if(!$this->getRequest()->isXmlHttpRequest())
        {
            throw $this->createNotFoundException();
        }
        
        $payload = array_merge($data, ['debug' => isset($GLOBALS['debug']) ? $GLOBALS['debug'] : []]);
        return $this->json(
            $payload
        );
    }

    

    /**
     * Returns current request
     * @return Request
     */
    protected function getRequest()
    {
        return $this->request;
    }

}


