示例#1
0
function handle($uri = '')
{
    try {
        if (($matched = dispatch($uri)) != null) {
            if (!before()) {
                $handler = $matched['handler'];
                if (!empty($matched['options']['router'])) {
                    $handler = call_user_func($handler, $matched);
                }
                if (!empty($matched['options']['create'])) {
                    $controllerClass = $handler[0];
                    $handler[0] = new $controllerClass();
                }
                if (isset($matched['params'])) {
                    call_user_func_array($handler, $matched['params']);
                } else {
                    call_user_func_array($handler, $matched['segments']);
                }
                after();
            }
        } else {
            notFound();
        }
        finish();
    } catch (Exception $e) {
        error_log($e->getMessage());
        error_log($e->getTraceAsString());
    }
    exit;
}
示例#2
0
function authorize($data = null)
{
    global $authorized;
    before();
    ?>
    <div id="xicl-error" style="">
        <table id="xicl-error-content"><tr><td>
            <?php 
    login();
    // показываем форму входа/выхода
    ?>
            <?php 
    if (_has('message')) {
        ?>
            <p class="message"><?php 
        echo _data('message');
        ?>
</p>
            <?php 
    }
    ?>
        </td></tr></table>
        <a href="./" id="xicl-error-home" title="на главную">&nbsp;</a>
    </div>
<?php 
    after();
    die;
    // прекратить дальнейшую работу
}
示例#3
0
function pubData($r, $i)
{
    $pubd = array();
    array_push($pubd, between('Artiste :', 'Matériaux :', $r['hits']['hits'][$i]['_source']['pubDate']));
    array_push($pubd, between('Matériaux :', 'Support :', $r['hits']['hits'][$i]['_source']['pubDate']));
    array_push($pubd, between('Support :', 'Format :', $r['hits']['hits'][$i]['_source']['pubDate']));
    array_push($pubd, between('Format :', 'Style :', $r['hits']['hits'][$i]['_source']['pubDate']));
    array_push($pubd, between('Style :', 'Prix :', $r['hits']['hits'][$i]['_source']['pubDate']));
    array_push($pubd, between('Conversion :', 'Référence :', $r['hits']['hits'][$i]['_source']['pubDate']));
    array_push($pubd, after('Référence :', $r['hits']['hits'][$i]['_source']['pubDate']));
    return $pubd;
}
示例#4
0
function getPlayerSkin($input, $list)
{
    if ($input !== '[]') {
        $name = after('[`', $input);
        $name = before('`', $name);
        if (in_array($name, $list)) {
            return $name;
        } else {
            return "Default";
        }
    } else {
        return "Default";
    }
}
示例#5
0
function fail($message)
{
    global $messages;
    before();
    ?>
    <div id="xicl-error" style="">
        <table id="xicl-error-content"><tr><td>
            <p class="message error"><?php 
    echo is_string($message) ? $message : (is_int($message) ? $messages[$message] : 'unknown param for fail page');
    ?>
</p>
        </td></tr></table>
        <a href="<?php 
    echo ServerRoot;
    ?>
" id="xicl-error-home" title="на главную">&nbsp;</a>
    </div>
<?php 
    after();
    die;
    // прекратить дальнейшую работу
}
示例#6
0
文件: Util.php 项目: aaron-em/matura
 public static function gensuite($config = array(), $current_depth = 1)
 {
     $config = array_merge(array('befores' => 0, 'before_alls' => 0, 'afters' => 0, 'after_alls' => 0, 'tests' => 1, 'depth' => 0, 'describes' => array('L', 'R'), 'callbacks' => array('it' => function ($ctx) {
         expect(true)->to->eql(true);
     }, 'before' => function ($ctx) {
         $ctx->value = 3;
     }, 'before_all' => function ($ctx) {
         $ctx->value = 5;
     }, 'after' => function ($ctx) {
         $ctx->value = 7;
     }, 'after_all' => function ($ctx) {
         $ctx->value = 11;
     })), $config);
     if ($config['depth'] == 0) {
         return;
     }
     foreach ($config['describes'] as $side) {
         describe("Level {$side}{$current_depth}", function ($ctx) use($config, $current_depth) {
             for ($i = 1; $i <= $config['tests']; $i++) {
                 it("nested {$i}", $config['callbacks']['it']);
             }
             for ($i = 1; $i <= $config['befores']; $i++) {
                 before($config['callbacks']['before']);
             }
             for ($i = 1; $i <= $config['before_alls']; $i++) {
                 before_all($config['callbacks']['before_all']);
             }
             for ($i = 1; $i <= $config['after_alls']; $i++) {
                 after_all($config['callbacks']['after_all']);
             }
             for ($i = 1; $i <= $config['afters']; $i++) {
                 after($config['callbacks']['after']);
             }
             $config['depth']--;
             Util::gensuite($config, $current_depth + 1);
         });
     }
 }
示例#7
0
after('deploy:symlink', 'deploy:cron:enable');
task('deploy:database:update', function () {
    run('php {{release_path}}/' . trim(get('bin_dir'), '/') . '/console doctrine:schema:update --env={{env}} --force');
});
after('deploy:vendors', 'deploy:database:update');
task('elastica:populate', function () {
    run('php {{release_path}}/' . trim(get('bin_dir'), '/') . '/console fos:elastica:populate --env=\'prod\'');
});
task('php:restart', function () {
    run('sudo service {{php_fpm}} restart');
});
after('deploy', 'php:restart');
task('elastica:populate', function () {
    run('php {{release_path}}/' . trim(get('bin_dir'), '/') . '/console fos:elastica:populate --env=\'prod\'');
});
task('elastica:populate:current', function () {
    run('php {{deploy_path}}/current/' . trim(get('bin_dir'), '/') . '/console fos:elastica:populate --env=\'prod\'');
});
task('seo:dump', function () {
    run('php {{release_path}}/' . trim(get('bin_dir'), '/') . '/console seo:metatag:patterns --env=\'prod\'');
    run('php {{release_path}}/' . trim(get('bin_dir'), '/') . '/console seo:sitemap --env=\'prod\'');
});
task('deploy:cleanup', function () {
    run('rm -f {{release_path}}/Vagrantfile*');
    run('rm -f {{release_path}}/deploy.php');
    run('rm -rf {{release_path}}/.git');
    run('rm -f {{release_path}}/README*');
    run('rm -f {{release_path}}/build.xml');
});
after('cleanup', 'deploy:cleanup');
示例#8
0
require 'recipe/drupal8.php';
server('prod', '146.185.128.63', 9999)->user('deploy')->identityFile()->stage('production')->env('deploy_path', '/usr/share/nginx/html/kristiankaadk');
set('repository', 'git@github.com:kaa4ever/kristiankaadk.git');
task('deploy:permissions', function () {
    run('if [ -d {{deploy_path}}/shared ]; then sudo chown -R deploy:deploy {{deploy_path}}/shared; fi');
    run('if [ -d {{deploy_path}}/releases ]; then sudo chown -R deploy:deploy {{deploy_path}}/releases; fi');
});
task('docker:reboot', function () {
    cd('{{release_path}}');
    run('docker stop kristiankaa.site || true');
    run('docker rm kristiankaa.site || true');
    run('docker-compose -f docker-compose.prod.yml up -d');
});
task('drush:make', function () {
    writeln("<info>Drush: Building site</info>");
    run('docker exec kristiankaa.site bash -c "cd /var/www/html && drush make site.make -y"');
});
task('drush:updb', function () {
    writeln("<info>Drush: Updating database</info>");
    run('docker exec kristiankaa.site drush updb -y --root=/var/www/html');
});
task('drush:cache', function () {
    writeln("<info>Drush: Rebuilding cache</info>");
    run('docker exec kristiankaa.site drush cr --root=/var/www/html');
});
after('deploy:prepare', 'deploy:permissions');
after('deploy:update_code', 'docker:reboot');
after('deploy:update_code', 'drush:make');
after('deploy', 'drush:updb');
after('deploy', 'drush:cache');
示例#9
0
<?php

namespace Deployer;

/**
 * @author Benjamin HUBERT <*****@*****.**>
 */
/**
 * SEO
 */
task('seo:meta-tags', function () {
    run("php {{release_path}}/" . trim(get('bin_dir'), '/') . "/console alpixel:seo:metatag:dump --env='prod'");
})->desc('Dump meta tags');
task('seo:sitemap', function () {
    run("php {{release_path}}/" . trim(get('bin_dir'), '/') . "/console alpixel:cms:sitemap --env='prod'");
})->desc('Dump sitemap');
after('deploy:vendors', 'seo:meta-tags');
after('deploy:vendors', 'seo:sitemap');
示例#10
0
/**
 * Running application
 *
 * @param string $env
 * @return void
 */
function run($env = null)
{
    if (is_null($env)) {
        $env = env();
    }
    # 0. Set default configuration
    $root_dir = dirname(app_file());
    $base_path = dirname(file_path($env['SERVER']['SCRIPT_NAME']));
    $base_file = basename($env['SERVER']['SCRIPT_NAME']);
    $base_uri = file_path($base_path, $base_file == 'index.php' ? '?' : $base_file . '?');
    $lim_dir = dirname(__FILE__);
    option('root_dir', $root_dir);
    option('base_path', $base_path);
    option('base_uri', $base_uri);
    // set it manually if you use url_rewriting
    option('limonade_dir', file_path($lim_dir));
    option('limonade_views_dir', file_path($lim_dir, 'limonade', 'views'));
    option('limonade_public_dir', file_path($lim_dir, 'limonade', 'public'));
    option('public_dir', file_path($root_dir, 'public'));
    option('views_dir', file_path($root_dir, 'views'));
    option('controllers_dir', file_path($root_dir, 'controllers'));
    option('lib_dir', file_path($root_dir, 'lib'));
    option('error_views_dir', option('limonade_views_dir'));
    option('env', ENV_PRODUCTION);
    option('debug', true);
    option('session', LIM_SESSION_NAME);
    // true, false or the name of your session
    option('encoding', 'utf-8');
    option('x-sendfile', 0);
    // 0: disabled,
    // X-SENDFILE: for Apache and Lighttpd v. >= 1.5,
    // X-LIGHTTPD-SEND-FILE: for Apache and Lighttpd v. < 1.5
    # 1. Set error handling
    ini_set('display_errors', 1);
    set_error_handler('error_handler_dispatcher', E_ALL ^ E_NOTICE);
    # 2. Set user configuration
    call_if_exists('configure');
    # 3. Loading libs
    require_once_dir(option('lib_dir'));
    # 4. Starting session
    if (!defined('SID') && option('session')) {
        if (!is_bool(option('session'))) {
            session_name(option('session'));
        }
        if (!session_start()) {
            trigger_error("An error occured while trying to start the session", E_USER_WARNING);
        }
    }
    # 5. Set some default methods if needed
    if (!function_exists('after')) {
        function after($output)
        {
            return $output;
        }
    }
    if (!function_exists('route_missing')) {
        function route_missing($request_method, $request_uri)
        {
            halt(NOT_FOUND, "({$request_method}) {$request_uri}");
        }
    }
    # 6. Check request
    if ($rm = request_method()) {
        if (request_is_head()) {
            ob_start();
        }
        // then no output
        if (!request_method_is_allowed($rm)) {
            halt(HTTP_NOT_IMPLEMENTED, "The requested method <code>'{$rm}'</code> is not implemented");
        }
        # 6.1 Check matching route
        if ($route = route_find($rm, request_uri())) {
            params($route['params']);
            # 6.2 Load controllers dir
            require_once_dir(option('controllers_dir'));
            if (is_callable($route['function'])) {
                # 6.3 Call before function
                call_if_exists('before');
                # 6.4 Call matching controller function and output result
                if ($output = call_user_func($route['function'])) {
                    echo after(error_notices_render() . $output);
                }
                stop_and_exit();
            } else {
                halt(SERVER_ERROR, "Routing error: undefined function '{$route['function']}'", $route);
            }
        } else {
            route_missing($rm, request_uri());
        }
    } else {
        halt(HTTP_NOT_IMPLEMENTED, "The requested method <code>'{$rm}'</code> is not implemented");
    }
}
示例#11
0
文件: Order.php 项目: jaz303/phake
        p(2);
    });
});
desc('bleem');
task('bleem', function () {
    p(0);
});
after('bleem:baz', function () {
    p(3);
});
desc('foo');
task('foo', function () {
    p(5);
});
desc('bar');
task('bar', function () {
    p(8);
});
task('foo', function () {
    p(6);
});
before('foo', function () {
    p(4);
});
after('foo', function () {
    p(7);
});
task('foo', 'bleem:baz');
desc('default');
task('default', 'foo');
task('default', 'bar');
示例#12
0
function run($env = null)
{
    if (is_null($env)) {
        $env = env();
    }
    // 0. Set default configuration
    $root_dir = dirname(app_file());
    $lim_dir = dirname(__FILE__);
    $base_path = dirname(file_path($env['SERVER']['SCRIPT_NAME']));
    $base_file = basename($env['SERVER']['SCRIPT_NAME']);
    $base_uri = file_path($base_path, $base_file == 'index.php' ? '?' : $base_file . '?');
    option('dir.root', $root_dir);
    option('dir.limonade', file_path($lim_dir));
    option('dir.limonade.views', file_path($lim_dir, 'limonade', 'views'));
    option('dir.limonade.public', file_path($lim_dir, 'limonade', 'public'));
    option('dir.public', file_path($root_dir, 'public'));
    option('dir.views', file_path($root_dir, 'views'));
    option('dir.controllers', file_path($root_dir, 'controllers'));
    option('dir.lib', file_path($root_dir, 'lib'));
    option('dir.views.errors', option('dir.limonade.views'));
    option('base.path', $base_path);
    option('base.uri', $base_uri);
    # set it manually if you use url_rewriting
    option('env', ENV_PRODUCTION);
    option('debug', true);
    option('session', LIM_SESSION_NAME);
    # true, false or the name of your session
    option('encoding', 'utf-8');
    option('signature', LIM_NAME);
    # X-Limonade header value or false to hide it
    option('gzip', false);
    option('x-sendfile', 0);
    # 0: disabled,
    # X-SENDFILE: for Apache and Lighttpd v. >= 1.5,
    # X-LIGHTTPD-SEND-FILE: for Apache and Lighttpd v. < 1.5
    // 1. Set handlers
    // 1.1 Set error handling
    ini_set('display_errors', 1);
    set_error_handler('error_handler_dispatcher', E_ALL ^ E_NOTICE);
    // 1.2 Register shutdown function
    register_shutdown_function('stop_and_exit');
    // 2. Set user configuration
    call_if_exists('configure');
    // 2.1 Set gzip compression if defined
    if (is_bool(option('gzip')) && option('gzip')) {
        ini_set('zlib.output_compression', '1');
    }
    // 2.2 Set X-Limonade header
    if ($signature = option('signature')) {
        header("X-Limonade: {$signature}");
    }
    // 3. Loading libs
    require_once_dir(option('dir.lib'));
    fallbacks_for_not_implemented_functions();
    // 4. Starting session
    if (!defined('SID') && option('session')) {
        if (!is_bool(option('session'))) {
            session_name(option('session'));
        }
        if (!session_start()) {
            trigger_error("An error occured while trying to start the session", E_USER_WARNING);
        }
    }
    // 5. Set some default methods if needed
    if (!function_exists('after')) {
        function after($output)
        {
            return $output;
        }
    }
    if (!function_exists('route_missing')) {
        function route_missing($request_method, $request_uri)
        {
            halt(NOT_FOUND, "({$request_method}) {$request_uri}");
        }
    }
    call_if_exists('initialize');
    // 6. Check request
    if ($rm = request_method($env)) {
        if (request_is_head($env)) {
            ob_start();
        }
        // then no output
        if (!request_method_is_allowed($rm)) {
            halt(HTTP_NOT_IMPLEMENTED, "The requested method <code>'{$rm}'</code> is not implemented");
        }
        // 6.1 Check matching route
        if ($route = route_find($rm, request_uri($env))) {
            params($route['params']);
            // 6.2 Load controllers dir
            if (!function_exists('autoload_controller')) {
                function autoload_controller($callback)
                {
                    require_once_dir(option('dir.controllers'));
                }
            }
            autoload_controller($route['callback']);
            if (is_callable($route['callback'])) {
                // 6.3 Call before function
                call_if_exists('before', $route);
                // 6.4 Call matching controller function and output result
                $output = call_user_func_array($route['callback'], array_values($route['params']));
                if (is_null($output)) {
                    $output = call_if_exists('autorender', $route);
                }
                echo after(error_notices_render() . $output, $route);
            } else {
                halt(SERVER_ERROR, "Routing error: undefined function '{$route['callback']}'", $route);
            }
        } else {
            route_missing($rm, request_uri($env));
        }
    } else {
        halt(HTTP_NOT_IMPLEMENTED, "The requested method <code>'{$rm}'</code> is not implemented");
    }
}
function ifFileIsADuplicate($testFileName, $fileNameWithoutType)
{
    $fileName = before('.', $testFileName);
    //remove last 4 characters
    $fileType = after('.', $testFileName);
    //save last 3 characters
    // $testFileName = $convertedData;
    // $fileName = before('.', $convertedData);
    // $fileType = after('.', $convertedData);
    $a = 1;
    while (file_exists($testFileName) == 'true') {
        $testFileName = $fileName . '_' . $a . '.' . $fileType;
        // return new file name and repeat until unique
        $a++;
    }
    return $testFileName;
}
示例#14
0
         });
     });
 });
 describe('Error Capture and Reporting', function ($ctx) {
     before(function ($ctx) {
         $ctx->spy = $spy = Mockery::mock()->shouldIgnoreMissing();
         $ctx->listener = Mockery::mock('Matura\\Events\\Listener')->shouldIgnoreMissing();
         $ctx->suite = suite('Fixture', function ($inner_ctx) use($spy, $ctx) {
             $ctx->before_all = before_all(array($spy, 'before_all'));
             $ctx->after_all = after_all(array($spy, 'after_all'));
             $ctx->after = after(array($spy, 'after'));
             $ctx->before = before(array($spy, 'before'));
             $ctx->describe = describe('Inner', function ($inner_ctx) use($spy, $ctx) {
                 $ctx->inner_before_all = before_all(array($spy, 'inner_before_all'));
                 $ctx->inner_after_all = after_all(array($spy, 'inner_after_all'));
                 $ctx->inner_after = after(array($spy, 'inner_after'));
                 $ctx->inner_before = before(array($spy, 'inner_before'));
                 $ctx->test = it('should have a test case', array($spy, 'it'));
             });
         });
         $ctx->suite_runner = new SuiteRunner($ctx->suite, new ResultSet());
         $ctx->suite_runner->addListener($ctx->listener);
     });
     describe('At the Suite Level', function ($ctx) {
         it('should capture before_all errors', function ($ctx) {
             $ctx->spy->shouldReceive('before_all')->once()->andThrow('\\Exception');
             $ctx->suite_runner->run();
             $failures = $ctx->suite_runner->getResultSet()->getFailures();
             expect($failures)->to->have->length(1);
             expect($failures[0]->getBlock())->to->be($ctx->suite);
         });
<?php

namespace Deployer;

/**
 * @author Benjamin HUBERT <*****@*****.**>
 */
/**
 * TRANSLATION
 */
set('shared_dirs', array_merge(get('shared_dirs'), ['app/Resources/translations']));
task('deploy:translation:download', function () {
    run("php {{release_path}}/" . trim(get('bin_dir'), '/') . "/console alpixel:cms:translations:download --env='prod'");
})->desc('Downloading translations');
after('deploy:vendors', 'deploy:translation:download');
示例#16
0
     it("passes if `beforeEach` has been executed twice", function () {
         expect($this->nb)->toBe(2);
     });
     context("with sub scope", function () {
         it("passes if `beforeEach` has been executed once more", function () {
             expect($this->nb)->toBe(3);
         });
     });
     it("passes if `beforeEach` has been executed once more", function () {
         expect($this->nb)->toBe(4);
     });
 });
 describe("->after()", function () {
     $this->nb = 0;
     after(function () {
         $this->nb++;
     });
     it("passes if `after` has not been executed", function () {
         expect($this->nb)->toBe(0);
     });
 });
 describe("->afterEach()", function () {
     $this->nb = 0;
     afterEach(function () {
         $this->nb++;
     });
     it("passes if `afterEach` has not been executed", function () {
         expect($this->nb)->toBe(0);
     });
     it("passes if `afterEach` has been executed", function () {
         expect($this->nb)->toBe(1);
示例#17
0
文件: dispatch.php 项目: damaera/damn
/**
 * Maps a callback or invokes a callback for requests
 * on $pattern. If $callback is not set, $pattern
 * is matched against all routes for $method, and the
 * the mapped callback for the match is invoked. If $callback
 * is set, that callback is mapped against $pattern for $method
 * requests.
 *
 * @param string $method HTTP request method or method + path
 * @param string $pattern path or callback
 * @param callable $callback optional, handler to map
 *
 * @return void
 */
function on($method, $path, $callback = null)
{
    // state (routes and cache util)
    static $routes = array();
    $regexp = null;
    $path = trim($path, '/');
    // a callback was passed, so we create a route definition
    if (is_callable($callback)) {
        // if we're inside a resouce, use the path
        if (strlen($pref = prefix())) {
            $path = trim("{$pref}/{$path}", '/');
        }
        // add bracketed optional sections and "match anything"
        $path = str_replace(array(')', '*'), array(')?', '.*?'), $path);
        // revised regex that allows named capture groups with optional regexes
        // (uses @ to separate param name and regex)
        $regexp = preg_replace_callback('#:([\\w]+)(@([^/\\(\\)]*))?#', function ($matches) {
            // 2 versions of named capture groups:
            // with and without a following regex.
            if (isset($matches[3])) {
                return '(?P<' . $matches[1] . '>' . $matches[3] . ')';
            } else {
                return '(?P<' . $matches[1] . '>[^/]+)';
            }
        }, $path);
        $method = array_map('strtoupper', (array) $method);
        foreach ($method as $m) {
            $routes[$m]['@^' . $regexp . '$@'] = $callback;
        }
        return;
    }
    // setup method and rexp for dispatch
    $method = strtoupper($method);
    // cache miss, do a lookup
    $finder = function ($routes, $path) {
        $found = false;
        foreach ($routes as $regexp => $callback) {
            if (preg_match($regexp, $path, $values)) {
                return array($regexp, $callback, $values);
            }
        }
        return array(null, null, null);
    };
    // lookup a matching route
    if (isset($routes[$method])) {
        list($regexp, $callback, $values) = $finder($routes[$method], $path);
    }
    // if no match, try the any-method handlers
    if (!$regexp && isset($routes['*'])) {
        list($regexp, $callback, $values) = $finder($routes['*'], $path);
    }
    // we got a match
    if ($regexp) {
        // construct the params for the callback
        $tokens = array_filter(array_keys($values), 'is_string');
        $values = array_map('urldecode', array_intersect_key($values, array_flip($tokens)));
        // setup + dispatch
        ob_start();
        params($values);
        filter($values);
        before($method, "@{$path}");
        // adjust $values array to suit the number of args that the callback is expecting.
        // null padding is added to the array to stop error if optional args don't match
        // the number of parameters.
        $ref = new ReflectionFunction($callback);
        $num_args_expected = $ref->getNumberOfParameters();
        // append filler array. (note: can't call array_fill with zero quantity - throws error)
        $values += ($diff = $num_args_expected - count($values)) > 0 ? array_fill(0, $diff, null) : array();
        call_user_func_array($callback, array_values(bind($values)));
        after($method, $path);
        $buff = ob_get_clean();
        if ($method !== 'HEAD') {
            echo $buff;
        }
    } else {
        error(404);
    }
}
示例#18
0
/**
 * Running application
 *
 * @param string $env 
 * @return void
 */
function run($env = null)
{
    if (is_null($env)) {
        $env = env();
    }
    # 0. Set default configuration
    $root_dir = dirname(app_file());
    option('root_dir', $root_dir);
    option('limonade_dir', dirname(__FILE__) . '/');
    option('public_dir', $root_dir . '/public/');
    option('views_dir', $root_dir . '/views/');
    option('controllers_dir', $root_dir . '/controllers/');
    option('lib_dir', $root_dir . '/lib/');
    option('env', ENV_PRODUCTION);
    option('debug', true);
    option('encoding', 'utf-8');
    option('x-sendfile', 0);
    // 0: disabled,
    // X-SENDFILE: for Apache and Lighttpd v. >= 1.5,
    // X-LIGHTTPD-SEND-FILE: for Apache and Lighttpd v. < 1.5
    # 1. Set error handling
    ini_set('display_errors', 1);
    set_error_handler('error_handler_dispatcher', E_ALL ^ E_NOTICE);
    # 2. Loading libs
    require_once_dir(option('lib_dir'));
    # 3. Set some default methods if needed
    if (!function_exists('after')) {
        function after($output)
        {
            return $output;
        }
    }
    if (!function_exists('route_missing')) {
        function route_missing($request_method, $request_uri)
        {
            halt(NOT_FOUND, "({$request_method}) {$request_uri}");
        }
    }
    # 4. Set user configuration
    call_if_exists('configure');
    # 5. Check request
    if ($rm = request_method()) {
        # 5.1 Check matching route
        if ($route = route_find($rm, request_uri())) {
            params($route['params']);
            # 5.2 Load controllers dir
            require_once_dir(option('controllers_dir'));
            if (function_exists($route['function'])) {
                # 5.3 Call before function
                call_if_exists('before');
                # 5.4 Call matching controller function and output result
                if ($output = call_user_func($route['function'])) {
                    if (option('debug') && option('env') > ENV_PRODUCTION) {
                        $notices = error_notice();
                        if (!empty($notices)) {
                            foreach ($notices as $notice) {
                                echo $notice;
                            }
                            echo '<hr>';
                        }
                    }
                    echo after($output);
                }
                exit;
            } else {
                halt(SERVER_ERROR, "Routing error: undefined function '{$route['function']}'", $route);
            }
        } else {
            route_missing($rm, request_uri());
        }
    } else {
        halt(SERVER_ERROR, "Unknown request method <code>{$rm}</code>");
    }
}
示例#19
0
<?php

require_once __DIR__ . '/deployer/recipe/yii-configure.php';
require_once __DIR__ . '/deployer/recipe/yii2-app-basic.php';
require_once __DIR__ . '/deployer/recipe/in-place.php';
if (!file_exists(__DIR__ . '/deployer/stage/servers.yml')) {
    die('Please create "' . __DIR__ . '/deployer/stage/servers.yml" before continuing.' . "\n");
}
serverList(__DIR__ . '/deployer/stage/servers.yml');
set('repository', '{{repository}}');
set('default_stage', 'production');
set('keep_releases', 2);
set('writable_use_sudo', false);
// Using sudo in writable commands?
set('shared_files', ['config/db.php']);
task('deploy:configure_composer', function () {
    $stage = env('app.stage');
    if ($stage == 'dev') {
        env('composer_options', 'install --verbose --no-progress --no-interaction');
    }
})->desc('Configure composer');
// uncomment the next two lines to run migrations
//after('deploy:symlink', 'deploy:run_migrations');
//after('inplace:configure', 'inplace:run_migrations');
after('deploy:shared', 'deploy:configure');
before('inplace:vendors', 'deploy:configure_composer');
before('deploy:vendors', 'deploy:configure_composer');
示例#20
0
文件: bento.php 项目: nramenta/bento
/**
 * Dispatches incoming request. This function may trigger the 'before',
 * and 'after' events.
 *
 * @param string $method Request method
 * @param string $path   Request path
 */
function dispatch($method, $path)
{
    $callbacks = route();
    foreach ($callbacks as $route => $methods) {
        if (route_match($route, $path, $matches, $redirect)) {
            if ($redirect) {
                $url = url_for($path . '/' . (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : ''));
                redirect($url, 301);
            }
            config('_route', $route);
            if ($method === 'HEAD') {
                if (isset($methods['HEAD'])) {
                    $callback = $methods['HEAD'];
                } elseif (isset($methods['GET'])) {
                    $callback = $methods['GET'];
                } else {
                    $callback = null;
                }
            } elseif ($method === 'OPTIONS') {
                $allowed = array_keys($methods);
                if (in_array('GET', $allowed) && !in_array('HEAD', $allowed)) {
                    $allowed[] = 'HEAD';
                }
                header('Allow: ' . implode(',', $allowed));
                if (isset($methods['OPTIONS'])) {
                    $callback = $methods['OPTIONS'];
                } else {
                    halt();
                }
            } else {
                $callback = isset($methods[$method]) ? $methods[$method] : null;
            }
            if (!isset($callback)) {
                $allowed = array_keys($methods);
                if (in_array('GET', $allowed) && !in_array('HEAD', $allowed)) {
                    $allowed[] = 'HEAD';
                }
                header('Allow: ' . implode(',', array_keys($methods)));
                halt(405);
            }
            $params = array();
            foreach ($matches as $key => $val) {
                if (is_string($key)) {
                    params($key, $params[$key] = urldecode($val));
                }
            }
            $pass = false;
            try {
                ($before = before()) && apply($before, $params);
                apply($callback, $params);
                ($after = after()) && apply($after, $params);
            } catch (\PassException $e) {
                $pass = true;
            }
            if (!$pass) {
                return;
            }
        }
    }
    halt(404);
}
function between($this, $that, $inthat)
{
    return before($that, after($this, $inthat));
}
示例#22
0
    context('with invalid parameters', function () {
        it('fails with an invalid API key', function () {
            $expected = function () {
                (new GoogleMaps('TEAZEE_BAD_KEY', new HttpAdapter(new Client()), new GuzzleMessageFactory()))->find($this->lat, $this->lng, 1455926050);
            };
            expect($expected)->toThrow(new RuntimeException('The provided API key is invalid.'));
        });
    });
    context('when no timestamp given', function () {
        before(function () {
            VCR::turnOff();
        });
        beforeEach(function () {
            $this->now = (new DateTimeImmutable(null, new DateTimeZone('UTC')))->getTimestamp();
            $this->time = $this->teazee->find($this->lat, $this->lng)->getTimestamp();
        });
        it('uses the default timestamp', function () {
            // Note: this _could_ fail if response times are especially bad, but it's google,
            // so we'll take our chances.
            expect($this->time)->toBeGreaterThan($this->now - 1);
            expect($this->time)->toBeLessThan($this->now + 3);
        });
        after(function () {
            VCR::turnOn();
            VCR::insertCassette('google_maps');
        });
    });
    after(function () {
        VCR::eject();
    });
});
<?php

describe("Command Generator Command", function () {
    before(function () {
        $this->app = (new Siphon\Application())->boot();
        $this->app['directory']->create($this->app->basePath('app'));
        $this->app['directory']->create($this->app->basePath('app/Command'));
    });
    after(function () {
        $this->app['directory']->delete($this->app->basePath('app'));
    });
    describe("->handle()", function () {
        it("generates a new controller class", function () {
            $this->app['console']->call('generate:command', ['class' => 'Foo']);
            $file = $this->app->basePath('app/Command/FooCommand.php');
            $content = file_get_contents($file);
            expect(file_exists($file))->toBe(true);
            expect(strpos($content, 'namespace Siphon\\Command'))->toBeA('integer');
            expect(strpos($content, 'class FooCommand extends Command'))->toBeA('integer');
        });
    });
});
示例#24
0
    run('echo "<?php return require \'env-' . $file . '.php\';" > env.php');
    cd('{{release_path}}');
    $adminCoreCommands = has('adminCoreCommands') ? get('adminCoreCommands') : true;
    if ($adminCoreCommands) {
        // run all basic luya commands
        run('./vendor/bin/luya migrate --interactive=0');
    }
    $commands = has('beforeCommands') ? get('beforeCommands') : [];
    foreach ($commands as $cmd) {
        run($cmd);
    }
    if ($adminCoreCommands) {
        run('./vendor/bin/luya import');
        run('./vendor/bin/luya health');
    }
    $commands = has('afterCommands') ? get('afterCommands') : [];
    foreach ($commands as $cmd) {
        run($cmd);
    }
});
task('luya:command_exporter', function () {
    run('cd {{release_path}} && ./vendor/bin/luya exporter/export');
});
set('shared_dirs', ['public_html/storage']);
task('luya', array('deploy:prepare', 'deploy:release', 'deploy:update_code', 'deploy:vendors', 'deploy:luya', 'deploy:symlink', 'deploy:shared', 'cleanup'))->desc('LUYA project deployment');
task('cleanup:deployfile', function () {
    run('rm -f {{release_path}}/deploy.php');
    run('rm -f {{release_path}}/README.md');
});
after('cleanup', 'cleanup:deployfile');
示例#25
0
<?php

require 'frank.php';
class Helpers
{
    function hello($name)
    {
        return "Hello, {$name}";
    }
}
configure(function () {
    $test = 'test';
    set(array('views' => dirname(__FILE__) . '/templates'));
});
after(function () {
    echo " AFTER!";
});
get("/", function () {
    render('form', array('locals' => array('test' => 'test')));
});
template("form", function ($locals) {
    echo '<form method="post">
	        	<input type="submit" value="submit" />
	        	</form>';
});
post("/", function () {
    echo "post";
});
get("/hello/:name", function ($params) {
    pass('/hello/' . $params['name'] . '/test');
});
示例#26
0
<?php

before('create', 'save_level');
after('create', 'save_to_record, update_level');
after('destroy', 'restore_level');
class Ban extends ActiveRecord
{
    function restore_level($user_id, $old_level)
    {
        // User::update_attribute_by_id($user_id, array('level' => $old_level));
        // User::find($user_id).update_attribute(:level, old_level)
    }
    function save_level()
    {
        $this->old_level = User::find_level($this->user_id);
    }
    function update_level($user_id)
    {
        $user = User::find($user_id);
        $user->level = CONFIG::$user_levels['Blocked'];
        $user->save();
    }
    function save_to_record()
    {
        // UserRecord.create(:user_id => self.user_id, :reported_by => self.banned_by, :is_positive => false, :body => "Blocked: #{self.reason}")
    }
    function duration($dur)
    {
        // $this->expires_at = (dur.to_f * 60*60*24).seconds.from_now
        // @duration = dur
    }
示例#27
0
 /**
  * Save current & reinitialize the Interceptor class.
  */
 before(function () {
     $this->previous = Interceptor::instance();
     Interceptor::unpatch();
     $cachePath = rtrim(sys_get_temp_dir(), DS) . DS . 'kahlan';
     $include = ['Kahlan\\Spec\\'];
     $interceptor = Interceptor::patch(compact('include', 'cachePath'));
     $interceptor->patchers()->add('pointcut', new Pointcut());
 });
 /**
  * Restore Interceptor class.
  */
 after(function () {
     Interceptor::load($this->previous);
 });
 describe("::on()", function () {
     context("with an instance", function () {
         it("stubs a method", function () {
             $foo = new Foo();
             Stub::on($foo)->method('message')->andReturn('Good Bye!');
             expect($foo->message())->toBe('Good Bye!');
         });
         it("stubs only on the stubbed instance", function () {
             $foo = new Foo();
             Stub::on($foo)->method('message')->andReturn('Good Bye!');
             expect($foo->message())->toBe('Good Bye!');
             $foo2 = new Foo();
             expect($foo2->message())->toBe('Hello World!');
         });
示例#28
0
 public function testAfterExceptionel1()
 {
     $this->assertEquals("", after("DESCRIPTION:", ""));
 }
示例#29
0
task('artisan:view:clear', function () {
    run('{{bin/php}} {{release_path}}/artisan view:clear');
});
desc('Execute artisan optimize');
task('artisan:optimize', function () {
    run('{{bin/php}} {{release_path}}/artisan optimize');
});
/**
 * Task deploy:public_disk support the public disk.
 * To run this task automatically, please add below line to your deploy.php file
 *
 *     before('deploy:symlink', 'deploy:public_disk');
 *
 * @see https://laravel.com/docs/5.2/filesystem#configuration
 */
desc('Make symlink for public disk');
task('deploy:public_disk', function () {
    // Remove from source.
    run('if [ -d $(echo {{release_path}}/public/storage) ]; then rm -rf {{release_path}}/public/storage; fi');
    // Create shared dir if it does not exist.
    run('mkdir -p {{deploy_path}}/shared/storage/app/public');
    // Symlink shared dir to release dir
    run('{{bin/symlink}} {{deploy_path}}/shared/storage/app/public {{release_path}}/public/storage');
});
/**
 * Main task
 */
desc('Deploy your project');
task('deploy', ['deploy:prepare', 'deploy:lock', 'deploy:release', 'deploy:update_code', 'deploy:shared', 'deploy:vendors', 'deploy:writable', 'artisan:view:clear', 'artisan:cache:clear', 'artisan:config:cache', 'artisan:optimize', 'deploy:symlink', 'deploy:unlock', 'cleanup']);
after('deploy', 'success');
示例#30
0
     $this->previous = Interceptor::instance();
     Interceptor::unpatch();
     $this->composer = Interceptor::composer();
     skipIf(!$this->composer);
     $composer = clone $this->composer[0];
     $this->autoloader = new Autoloader($composer);
     spl_autoload_register([$this->autoloader, 'loadClass']);
     spl_autoload_unregister($this->composer);
     $this->cachePath = Dir::tempnam(null, 'cache');
 });
 afterEach(function () {
     Interceptor::unpatch();
 });
 after(function () {
     spl_autoload_register($this->composer);
     spl_autoload_unregister([$this->autoloader, 'loadClass']);
     Dir::remove($this->cachePath);
     Interceptor::load($this->previous);
 });
 describe("::patch()", function () {
     it("patches the composer autoloader by default", function () {
         $interceptor = Interceptor::patch(['cachePath' => $this->cachePath]);
         expect($interceptor->originalInstance())->toBeAnInstanceOf("Composer\\Autoload\\ClassLoader");
     });
     it("throws an exception if the autoloader has already been patched", function () {
         $closure = function () {
             Interceptor::patch(['cachePath' => $this->cachePath]);
             Interceptor::patch(['cachePath' => $this->cachePath]);
         };
         expect($closure)->toThrow(new JitException("An interceptor is already attached."));
     });
     it("throws an exception if the autoloader has already been patched", function () {