示例#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 getPlayerSkin($input, $list)
{
    if ($input !== '[]') {
        $name = after('[`', $input);
        $name = before('`', $name);
        if (in_array($name, $list)) {
            return $name;
        } else {
            return "Default";
        }
    } else {
        return "Default";
    }
}
示例#4
0
/**
 * 404 error page.
 */
function not_found($errno, $errstr, $errfile = null, $errline = null)
{
    if (strpos($errstr, '/public/soft_images/') !== false) {
        render_file('public/img/down.png');
        return;
    }
    before();
    set('errno', $errno);
    set('errstr', $errstr);
    set('errfile', $errfile);
    set('errline', $errline);
    layout('layout.php');
    return html('404.php');
}
示例#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);
         });
     }
 }
function fddbSuche($gtin)
{
    //$gtin = "4388844009943";
    $gtin = preg_replace('/[^0-9]+/', '', $gtin);
    $data = curlData("http://fddb.mobi/search/?lang=de&cat=mobile-de&search=" . $gtin);
    $resultblock = between("<!-- %sresultblock% //-->", "<!-- %eresultblock% //-->", $data);
    $link = between("window.location.href = '", "';", $data);
    $area = between("<b>100 g:</b>", "<b>1 Packung:</b>", $data);
    if ($link != false && strlen($gtin) >= 13) {
        $werte = array("energy" => preg_replace('/[^0-9,.]+/', '', before("(", $area)), "calories" => preg_replace('/[^0-9,.]+/', '', between("(", ")", $area)), "fat" => preg_replace('/[^0-9,.]+/', '', between("Fett: ", "KH:", $area)), "carbonhydrate" => preg_replace('/[^0-9,.]+/', '', between("KH: ", "<br>", $area)));
        //$werte = array("Energie", "Energie1", "Fett", "Kohlenhydrate");
        $naerhwerte = "";
        foreach ($werte as $key => $value) {
            $naerhwerte[$key]["value"] = preg_replace('/[^0-9]+/', '', $werte[$key]);
            $naerhwerte[$key]["currencie"] = preg_replace('/[^a-zA-Z]+/', '', $werte[$key]);
        }
        $result = array("sourecName" => "fddb", "link" => $link, "gtin" => $gtin, "nutriTable" => $werte, "titel" => between("<a href='" . $link . "'><b>", '</b></a>', $resultblock));
        $graph = new EasyRdf_Graph();
        $namespace = new EasyRdf_Namespace();
        $namespace->set('rezept', "http://manke-hosting.de/ns-syntax#");
        buildTree($graph, $result["link"], $result, 'rezept');
        echo $graph->serialise("turtle");
    }
}
示例#8
0
 before(function () use(&$console, &$spec) {
     $console = new Console(array(), 'php://output');
     $console->parseArguments();
     $suite = new Suite('test', function () {
     });
     $spec = new Spec('testspec', function () {
     }, $suite);
 });
 it('implements the ReporterInterface', function () use(&$console) {
     $reporter = new SpecReporter($console);
     expect($reporter instanceof ReporterInterface)->toBeTrue();
 });
 context('beforeSuite', function () use(&$console) {
     $reporter = null;
     before(function () use(&$console, &$reporter) {
         $reporter = new SpecReporter($console);
     });
     it('prints the suite title', function () use(&$reporter) {
         $beforeSuite = function () use(&$reporter) {
             $suite = new Suite('test suite', function () {
             });
             $reporter->beforeSuite($suite);
         };
         expect($beforeSuite)->toPrint(PHP_EOL . "test suite" . PHP_EOL);
     });
     it('pads nested suites', function () use(&$reporter) {
         $beforeSuite = function () use(&$reporter) {
             $suite = new Suite('test suite', function () {
             });
             $reporter->beforeSuite($suite);
         };
示例#9
0
<?php

namespace kahlan\spec\suite\analysis;

use kahlan\analysis\Inspector;
describe("Inspector", function () {
    before(function () {
        $this->class = 'kahlan\\spec\\fixture\\analysis\\SampleClass';
    });
    describe('::inspect()', function () {
        it("gets the reflexion layer of a class", function () {
            $inspector = Inspector::inspect($this->class);
            expect($inspector)->toBeAnInstanceOf('ReflectionClass');
            expect($inspector->name)->toBe($this->class);
        });
    });
    describe('::parameters()', function () {
        it("gets method's parameters details", function () {
            $inspector = Inspector::parameters($this->class, 'parametersExample');
            expect($inspector)->toBeA('array');
            $param2 = next($inspector);
            expect($param2)->toBeAnInstanceOf('ReflectionParameter');
            expect($param2->getName())->toBe('b');
            expect($param2->getDefaultValue())->toBe(100);
            $param3 = next($inspector);
            expect($param3)->toBeAnInstanceOf('ReflectionParameter');
            expect($param3->getName())->toBe('c');
            expect($param3->getDefaultValue())->toBe('abc');
            $param4 = next($inspector);
            expect($param4)->toBeAnInstanceOf('ReflectionParameter');
            expect($param4->getName())->toBe('d');
示例#10
0
use pho\Suite\Suite;
use pho\Runnable\Spec;
use pho\Runnable\Runnable;
use pho\Exception\ErrorException;
use pho\Exception\ExpectationException;
class MockRunnable extends Runnable
{
    public function __construct(\Closure $closure, Suite $suite)
    {
        $this->suite = $suite;
        $this->closure = $closure->bindTo($suite);
    }
}
describe('Runnable', function () {
    before(function () {
        $this->suite = new Suite('TestSuite', function () {
        });
    });
    context('run', function () {
        it('catches and stores errors', function () {
            $closure = function () {
                trigger_error('TestError', E_USER_NOTICE);
            };
            $runnable = new MockRunnable($closure, $this->suite);
            $runnable->run();
            expect($runnable->exception->getType())->toEqual('E_USER_NOTICE');
        });
        it('catches and stores ExpectationExceptions', function () {
            $closure = function () {
                throw new ExpectationException('test');
            };
            $runnable = new MockRunnable($closure, $this->suite);
示例#11
0
         beforeEach(function () {
             $this->bar = 1;
         });
         it("can access variable from the parent scope", function () {
             expect($this->bar)->toBe(1);
         });
     });
 });
 describe("skipIf", function () {
     it("returns none if provided false/null", function () {
         expect(skipIf(false))->toBe(null);
     });
     $executed = 0;
     context("when used in a scope", function () use(&$executed) {
         before(function () {
             skipIf(true);
         });
         it("skips this spec", function () use(&$executed) {
             expect(true)->toBe(false);
             $executed++;
         });
         it("skips this spec too", function () use(&$executed) {
             expect(true)->toBe(false);
             $executed++;
         });
     });
     it("expects that no spec have been runned", function () use(&$executed) {
         expect($executed)->toBe(0);
     });
     context("when used in a spec", function () use(&$executed) {
         it("skips this spec", function () use(&$executed) {
示例#12
0
namespace Kahlan\Spec\Suite\Matcher;

use Kahlan\Jit\Interceptor;
use Kahlan\Jit\Patcher\Pointcut;
use Kahlan\Matcher\ToReceiveNext;
use Kahlan\Spec\Fixture\Plugin\Pointcut\Foo;
describe("toReceiveNext", function () {
    describe("::match()", function () {
        /**
         * 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);
        });
        it("expects called methods to be called in a defined order", function () {
            $foo = new Foo();
            expect($foo)->toReceive('message');
            expect($foo)->toReceiveNext('::version');
            expect($foo)->toReceiveNext('bar');
            $foo->message();
<?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');
        });
    });
});
示例#14
0
namespace Kahlan\Spec\Jit\Suite;

use Kahlan\Dir\Dir;
use Kahlan\Jit\JitException;
use Kahlan\Jit\Patchers;
use Kahlan\Jit\Interceptor;
use Kahlan\Plugin\Stub;
use Kahlan\Spec\Proxy\Autoloader;
use Kahlan\Spec\Mock\Patcher;
describe("Interceptor", function () {
    before(function () {
        $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 () {
示例#15
0
 //   });
 //   describe('Record', function () {
 //     xit('TODO', function ($db) {});
 //   });
 //   describe('Result', function () {
 //     xit('TODO', function ($db) {});
 //   });
 //   describe('Table', function () {
 //     xit('TODO', function ($db) {});
 //   });
 // });
 describe('Helpers', function () {
     describe('hydrate()', function () {
         before(function ($db) {
             $db->reset()->create('a', array('id' => 'primary_key', 'x' => 'integer'));
             $db->a->insert(array('x' => 123));
             $db->a->insert(array('x' => 456));
             let('a', $db->a);
         });
         it('should has consistency', function ($a) {
             expect($a->count())->toEqual(2);
             expect($a->all())->toBeArray();
         });
         describe('columns', function () {
             it('should be able to migrate', function ($a) {
                 \Grocery\Helpers::hydrate($a, array('x' => 'string'));
                 $b = $a->columns();
                 expect($b['x']['type'])->toEqual('string');
             });
             it('should maintain consistency', function ($a) {
                 $test = $a->all();
                 expect($test[0]->x)->toEqual(123);
示例#16
0
        return;
    }
}
describe('AbstractReporter', function () {
    $console = new Console(array(), 'php://output');
    $console->parseArguments();
    $reporter = new MockReporter($console);
    $printContents = null;
    context('afterRun', function () use(&$reporter, &$printContents) {
        before(function () use(&$reporter, &$printContents) {
            // Add a spec and run corresponding reporter hooks
            $suite = new Suite('test', function () {
            });
            $spec = new Spec('testspec', function () {
            }, $suite);
            $reporter->beforeSpec($spec);
            $reporter->afterSpec($spec);
            ob_start();
            $reporter->afterRun();
            $printContents = ob_get_contents();
            ob_end_clean();
        });
        it('prints the running time', function () use(&$printContents) {
            // TODO: Update once pattern matching is added
            $print = $printContents;
            expect($print)->toContain('Finished in');
            expect($print)->toContain('seconds');
        });
        it('prints the number of specs and failures', function () use(&$printContents) {
            expect($printContents)->toContain('1 spec, 0 failures');
        });
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;
}
示例#18
0
function find_route($method, $route, \Closure $callback)
{
    if ($_SERVER['REQUEST_METHOD'] === $method) {
        if (!empty($_SERVER['QUERY_STRING'])) {
            $url = substr($_SERVER['REQUEST_URI'], 0, -(strlen($_SERVER['QUERY_STRING']) + 1));
        } else {
            $url = $_SERVER['REQUEST_URI'];
        }
        $params = array();
        if (url_match($route, $url, $params)) {
            before($route);
            \call_user_func_array($callback, $params);
            exit;
        }
    }
}
示例#19
0
<?php

/*
 * Created by IntelliJ IDEA.
 * User: EgaLabs (c) 2015
 * Date: 26/05/2015
 * Time: 20:23
 */
namespace Matura\Tests\Hashing;

use Ignizr\URI\HTTPScheme;
global $uri;
$uri = "https://www.egalabs.io/register?to=http%3A%2F%2Fcdn.egalabs.io%2Fwelcome#who-we-are";
before(function ($ctx) use($uri) {
    $ctx->uri = $uri;
    $ctx->http_scheme = new HTTPScheme($uri);
});
示例#20
0
        before(function ($ctx) {
            $ctx->test = $ctx->suite->find('Suite:Fixture:TestMethod');
        });
        it('should be a TestMethod', function ($ctx) {
            expect($ctx->test)->to->be->a('Matura\\Blocks\\Methods\\TestMethod');
        });
        it('should have the correct parent Block', function ($ctx) {
            expect($ctx->test->parentBlock())->to->be->a('Matura\\Blocks\\Describe');
        });
    });
    describe('BeforeHook', function ($ctx) {
        before(function ($ctx) {
            $ctx->describe = $ctx->suite->find('Suite:Fixture');
        });
        it('should have 1 BeforeHook', function ($ctx) {
            $befores = $ctx->describe->befores();
            expect($befores)->to->have->length(1);
            expect($befores[0])->to->be->a('Matura\\Blocks\\Methods\\BeforeHook');
        });
    });
    describe('BeforeAllHook', function ($ctx) {
        before(function ($ctx) {
            $ctx->describe = $ctx->suite->find('Suite:Fixture');
        });
        it('should have 1 BeforeAllHook', function ($ctx) {
            $before_alls = $ctx->describe->beforeAlls();
            expect($before_alls)->to->have->length(1);
            expect($before_alls[0])->to->be->a('Matura\\Blocks\\Methods\\BeforeAllHook');
        });
    });
});
示例#21
0
<?php

namespace Matura\Tests;

require 'vendor/autoload.php';
require 'day/4.php';
use AoC\Day;
describe('AoC Day 4', function ($ctx) {
    $ctx->tests = array("bgvyzdsv" => array(254575, 1038736));
    before(function ($ctx) {
        $ctx->Day = new Day();
    });
    foreach (array_keys($ctx->tests) as $case) {
        $expected = $ctx->tests[$case];
        it('should correctly solve "' . $case . '"', function ($ctx) use($case, $expected) {
            expect($ctx->Day->solve($case))->to->equal($expected);
        });
    }
});
示例#22
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);
}
示例#23
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');
function between($this, $that, $inthat)
{
    return before($that, after($this, $inthat));
}
示例#25
0
             });
             $stub::generateAbstractMethods('some\\unexisting\\Class');
         })->toThrow(new IncompleteException('Unexisting parent class `some\\unexisting\\Class`'));
     });
 });
 describe("::create()", function () {
     before(function () {
         $this->is_method_exists = function ($instance, $method, $type = "public") {
             if (!method_exists($instance, $method)) {
                 return false;
             }
             $refl = new ReflectionMethod($instance, $method);
             switch ($type) {
                 case "static":
                     return $refl->isStatic();
                     break;
                 case "public":
                     return $refl->isPublic();
                     break;
                 case "private":
                     return $refl->isPrivate();
                     break;
             }
             return false;
         };
     });
     it("stubs an instance", function () {
         $stub = Stub::create();
         expect(is_object($stub))->toBe(true);
         expect(get_class($stub))->toMatch("/^Kahlan\\\\Spec\\\\Plugin\\\\Stub\\\\Stub\\d+\$/");
     });
     it("names a stub instance", function () {
示例#26
0
<?php

belongs_to('predicate', array('model_name' => 'Tag'));
belongs_to('consequent', array('model_name' => 'Tag'));
before('create', 'validate_uniqueness');
class TagImplication extends ActiveRecord
{
    function validate_uniqueness()
    {
        $this->predicate_is($this->predicate);
        $this->consequent_is($this->consequent);
        if (self::find('first', array('conditions' => array("(predicate_id = ? AND consequent_id = ?) OR (predicate_id = ? AND consequent_id = ?)", $this->predicate_id, $this->consequent_id, $this->consequent_id, $this->predicate_id)))) {
            $this->record_errors->add_to_base("Tag implication already exists");
            return false;
        }
    }
    function predicate_is($name)
    {
        $t = Tag::find_or_create_by_name($name);
        $this->predicate_id = $t->id;
    }
    function consequent_is($name)
    {
        $t = Tag::find_or_create_by_name($name);
        $this->consequent_id = $t->id;
    }
    function destroy_and_notify($current_user, $reason)
    {
        # TODO:
        if (!empty($this->creator_id) && $this->creator_id != $current_user->id) {
            // msg = "A tag implication you submitted (#{predicate.name} &rarr; #{consequent.name}) was deleted for the following reason: #{reason}."
示例#27
0
function test(\Closure $function)
{
    before();
    $function();
}
示例#28
0
<?php

namespace Kahlan\Spec\Suite\Analysis;

use Kahlan\Analysis\Inspector;
describe("Inspector", function () {
    before(function () {
        $this->class = 'Kahlan\\Spec\\Fixture\\Analysis\\SampleClass';
    });
    describe('::inspect()', function () {
        it("gets the reflexion layer of a class", function () {
            $inspector = Inspector::inspect($this->class);
            expect($inspector)->toBeAnInstanceOf('ReflectionClass');
            expect($inspector->name)->toBe($this->class);
        });
    });
    describe('::parameters()', function () {
        it("gets method's parameters details", function () {
            $inspector = Inspector::parameters($this->class, 'parametersExample');
            expect($inspector)->toBeA('array');
            $param2 = next($inspector);
            expect($param2)->toBeAnInstanceOf('ReflectionParameter');
            expect($param2->getName())->toBe('b');
            expect($param2->getDefaultValue())->toBe(100);
            $param3 = next($inspector);
            expect($param3)->toBeAnInstanceOf('ReflectionParameter');
            expect($param3->getName())->toBe('c');
            expect($param3->getDefaultValue())->toBe('abc');
            $param4 = next($inspector);
            expect($param4)->toBeAnInstanceOf('ReflectionParameter');
            expect($param4->getName())->toBe('d');
<?php

use kahlan\Arg;
use kahlan\plugin\Stub;
use Sofa\Searchable\Query;
use Sofa\Searchable\Parser;
use Sofa\Searchable\Searchable;
use Illuminate\Database\Connection;
use Illuminate\Database\Query\Builder;
describe('Searchable Query Builder', function () {
    before(function () {
        (new Searchable(new Parser()))->boot();
    });
    given('query', function () {
        $connection = Stub::create(['extends' => Connection::class, 'methods' => ['__construct']]);
        $grammar = new Illuminate\Database\Query\Grammars\MySqlGrammar();
        $processor = new Illuminate\Database\Query\Processors\MySqlProcessor();
        return (new Builder($connection, $grammar, $processor))->from('users');
    });
    it('replaces query with custom implementation on call', function () {
        expect($this->query)->toBeAnInstanceOf(Builder::class);
        expect($this->query->search('word', ['column']))->toBeAnInstanceOf(Query::class);
    });
    it('adds basic SELECT, WHERE and GROUP BY clauses', function () {
        $sql = 'select * from (select `users`.*, max(case when `users`.`name` = ? then 15 else 0 end) as relevance ' . 'from `users` where (`users`.`name` like ?) group by `users`.`id`) as `users` ' . 'where `relevance` >= 1 order by `relevance` desc';
        $query = $this->query->search('Jarek', ['name'], false, 1);
        expect($query->toSql())->toBe($sql);
        expect($query->toBase()->getBindings())->toBe(['Jarek', 'Jarek']);
    });
    it('splits string into separate keywords and adds valid clauses for multiple columns', function () {
        $sql = 'select * from (select `users`.*, max(case when `users`.`first_name` = ? or `users`.`first_name` = ? then 15 else 0 end ' . '+ case when `users`.`last_name` = ? or `users`.`last_name` = ? then 30 else 0 end) as relevance from `users` ' . 'where (`users`.`first_name` like ? or `users`.`first_name` like ? or `users`.`last_name` like ? or `users`.`last_name` like ?) ' . 'group by `users`.`id`) as `users` where `relevance` >= 0.75 order by `relevance` desc';
示例#30
0
use Kahlan\Plugin\Stub;
use Teazee\Exception\ChainNoResult;
use Teazee\Provider\Chain;
use Teazee\Provider\Provider;
use Teazee\ZoneInfo;
describe(Chain::class, function () {
    it('is a ' . Provider::class, function () {
        expect(new Chain())->toBeAnInstanceOf(Provider::class);
    });
    it('->getName()', function () {
        expect((new Chain())->getName())->toBe('chain');
    });
    context('->find()', function () {
        before(function () {
            $this->lat = 40.1146914;
            $this->lng = -88.3121289;
        });
        context('without providers', function () {
            it('throws an exception', function () {
                expect(function () {
                    $chain = new Chain();
                    $chain->find($this->lat, $this->lng);
                })->toThrow();
            });
        });
        context('with multiple providers', function () {
            beforeEach(function () {
                $this->time = time();
                $this->p1 = Stub::create();
                Stub::on($this->p1)->method('find', function ($lat, $lng, $timestamp = null) {
                    return new ZoneInfo('America/Chicago', $timestamp);