<commit_before><?php
/**
 * Application base class, facade for controller and router
 * 
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @category   Spark
 * @package    Spark_Util
 * @author     <NAME> <<EMAIL>>
 * @copyright  Copyright (c) <NAME>
 * @license    MIT License
 */

namespace Spark;

use Spark\Http\Request, 
    Spark\Http\Response,
    Spark\Http\NotFoundException,
    Symfony\Component\HttpFoundation\RequestMatcher,
    Spark\Dispatcher,
    Spark\Util\FilterChain,
    Spark\Util;

class App
{
    /** @var \Spark\Util\ExtensionManager */
    protected $extensions; 

    protected $routes = array();
    
    /** @var array */
    protected $filters = array();
    
    protected $request;
    
    /** @var Response */
    protected $response;
    
    /** @var Spark\Settings */
    protected $settings;
    
    protected $error = array();
    
	final function __construct()
	{
        $this->extensions = new \Spark\Util\ExtensionManager($this);
        $this->settings = new \Spark\Settings;
        
        $this->request = Request::createFromGlobals();
        
        $this->register("\Spark\Extension\Templates");
        $this->register("\Spark\Extension\Redirecting");
        
        foreach (Util\words("before after shutdown") as $w) {
            $this->filters[$w] = new FilterChain;
        }
        
        $this->init();
    }
    
    function addFilter($event, $handler)
    {
        $this->filters[$event]->add($handler);
    }
    
    /**
     * Template Method which can be used to initialize Subclasses
     */
    function init()
    {}
    
    /**
     * Invokes the given callback and captures the response
     *
     * @param callback $callback
     * @param array $args
     */
    protected function getResponseCapturer($callback)
    {
        $response = $this->response();
        $self = $this;
        
        return function() use ($callback, $response, $self) {
            $args = func_get_args();
        
            ob_start();
            
            try {
                $return = call_user_func_array($callback, $args);
                $self->halt($return);
                
            } catch (\Spark\HaltException $e) {
                $return = $e->getResponse();
                $response->write(ob_get_clean());
                
                $response->write($return->getContent());
                $response->setStatusCode($return->getStatusCode());
                $response->headers->add($return->headers->all());
            }
        };
    }
    
    protected function evalConditions(array $conditions, Request $request)
    {
        $result = false;
        
        foreach ($conditions as $condition) {
            $result = $condition($request);
        }
        
        if (!$result) {
            $this->pass();
        }
        return true;
    }
    
    protected function dispatch(Request $request)
    {
        $method = $request->getMethod();
		
	    if (empty($this->routes[$method])) {
	        $this->response()->setStatusCode(404);
	    }
	    
	    $match = false;
	    
	    foreach ($this->routes[$method] as $route) {
            try {
	            list($pattern, $callback, $conditions) = $route;
	            
	            if (!preg_match($pattern, $request->getRequestUri(), $matches)) {
	                continue;
	            }
	            
                if (!empty($conditions)) {
                    $this->evalConditions($conditions, $request);
                }
                
                $callback = $this->getResponseCapturer($callback);
                $callback($request);
                
                unset($matches[0]);
                $match = true;
                break;
            } catch (\Spark\PassException $e) {
                continue;
            }
	    }
	    
	    if (!$match) {
	        $this->response()->setStatusCode(404);
	    }
	    
        $request->attributes->add($matches);
        return $callback;
    }
    
    /**
     * Dispatches the request and sends the Response
     *
     * @param  Request $request 
     * @return App|Response Returns the response if "return_response" is TRUE
     */
    function run(Request $request = null)
    {
        $request  = $request ?: $this->request;
		$response = $this->response();
		
		dispatch:
	        try {
	            $this->filters["before"]->filter(array($request, $response));  
                $this->dispatch($request);
                
                if (!$response->isSuccessful()) {
                    throw new \Exception("Request not successful.", $response->getStatusCode());
                }
            } catch (\Exception $e) {
                $code = $e->getCode() ?: get_class($e);
                
                if (!$this->handleError($code, $request, $response, $e)) {
                    goto finish;
                }
            }
		
		after:
	        $this->filters["after"]->filter(array($request, $response));
        
        finish:
	        $response->send();
    }
    
    /**
     * Call extensions
     */
    function __call($method, array $args)
    {
        if (in_array($method, array("get", "post", "put", "delete", "head", "options"))) {
            $route = array_shift($args);
            $callback = array_pop($args);
            return $this->route(strtoupper($method), $route, $args, $callback);
        }
        return $this->extensions->call($method, $args);
    }
    
    function halt($response)<commit_msg>Fixed some bugs.<commit_after><?php
/**
 * Application base class, facade for controller and router
 * 
 * This source file is subject to the MIT license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @category   Spark
 * @package    Spark_Util
 * @author     <NAME> <<EMAIL>>
 * @copyright  Copyright (c) <NAME>
 * @license    MIT License
 */

namespace Spark;

use Spark\Http\Request, 
    Spark\Http\Response,
    Spark\Http\NotFoundException,
    Symfony\Component\HttpFoundation\RequestMatcher,
    Spark\Dispatcher,
    Spark\Util\FilterChain,
    Spark\Util;

class App
{
    /** @var \Spark\Util\ExtensionManager */
    protected $extensions; 

    protected $routes = array();
    
    /** @var array */
    protected $filters = array();

    /** @var Request */
    protected $request;
    
    /** @var Response */
    protected $response;
    
    /** @var Spark\Settings */
    protected $settings;

    /** Error Handlers */
    protected $error = array();
    
	final function __construct()
	{
        $this->extensions = new \Spark\Util\ExtensionManager($this);
        $this->settings = new \Spark\Settings;
        
        $this->request = Request::createFromGlobals();
        
        $this->register("\Spark\Extension\Templates");
        $this->register("\Spark\Extension\Redirecting");
        
        foreach (Util\words("before after shutdown") as $w) {
            $this->filters[$w] = new FilterChain;
        }
        
        $this->init();
    }
    
    function addFilter($event, $handler)
    {
        $this->filters[$event]->add($handler);
    }
    
    /**
     * Template Method which can be used to initialize Subclasses
     */
    function init()
    {}
    
    /**
     * Invokes the given callback and captures the response
     *
     * @param callback $callback
     * @param array $args
     */
    protected function getResponseCapturer($callback)
    {
        $response = $this->response();
        $self = $this;
        
        return function() use ($callback, $response, $self) {
            $args = func_get_args();
        
            ob_start();
            
            try {
                $return = call_user_func_array($callback, $args);
                $self->halt($return);
                
            } catch (\Spark\HaltException $e) {
                $return = $e->getResponse();
                $response->write(ob_get_clean());
                
                $response->write($return->getContent());
                $response->setStatusCode($return->getStatusCode());
                $response->headers->add($return->headers->all());
            }
        };
    }
    
    protected function evalConditions(array $conditions, Request $request)
    {
        $result = false;
        
        foreach ($conditions as $condition) {
            $result = $condition($request);
        }
        
        if (!$result) {
            $this->pass();
        }
        return true;
    }
    
    protected function dispatch(Request $request)
    {
        $method = $request->getMethod();
		
	    if (empty($this->routes[$method])) {
            return $this->response()->setStatusCode(404);
        }
	    
	    $match = false;
	    
	    foreach ($this->routes[$method] as $route) {
            try {
	            list($pattern, $callback, $conditions) = $route;
	            
	            if (!preg_match($pattern, $request->getRequestUri(), $matches)) {
	                continue;
	            }
	            
                if (!empty($conditions)) {
                    $this->evalConditions($conditions, $request);
                }

                unset($matches[0]);
                $request->attributes->add($matches);
                
                $callback = $this->getResponseCapturer($callback);
                $callback($request);
                
                $match = true;
                break;
            } catch (\Spark\PassException $e) {
                continue;
            }
	    }
	    
	    if (!$match) {
	        $this->response()->setStatusCode(404);
	    }
    }
    
    /**
     * Dispatches the request and sends the Response
     *
     * @param  Request $request 
     * @return App|Response Returns the response if "return_response" is TRUE
     */
    function run(Request $request = null)
    {
        $request  = $request ?: $this->request;
		$response = $this->response();
		
		dispatch:
	        try {
	            $this->filters["before"]->filter(array($request, $response));  
                $this->dispatch($request);
                
                if (!$response->isSuccessful()) {
                    throw new \Exception("Request not successful.", $response->getStatusCode());
                }
            } catch (\Exception $e) {
                $code = $e->getCode() ?: get_class($e);

                if (!$this->handleError($code, $request, $response, $e)) {
                    // We are processing a thrown Exception, not an HTTP Error here
                    if (is_string($code)) {
                        throw $e;
                    }
                    goto finish;
                }
            }
		
		after:
	        $this->filters["after"]->filter(array($request, $response));
        
        finish:
	        $response->send();
    }
    
    /**
     * Call extensions
     */
    function __call($method, array $args)
    {
        if (in_array($method, array("get", "post", "put", "delete", "head", "options"))) {
            $route = array_shift($args);
            $callback = array_pop($args);
            return $this->route(strtoupper($method), $route, $args, $callback);
        }
        return $this->extensions->call($method, $args);
    }
    
    function halt($response)
{'fraction_non_alphanumeric': 0.1370903630421341, 'fraction_numerical': 0.001236639872802756, 'mean_word_length': 1.6305762081784387, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 109, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '760485', 'n_tokens_mistral': 3117, 'n_tokens_neox': 2985, 'n_words': 645}