code
stringlengths
31
1.39M
docstring
stringlengths
23
16.8k
func_name
stringlengths
1
126
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
166
url
stringlengths
50
220
license
stringclasses
7 values
public function addMatchTypes(array $matchTypes) { $this->matchTypes = array_merge($this->matchTypes, $matchTypes); }
Add named match types. It uses array_merge so keys can be overwritten. @param array $matchTypes The key is the name and the value is the regex.
addMatchTypes
php
dannyvankooten/AltoRouter
AltoRouter.php
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
MIT
public function map(string $method, string $route, $target, ?string $name = null) { $this->routes[] = [$method, $route, $target, $name]; if ($name) { if (isset($this->namedRoutes[$name])) { throw new RuntimeException("Can not redeclare route '{$name}'"); } $this->namedRoutes[$name] = $route; } }
Map a route to a target @param string $method One of 5 HTTP Methods, or a pipe-separated list of multiple HTTP Methods (GET|POST|PATCH|PUT|DELETE) @param string $route The route regex, custom regex must start with an @. You can use multiple pre-set regex filters, like [i:id] @param mixed $target The target where this route should point to. Can be anything. @param string $name Optional name of this route. Supply if you want to reverse route this url in your application. @throws Exception
map
php
dannyvankooten/AltoRouter
AltoRouter.php
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
MIT
public function generate(string $routeName, array $params = []): string { // Check if named route exists if (!isset($this->namedRoutes[$routeName])) { throw new RuntimeException("Route '{$routeName}' does not exist."); } // Replace named parameters $route = $this->namedRoutes[$routeName]; // prepend base path to route url again $url = $this->basePath . $route; if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) { foreach ($matches as $index => $match) { list($block, $pre, $type, $param, $optional) = $match; if ($pre) { $block = substr($block, 1); } if (isset($params[$param])) { // Part is found, replace for param value $url = str_replace($block, $params[$param], $url); } elseif ($optional && $index !== 0) { // Only strip preceding slash if it's not at the base $url = str_replace($pre . $block, '', $url); } else { // Strip match block $url = str_replace($block, '', $url); } } } return $url; }
Reversed routing Generate the URL for a named route. Replace regexes with supplied parameters @param string $routeName The name of the route. @param array $params Associative array of parameters to replace placeholders with. @return string The URL of the route with named parameters in place. @throws Exception
generate
php
dannyvankooten/AltoRouter
AltoRouter.php
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
MIT
public function match(?string $requestUrl = null, ?string $requestMethod = null) { $params = []; // set Request Url if it isn't passed as parameter if ($requestUrl === null) { $requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'; } // strip base path from request url $requestUrl = substr($requestUrl, strlen($this->basePath)); // Strip query string (?a=b) from Request Url if (($strpos = strpos($requestUrl, '?')) !== false) { $requestUrl = substr($requestUrl, 0, $strpos); } $lastRequestUrlChar = $requestUrl ? $requestUrl[strlen($requestUrl) - 1] : ''; // set Request Method if it isn't passed as a parameter if ($requestMethod === null) { $requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET'; } foreach ($this->routes as $handler) { list($methods, $route, $target, $name) = $handler; $method_match = (stripos($methods, $requestMethod) !== false); // Method did not match, continue to next route. if (!$method_match) { continue; } if ($route === '*') { // * wildcard (matches all) $match = true; } elseif (isset($route[0]) && $route[0] === '@') { // @ regex delimiter $pattern = '`' . substr($route, 1) . '`u'; $match = preg_match($pattern, $requestUrl, $params) === 1; } elseif (($position = strpos($route, '[')) === false) { // No params in url, do string comparison $match = strcmp($requestUrl, $route) === 0; } else { // Compare longest non-param string with url before moving on to regex // Check if last character before param is a slash, because it could be optional if param is optional too (see https://github.com/dannyvankooten/AltoRouter/issues/241) if (strncmp($requestUrl, $route, $position) !== 0 && ($lastRequestUrlChar === '/' || $route[$position - 1] !== '/')) { continue; } $regex = $this->compileRoute($route); $match = preg_match($regex, $requestUrl, $params) === 1; } if ($match) { if ($params) { foreach ($params as $key => $value) { if (is_numeric($key)) { unset($params[$key]); } } } return [ 'target' => $target, 'params' => $params, 'name' => $name ]; } } return false; }
Match a given Request Url against stored routes @param string $requestUrl @param string $requestMethod @return array|boolean Array with route information on success, false on failure (no match).
match
php
dannyvankooten/AltoRouter
AltoRouter.php
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
MIT
protected function compileRoute(string $route): string { if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) { $matchTypes = $this->matchTypes; foreach ($matches as $match) { list($block, $pre, $type, $param, $optional) = $match; if (isset($matchTypes[$type])) { $type = $matchTypes[$type]; } if ($pre === '.') { $pre = '\.'; } $optional = $optional !== '' ? '?' : null; //Older versions of PCRE require the 'P' in (?P<named>) $pattern = '(?:' . ($pre !== '' ? $pre : null) . '(' . ($param !== '' ? "?P<$param>" : null) . $type . ')' . $optional . ')' . $optional; $route = str_replace($block, $pattern, $route); } } return "`^$route$`u"; }
Compile the regex for a given route (EXPENSIVE) @param string $route @return string
compileRoute
php
dannyvankooten/AltoRouter
AltoRouter.php
https://github.com/dannyvankooten/AltoRouter/blob/master/AltoRouter.php
MIT
protected function setUp() : void { $this->router = new AltoRouterDebug; }
Sets up the fixture, for example, opens a network connection. This method is called before a test is executed.
setUp
php
dannyvankooten/AltoRouter
tests/AltoRouterTest.php
https://github.com/dannyvankooten/AltoRouter/blob/master/tests/AltoRouterTest.php
MIT
public function testMatch() { $this->router->map('GET', '/foo/[:controller]/[:action]', 'foo_action', 'foo_route'); $this->assertEquals([ 'target' => 'foo_action', 'params' => [ 'controller' => 'test', 'action' => 'do' ], 'name' => 'foo_route' ], $this->router->match('/foo/test/do', 'GET')); $this->assertFalse($this->router->match('/foo/test/do', 'POST')); $this->assertEquals([ 'target' => 'foo_action', 'params' => [ 'controller' => 'test', 'action' => 'do' ], 'name' => 'foo_route' ], $this->router->match('/foo/test/do?param=value', 'GET')); }
@covers AltoRouter::match @covers AltoRouter::compileRoute
testMatch
php
dannyvankooten/AltoRouter
tests/AltoRouterTest.php
https://github.com/dannyvankooten/AltoRouter/blob/master/tests/AltoRouterTest.php
MIT
public function __construct() { $this->middleware('auth'); }
Create a new controller instance. @return void
__construct
php
ploi/roadmap
app/Http/Controllers/Auth/ConfirmPasswordController.php
https://github.com/ploi/roadmap/blob/master/app/Http/Controllers/Auth/ConfirmPasswordController.php
MIT
protected function redirectTo($request) { if (! $request->expectsJson()) { return route('login'); } }
Get the path the user should be redirected to when they are not authenticated. @param \Illuminate\Http\Request $request @return string|null
redirectTo
php
ploi/roadmap
app/Http/Middleware/Authenticate.php
https://github.com/ploi/roadmap/blob/master/app/Http/Middleware/Authenticate.php
MIT
public function handle(Request $request, Closure $next) { if (auth()->check()) { app()->setLocale(auth()->user()->locale ?? config('app.locale')); } return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
handle
php
ploi/roadmap
app/Http/Middleware/Localize.php
https://github.com/ploi/roadmap/blob/master/app/Http/Middleware/Localize.php
MIT
public function handle(Request $request, Closure $next) { if (auth()->check()) { Carbon::setLocale(auth()->user()->date_locale ?? config('app.locale')); } return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
handle
php
ploi/roadmap
app/Http/Middleware/LocalizeDates.php
https://github.com/ploi/roadmap/blob/master/app/Http/Middleware/LocalizeDates.php
MIT
public function handle(Request $request, Closure $next, ...$guards) { $guards = empty($guards) ? [null] : $guards; foreach ($guards as $guard) { if (Auth::guard($guard)->check()) { return redirect(RouteServiceProvider::HOME); } } return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next @param string|null ...$guards @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
handle
php
ploi/roadmap
app/Http/Middleware/RedirectIfAuthenticated.php
https://github.com/ploi/roadmap/blob/master/app/Http/Middleware/RedirectIfAuthenticated.php
MIT
public function hosts() { return [ $this->allSubdomainsOfApplicationUrl(), ]; }
Get the host patterns that should be trusted. @return array<int, string|null>
hosts
php
ploi/roadmap
app/Http/Middleware/TrustHosts.php
https://github.com/ploi/roadmap/blob/master/app/Http/Middleware/TrustHosts.php
MIT
public function mount(Changelog $changelog): void { $this->changelog = $changelog; $this->votes = $changelog->votes; }
Mount the component. @param Changelog $changelog The Changelog instance to be mounted. @return void
mount
php
ploi/roadmap
app/Livewire/Changelog/Vote.php
https://github.com/ploi/roadmap/blob/master/app/Livewire/Changelog/Vote.php
MIT
public function vote(): void { $this->changelog->toggleUpvote(auth()->user()); $this->votes = $this->changelog->votes; }
Toggles the vote for the authenticated user on the changelog. Updates the votes count on the changelog. @return void
vote
php
ploi/roadmap
app/Livewire/Changelog/Vote.php
https://github.com/ploi/roadmap/blob/master/app/Livewire/Changelog/Vote.php
MIT
public function render(): View { return view( 'livewire.changelog.vote', [ 'changelog' => $this->changelog, 'votes' => $this->votes, ] ); }
Render the component. @return \Illuminate\View\View
render
php
ploi/roadmap
app/Livewire/Changelog/Vote.php
https://github.com/ploi/roadmap/blob/master/app/Livewire/Changelog/Vote.php
MIT
public function boot() { Broadcast::routes(); require base_path('routes/channels.php'); }
Bootstrap any application services. @return void
boot
php
ploi/roadmap
app/Providers/BroadcastServiceProvider.php
https://github.com/ploi/roadmap/blob/master/app/Providers/BroadcastServiceProvider.php
MIT
public function boot() { // }
Register any events for your application. @return void
boot
php
ploi/roadmap
app/Providers/EventServiceProvider.php
https://github.com/ploi/roadmap/blob/master/app/Providers/EventServiceProvider.php
MIT
public function shouldDiscoverEvents() { return false; }
Determine if events and listeners should be automatically discovered. @return bool
shouldDiscoverEvents
php
ploi/roadmap
app/Providers/EventServiceProvider.php
https://github.com/ploi/roadmap/blob/master/app/Providers/EventServiceProvider.php
MIT
public function register() { foreach (glob(app_path('Helpers') . '/*.php') as $file) { require_once $file; } }
Register the application services. @return void
register
php
ploi/roadmap
app/Providers/HelperServiceProvider.php
https://github.com/ploi/roadmap/blob/master/app/Providers/HelperServiceProvider.php
MIT
public function boot() { $this->configureRateLimiting(); $this->routes(function () { Route::middleware('api') ->prefix('api') ->group(base_path('routes/api.php')); Route::middleware('web') ->group(base_path('routes/web.php')); }); }
Define your route model bindings, pattern filters, etc. @return void
boot
php
ploi/roadmap
app/Providers/RouteServiceProvider.php
https://github.com/ploi/roadmap/blob/master/app/Providers/RouteServiceProvider.php
MIT
public function getRecentVoterDetails(int $count = 5): Collection|\Illuminate\Support\Collection { return $this->votes() ->with('user') ->orderBy('created_at', 'desc') ->take($count) ->get() ->map(function ($vote) { return [ 'name' => $vote->user->name, 'avatar' => $vote->user->getGravatar('50'), ]; }); }
Returns a collection of the most recent users who have voted for this item. @param int $count Displays five users by default. @return Collection|\Illuminate\Support\Collection
getRecentVoterDetails
php
ploi/roadmap
app/Traits/HasUpvote.php
https://github.com/ploi/roadmap/blob/master/app/Traits/HasUpvote.php
MIT
public function render() { $tw = new Tailwind('brand', app(\App\Settings\ColorSettings::class)->primary); $this->brandColors = $tw->getCssFormat(); $tw = new Tailwind('primary', app(\App\Settings\ColorSettings::class)->primary); $this->primaryColors = str($tw->getCssFormat())->replace('color-', ''); $fontFamily = app(\App\Settings\ColorSettings::class)->fontFamily ?? "Nunito"; $this->fontFamily = [ 'cssValue' => $fontFamily, 'urlValue' => Str::snake($fontFamily, '-') ]; $this->logo = app(\App\Settings\ColorSettings::class)->logo; $this->userNeedsToVerify = app(GeneralSettings::class)->users_must_verify_email && auth()->check() && !auth()->user()->hasVerifiedEmail(); return view('components.app'); }
Get the view / contents that represent the component. @return \Illuminate\Contracts\View\View|\Closure|string
render
php
ploi/roadmap
app/View/Components/App.php
https://github.com/ploi/roadmap/blob/master/app/View/Components/App.php
MIT
public function render(): View|Closure|string { return view('components.theme-toggle'); }
Get the view / contents that represent the component.
render
php
ploi/roadmap
app/View/Components/ThemeToggle.php
https://github.com/ploi/roadmap/blob/master/app/View/Components/ThemeToggle.php
MIT
public function definition() { return [ 'title' => ucfirst($this->faker->domainWord), 'slug' => $this->faker->word, 'can_users_create' => true, ]; }
Define the model's default state. @return array<string, mixed>
definition
php
ploi/roadmap
database/factories/BoardFactory.php
https://github.com/ploi/roadmap/blob/master/database/factories/BoardFactory.php
MIT
public function definition() { return [ 'title' => $this->faker->words(3, true), 'slug' => $this->faker->word, 'content' => $this->faker->paragraphs(3, true), ]; }
Define the model's default state. @return array<string, mixed>
definition
php
ploi/roadmap
database/factories/ChangelogFactory.php
https://github.com/ploi/roadmap/blob/master/database/factories/ChangelogFactory.php
MIT
public function definition() { return [ 'content' => $this->faker->text(200) ]; }
Define the model's default state. @return array<string, mixed>
definition
php
ploi/roadmap
database/factories/CommentFactory.php
https://github.com/ploi/roadmap/blob/master/database/factories/CommentFactory.php
MIT
public function definition() { return [ 'title' => ucfirst($this->faker->domainWord), 'content' => $this->faker->text(500), 'slug' => $this->faker->word, 'private' => false, ]; }
Define the model's default state. @return array<string, mixed>
definition
php
ploi/roadmap
database/factories/ItemFactory.php
https://github.com/ploi/roadmap/blob/master/database/factories/ItemFactory.php
MIT
public function definition() { return [ 'title' => ucfirst($this->faker->domainWord), 'slug' => $this->faker->word, 'private' => false, ]; }
Define the model's default state. @return array<string, mixed>
definition
php
ploi/roadmap
database/factories/ProjectFactory.php
https://github.com/ploi/roadmap/blob/master/database/factories/ProjectFactory.php
MIT
public function definition() { return [ 'name' => $this->faker->name(), 'email' => $this->faker->unique()->safeEmail(), 'email_verified_at' => now(), 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 'remember_token' => Str::random(10), ]; }
Define the model's default state. @return array<string, mixed>
definition
php
ploi/roadmap
database/factories/UserFactory.php
https://github.com/ploi/roadmap/blob/master/database/factories/UserFactory.php
MIT
public function unverified() { return $this->state(function (array $attributes) { return [ 'email_verified_at' => null, ]; }); }
Indicate that the model's email address should be unverified. @return static
unverified
php
ploi/roadmap
database/factories/UserFactory.php
https://github.com/ploi/roadmap/blob/master/database/factories/UserFactory.php
MIT
public function admin() { return $this->state(function (array $attributes) { return [ 'role' => UserRole::Admin ]; }); }
Indicate that the users's role should be admin. @return static
admin
php
ploi/roadmap
database/factories/UserFactory.php
https://github.com/ploi/roadmap/blob/master/database/factories/UserFactory.php
MIT
public function definition() { return [ 'name' => $this->faker->firstName ]; }
Define the model's default state. @return array<string, mixed>
definition
php
ploi/roadmap
database/factories/UserSocialFactory.php
https://github.com/ploi/roadmap/blob/master/database/factories/UserSocialFactory.php
MIT
public function definition() { return [ // ]; }
Define the model's default state. @return array<string, mixed>
definition
php
ploi/roadmap
database/factories/VoteFactory.php
https://github.com/ploi/roadmap/blob/master/database/factories/VoteFactory.php
MIT
public function run() { // \App\Models\User::factory(10)->create(); }
Seed the application's database. @return void
run
php
ploi/roadmap
database/seeders/DatabaseSeeder.php
https://github.com/ploi/roadmap/blob/master/database/seeders/DatabaseSeeder.php
MIT
public function createApplication() { $app = require __DIR__.'/../bootstrap/app.php'; $app->make(Kernel::class)->bootstrap(); return $app; }
Creates the application. @return \Illuminate\Foundation\Application
createApplication
php
ploi/roadmap
tests/CreatesApplication.php
https://github.com/ploi/roadmap/blob/master/tests/CreatesApplication.php
MIT
public function dispatch($request, $response) { $method = $request->server['request_method'] ?? 'GET'; $uri = $request->server['request_uri'] ?? '/'; $routeInfo = self::$dispatcher->dispatch($method, $uri); switch ($routeInfo[0]) { case Dispatcher::NOT_FOUND: return $this->defaultRouter($request, $response, $uri); case Dispatcher::METHOD_NOT_ALLOWED: $response->status(405); return $response->end(); case Dispatcher::FOUND: $handler = $routeInfo[1]; $vars = $routeInfo[2]; if (is_string($handler)) { $handler = explode('@', $handler); if (count($handler) != 2) { throw new RuntimeException("Route {$uri} config error, Only @ are supported"); } $className = $handler[0]; $func = $handler[1]; if (! class_exists($className)) { throw new RuntimeException("Route {$uri} defined '{$className}' Class Not Found"); } $controller = new $className(); if (! method_exists($controller, $func)) { throw new RuntimeException("Route {$uri} defined '{$func}' Method Not Found"); } $middlewareHandler = function ($request, $response, $vars) use ($controller, $func) { return $controller->{$func}($request, $response, $vars ?? null); }; $middleware = 'middleware'; if (property_exists($controller, $middleware)) { $classMiddlewares = $controller->{$middleware}['__construct'] ?? []; $methodMiddlewares = $controller->{$middleware}[$func] ?? []; $middlewares = array_merge($classMiddlewares, $methodMiddlewares); if ($middlewares) { $middlewareHandler = $this->packMiddleware($middlewareHandler, array_reverse($middlewares)); } } return $middlewareHandler($request, $response, $vars ?? null); } if (is_callable($handler)) { return call_user_func_array($handler, [$request, $response, $vars ?? null]); } throw new RuntimeException("Route {$uri} config error"); default: $response->status(400); return $response->end(); } }
@param $request @param $response @throws \Exception @return mixed|void
dispatch
php
simple-swoole/simps
src/Route.php
https://github.com/simple-swoole/simps/blob/master/src/Route.php
Apache-2.0
public function defaultRouter($request, $response, $uri) { $uri = trim($uri, '/'); $uri = explode('/', $uri); if ($uri[0] === '') { $className = '\\App\\Controller\\IndexController'; if (class_exists($className) && method_exists($className, 'index')) { return (new $className())->index($request, $response); } } $response->status(404); return $response->end(); }
@param $request @param $response @param $uri
defaultRouter
php
simple-swoole/simps
src/Route.php
https://github.com/simple-swoole/simps/blob/master/src/Route.php
Apache-2.0
public function packMiddleware($handler, $middlewares = []) { foreach ($middlewares as $middleware) { $handler = $middleware($handler); } return $handler; }
@param $handler @param array $middlewares @return mixed
packMiddleware
php
simple-swoole/simps
src/Route.php
https://github.com/simple-swoole/simps/blob/master/src/Route.php
Apache-2.0
public static function build($body = '', $status = 200, array $headers = []) { $reason = static::$_phrases[$status]; $body_len = \strlen($body); $version = static::$_version; if (empty($headers)) { return "HTTP/{$version} {$status} {$reason}\r\nServer: simps-http-server\r\nContent-Type: text/html;charset=utf-8\r\nContent-Length: {$body_len}\r\nConnection: keep-alive\r\n\r\n{$body}"; } $head = "HTTP/{$version} {$status} {$reason}\r\n"; $headers = $headers; if (! isset($headers['Server'])) { $head .= "Server: simps-http-server\r\n"; } foreach ($headers as $name => $value) { if (\is_array($value)) { foreach ($value as $item) { $head .= "{$name}: {$item}\r\n"; } continue; } $head .= "{$name}: {$value}\r\n"; } if (! isset($headers['Connection'])) { $head .= "Connection: keep-alive\r\n"; } if (! isset($headers['Content-Type'])) { $head .= "Content-Type: text/html;charset=utf-8\r\n"; } else { if ($headers['Content-Type'] === 'text/event-stream') { return $head . $body; } } if (! isset($headers['Transfer-Encoding'])) { $head .= "Content-Length: {$body_len}\r\n\r\n"; } else { return "{$head}\r\n" . dechex($body_len) . "\r\n{$body}\r\n"; } return $head . $body; }
@param string $body @param int $status @return string
build
php
simple-swoole/simps
src/Server/Protocol/HTTP/SimpleResponse.php
https://github.com/simple-swoole/simps/blob/master/src/Server/Protocol/HTTP/SimpleResponse.php
Apache-2.0
public function dispatch($server, $fd, $data) { $first_line = \strstr($data, "\r\n", true); $tmp = \explode(' ', $first_line, 3); $method = $tmp[0] ?? 'GET'; $uri = $tmp[1] ?? '/'; $routeInfo = self::$dispatcher->dispatch($method, $uri); switch ($routeInfo[0]) { // Dispatcher::FOUND case 1: $handler = $routeInfo[1]; $vars = $routeInfo[2]; if (isset(self::$cache[$handler])) { $cache_entity = self::$cache[$handler]; return $cache_entity[0]->{$cache_entity[1]}($server, $fd, $vars ?? null); } if (is_string($handler)) { $handlerArr = explode('@', $handler); if (count($handlerArr) != 2) { throw new RuntimeException("Route {$uri} config error, Only @ are supported"); } $className = $handlerArr[0]; $func = $handlerArr[1]; if (! class_exists($className)) { throw new RuntimeException("Route {$uri} defined '{$className}' Class Not Found"); } $controller = new $className(); if (! method_exists($controller, $func)) { throw new RuntimeException("Route {$uri} defined '{$func}' Method Not Found"); } self::$cache[$handler] = [$controller, $func]; return $controller->{$func}($server, $fd, $vars ?? null); } if (is_callable($handler)) { return call_user_func_array($handler, [$server, $fd, $vars ?? null]); } throw new RuntimeException("Route {$uri} config error"); break; case Dispatcher::NOT_FOUND: return $this->defaultRouter($server, $fd, $uri); break; case Dispatcher::METHOD_NOT_ALLOWED: return $server->send($fd, SimpleResponse::build('', 405)); // throw new RuntimeException('Request Method Not Allowed', 405); break; default: return $server->send($fd, SimpleResponse::build('', 400)); } throw new RuntimeException("Undefined Route {$uri}"); }
@param $server @param $fd @param $data @throws \Exception @return mixed
dispatch
php
simple-swoole/simps
src/Server/Protocol/HTTP/SimpleRoute.php
https://github.com/simple-swoole/simps/blob/master/src/Server/Protocol/HTTP/SimpleRoute.php
Apache-2.0
public function defaultRouter($server, $fd, $uri) { $uri = trim($uri, '/'); $uri = explode('/', $uri); if ($uri[0] === '') { $className = '\\App\\Controller\\IndexController'; if (class_exists($className) && method_exists($className, 'index')) { return (new $className())->index($server, $fd); } // throw new RuntimeException('The default route index/index class does not exist', 404); } return $server->send($fd, SimpleResponse::build('', 404)); // throw new RuntimeException('Route Not Found', 404); }
@param $server @param $fd @param $uri @throws \Exception @return mixed
defaultRouter
php
simple-swoole/simps
src/Server/Protocol/HTTP/SimpleRoute.php
https://github.com/simple-swoole/simps/blob/master/src/Server/Protocol/HTTP/SimpleRoute.php
Apache-2.0
public function __construct(array $patterns) { $this->patternOverrides = []; $this->patterns = $patterns; }
Create a new postal code matcher. @param array $patterns @return void
__construct
php
axlon/laravel-postal-code-validation
src/PostalCodeValidator.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/PostalCodeValidator.php
MIT
public function fails(string $countryCode, ?string ...$postalCodes): bool { return !$this->passes($countryCode, ...$postalCodes); }
Determine if the given postal code(s) are invalid for the given country. @param string $countryCode @param string|null ...$postalCodes @return bool
fails
php
axlon/laravel-postal-code-validation
src/PostalCodeValidator.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/PostalCodeValidator.php
MIT
public function override($countryCode, ?string $pattern = null): void { if (is_array($countryCode)) { $this->patternOverrides = array_merge( $this->patternOverrides, array_change_key_case($countryCode, CASE_UPPER) ); } else { $this->patternOverrides[strtoupper($countryCode)] = $pattern; } }
Override pattern matching for the given country. @param array|string $countryCode @param string|null $pattern @return void
override
php
axlon/laravel-postal-code-validation
src/PostalCodeValidator.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/PostalCodeValidator.php
MIT
public function passes(string $countryCode, ?string ...$postalCodes): bool { if (!$this->supports($countryCode)) { return false; } if (($pattern = $this->patternFor($countryCode)) === null) { return true; } foreach ($postalCodes as $postalCode) { if ($postalCode === null || trim($postalCode) === '') { return false; } if (preg_match($pattern, $postalCode) !== 1) { return false; } } return true; }
Determine if the given postal code(s) are valid for the given country. @param string $countryCode @param string|null ...$postalCodes @return bool
passes
php
axlon/laravel-postal-code-validation
src/PostalCodeValidator.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/PostalCodeValidator.php
MIT
public function patternFor(string $countryCode): ?string { $countryCode = strtoupper($countryCode); if (array_key_exists($countryCode, self::ALIASES)) { $countryCode = self::ALIASES[$countryCode]; } return $this->patternOverrides[$countryCode] ?? $this->patterns[$countryCode] ?? null; }
Get the matching pattern for the given country. @param string $countryCode @return string|null
patternFor
php
axlon/laravel-postal-code-validation
src/PostalCodeValidator.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/PostalCodeValidator.php
MIT
public function supports(string $countryCode): bool { $countryCode = strtoupper($countryCode); return array_key_exists($countryCode, $this->patternOverrides) || array_key_exists($countryCode, $this->patterns) || array_key_exists($countryCode, self::ALIASES); }
Determine if a matching pattern exists for the given country. @param string $countryCode @return bool
supports
php
axlon/laravel-postal-code-validation
src/PostalCodeValidator.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/PostalCodeValidator.php
MIT
public function register(): void { if ($this->app->resolved('validator')) { $this->registerRules($this->app['validator']); } else { $this->app->resolving('validator', function (Factory $validator) { $this->registerRules($validator); }); } $this->app->singleton('postal_codes', function () { return new PostalCodeValidator(require __DIR__ . '/../resources/patterns.php'); }); $this->app->alias('postal_codes', PostalCodeValidator::class); }
Register postal code validation services. @return void
register
php
axlon/laravel-postal-code-validation
src/ValidationServiceProvider.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/ValidationServiceProvider.php
MIT
public function registerRules(Factory $validator): void { $validator->extend('postal_code', 'Axlon\PostalCodeValidation\Extensions\PostalCode@validate'); $validator->replacer('postal_code', 'Axlon\PostalCodeValidation\Extensions\PostalCode@replace'); $validator->replacer('postal_code_for', 'Axlon\PostalCodeValidation\Extensions\PostalCodeFor@replace'); $validator->replacer('postal_code_with', 'Axlon\PostalCodeValidation\Extensions\PostalCodeFor@replace'); if (method_exists($validator, 'extendDependent')) { $validator->extendDependent('postal_code_for', 'Axlon\PostalCodeValidation\Extensions\PostalCodeFor@validate'); $validator->extendDependent('postal_code_with', 'Axlon\PostalCodeValidation\Extensions\PostalCodeFor@validate'); } else { $validator->extend('postal_code_for', 'Axlon\PostalCodeValidation\Extensions\PostalCodeFor@validate'); $validator->extend('postal_code_with', 'Axlon\PostalCodeValidation\Extensions\PostalCodeFor@validate'); } }
Register the postal code validation rules with the validator. @param \Illuminate\Contracts\Validation\Factory $validator @return void
registerRules
php
axlon/laravel-postal-code-validation
src/ValidationServiceProvider.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/ValidationServiceProvider.php
MIT
public function __construct(PostalCodeValidator $validator, PostalCodeExamples $examples) { $this->examples = $examples; $this->validator = $validator; }
Create a new PostalCode validator extension. @param \Axlon\PostalCodeValidation\PostalCodeValidator $validator @param \Axlon\PostalCodeValidation\Support\PostalCodeExamples $examples @return void
__construct
php
axlon/laravel-postal-code-validation
src/Extensions/PostalCode.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Extensions/PostalCode.php
MIT
public function replace(string $message, string $attribute, string $rule, array $parameters): string { $countries = []; $examples = []; foreach ($parameters as $parameter) { if (($example = $this->examples->get($parameter)) === null) { continue; } $countries[] = $parameter; $examples[] = $example; } $replacements = [ $attribute, implode(', ', array_unique($countries)), implode(', ', array_unique($examples)), ]; return str_replace([':attribute', ':countries', ':examples'], $replacements, $message); }
Replace error message placeholders. @param string $message @param string $attribute @param string $rule @param string[] $parameters @return string
replace
php
axlon/laravel-postal-code-validation
src/Extensions/PostalCode.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Extensions/PostalCode.php
MIT
public function validate(string $attribute, ?string $value, array $parameters): bool { if (empty($parameters)) { throw new InvalidArgumentException('Validation rule postal_code requires at least 1 parameter.'); } foreach ($parameters as $parameter) { if ($this->validator->passes($parameter, $value)) { return true; } } return false; }
Validate the given attribute. @param string $attribute @param string|null $value @param string[] $parameters @return bool
validate
php
axlon/laravel-postal-code-validation
src/Extensions/PostalCode.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Extensions/PostalCode.php
MIT
public function __construct(PostalCodeValidator $validator, PostalCodeExamples $examples) { $this->examples = $examples; $this->validator = $validator; }
Create a new PostalCodeFor validator extension. @param \Axlon\PostalCodeValidation\PostalCodeValidator $validator @param \Axlon\PostalCodeValidation\Support\PostalCodeExamples $examples @return void
__construct
php
axlon/laravel-postal-code-validation
src/Extensions/PostalCodeFor.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Extensions/PostalCodeFor.php
MIT
public function replace(string $message, string $attribute, string $rule, array $parameters, Validator $validator): string { $countries = []; $examples = []; foreach ($parameters as $parameter) { if (($input = Arr::get($validator->getData(), $parameter)) === null) { continue; } if (($example = $this->examples->get($input)) === null) { continue; } $countries[] = $input; $examples[] = $example; } $replacements = [ $attribute, implode(', ', array_unique($countries)), implode(', ', array_unique($examples)), ]; return str_replace([':attribute', ':countries', ':examples'], $replacements, $message); }
Replace error message placeholders. @param string $message @param string $attribute @param string $rule @param string[] $parameters @param \Illuminate\Validation\Validator $validator @return string
replace
php
axlon/laravel-postal-code-validation
src/Extensions/PostalCodeFor.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Extensions/PostalCodeFor.php
MIT
public function validate(string $attribute, ?string $value, array $parameters, Validator $validator): bool { if (empty($parameters)) { throw new InvalidArgumentException('Validation rule postal_code_with requires at least 1 parameter.'); } $parameters = Arr::only(Arr::dot($validator->getData()), $parameters); if ($parameters === []) { return true; } foreach ($parameters as $parameter) { if ($parameter === null) { continue; } if ($this->validator->passes($parameter, $value)) { return true; } } return false; }
Validate the given attribute. @param string $attribute @param string|null $value @param string[] $parameters @param \Illuminate\Validation\Validator $validator @return bool
validate
php
axlon/laravel-postal-code-validation
src/Extensions/PostalCodeFor.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Extensions/PostalCodeFor.php
MIT
public function __construct(array $parameters, bool $dependant) { $this->dependent = $dependant; $this->parameters = $parameters; }
Create a new postal code validation rule. @param array $parameters @param bool $dependant @return void
__construct
php
axlon/laravel-postal-code-validation
src/Rules/PostalCode.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Rules/PostalCode.php
MIT
public function __toString(): string { return 'postal_code' . ($this->dependent ? '_with:' : ':') . implode(',', $this->parameters); }
Convert the rule to a validation string. @return string
__toString
php
axlon/laravel-postal-code-validation
src/Rules/PostalCode.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Rules/PostalCode.php
MIT
public static function for(string $country): self { return static::forCountry($country); }
Get a postal_code_with constraint builder instance. @param string $country @return static
for
php
axlon/laravel-postal-code-validation
src/Rules/PostalCode.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Rules/PostalCode.php
MIT
public static function forCountry(string ...$parameters): self { return new static($parameters, false); }
Create a new postal code validation rule for given countries. @param string ...$parameters @return static
forCountry
php
axlon/laravel-postal-code-validation
src/Rules/PostalCode.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Rules/PostalCode.php
MIT
public static function forInput(string ...$parameters): self { return new static($parameters, true); }
Create a new postal code validation rule for given inputs. @param string ...$parameters @return static
forInput
php
axlon/laravel-postal-code-validation
src/Rules/PostalCode.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Rules/PostalCode.php
MIT
public function or(string ...$parameters): self { $this->parameters = array_merge($this->parameters, $parameters); return $this; }
Add additional validation parameters to the rule. @param string ...$parameters @return $this
or
php
axlon/laravel-postal-code-validation
src/Rules/PostalCode.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Rules/PostalCode.php
MIT
public static function with(string $field): self { return static::forInput($field); }
Get a postal_code_with constraint builder instance. @param string $field @return static
with
php
axlon/laravel-postal-code-validation
src/Rules/PostalCode.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Rules/PostalCode.php
MIT
public function get(string $countryCode): ?string { if ($this->examples === null) { $this->examples = require __DIR__ . '/../../resources/examples.php'; } return $this->examples[strtoupper($countryCode)] ?? null; }
Get a postal code example for the given country. @param string $countryCode @return string|null
get
php
axlon/laravel-postal-code-validation
src/Support/PostalCodeExamples.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/src/Support/PostalCodeExamples.php
MIT
public function testFacadesProxiesPatternMatcher(): void { $this->assertSame($this->app->make('postal_codes'), PostalCodes::getFacadeRoot()); }
Test if the facade properly proxies the pattern matcher instance. @return void
testFacadesProxiesPatternMatcher
php
axlon/laravel-postal-code-validation
tests/Integration/FacadeTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/FacadeTest.php
MIT
public function testValidationFailsInvalidCountry(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB', 'country' => 'not-a-country'], ['postal_code' => 'postal_code_for:country'] ); $this->assertFalse($validator->passes()); $this->assertContains('validation.postal_code_for', $validator->errors()->all()); }
Test if the 'postal_code_for' rule fails on invalid countries. @return void
testValidationFailsInvalidCountry
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeForTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeForTest.php
MIT
public function testValidationFailsInvalidPostalCode(): void { $validator = $this->app->make('validator')->make( ['postal_code' => 'not-a-postal-code', 'country' => 'NL'], ['postal_code' => 'postal_code_for:country'] ); $this->assertFalse($validator->passes()); $this->assertContains('validation.postal_code_for', $validator->errors()->all()); }
Test if the 'postal_code_for' rule fails invalid input. @return void
testValidationFailsInvalidPostalCode
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeForTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeForTest.php
MIT
public function testValidationFailsNullPostalCode(): void { $validator = $this->app->make('validator')->make( ['postal_code' => null, 'country' => 'DE'], ['postal_code' => 'postal_code_for:country'] ); $this->assertFalse($validator->passes()); $this->assertContains('validation.postal_code_for', $validator->errors()->all()); }
Test if the 'postal_code' rule fails null input. @return void @link https://github.com/axlon/laravel-postal-code-validation/issues/23
testValidationFailsNullPostalCode
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeForTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeForTest.php
MIT
public function testValidationIgnoresMissingFields(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB', 'empty' => '', 'null' => null, 'country' => 'NL'], ['postal_code' => 'postal_code_for:empty,missing,null,country'] ); $this->assertTrue($validator->passes()); $this->assertEmpty($validator->errors()->all()); }
Test if the 'postal_code_for' rule ignores references that aren't present. @return void
testValidationIgnoresMissingFields
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeForTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeForTest.php
MIT
public function testValidationPassesValidPostalCode(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB', 'country' => 'NL'], ['postal_code' => 'postal_code_for:country'] ); $this->assertTrue($validator->passes()); $this->assertEmpty($validator->errors()->all()); }
Test if the 'postal_code_for' rule passes valid input. @return void
testValidationPassesValidPostalCode
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeForTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeForTest.php
MIT
public function testValidationThrowsWithoutParameters(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB'], ['postal_code' => 'postal_code_for'] ); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Validation rule postal_code_with requires at least 1 parameter.'); $validator->validate(); }
Test if an exception is thrown when calling the 'postal_code' rule without arguments. @return void
testValidationThrowsWithoutParameters
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeForTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeForTest.php
MIT
public function testValidationFailsInvalidCountry(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB'], ['postal_code' => 'postal_code:not-a-country'] ); $this->assertFalse($validator->passes()); $this->assertContains('validation.postal_code', $validator->errors()->all()); }
Test if the 'postal_code' rule fails on invalid countries. @return void
testValidationFailsInvalidCountry
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeTest.php
MIT
public function testValidationFailsInvalidPostalCode(): void { $validator = $this->app->make('validator')->make( ['postal_code' => 'not-a-postal-code'], ['postal_code' => 'postal_code:NL'] ); $this->assertFalse($validator->passes()); $this->assertContains('validation.postal_code', $validator->errors()->all()); }
Test if the 'postal_code' rule fails invalid input. @return void
testValidationFailsInvalidPostalCode
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeTest.php
MIT
public function testValidationFailsNullPostalCode(): void { $validator = $this->app->make('validator')->make( ['postal_code' => null], ['postal_code' => 'postal_code:DE'] ); $this->assertFalse($validator->passes()); $this->assertContains('validation.postal_code', $validator->errors()->all()); }
Test if the 'postal_code' rule fails null input. @return void @link https://github.com/axlon/laravel-postal-code-validation/issues/23
testValidationFailsNullPostalCode
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeTest.php
MIT
public function testValidationPassesValidPostalCode(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB'], ['postal_code' => 'postal_code:NL'] ); $this->assertTrue($validator->passes()); $this->assertEmpty($validator->errors()->all()); }
Test if the 'postal_code' rule passes valid input. @return void
testValidationPassesValidPostalCode
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeTest.php
MIT
public function testValidationThrowsWithoutParameters(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB'], ['postal_code' => 'postal_code'] ); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Validation rule postal_code requires at least 1 parameter.'); $validator->validate(); }
Test if an exception is thrown when calling the 'postal_code' rule without arguments. @return void
testValidationThrowsWithoutParameters
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeTest.php
MIT
public function testValidationFailsInvalidCountry(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB', 'country' => 'not-a-country'], ['postal_code' => 'postal_code_with:country'] ); $this->assertFalse($validator->passes()); $this->assertContains('validation.postal_code_with', $validator->errors()->all()); }
Test if the 'postal_code_with' rule fails on invalid countries. @return void
testValidationFailsInvalidCountry
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeWithTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeWithTest.php
MIT
public function testValidationFailsInvalidPostalCode(): void { $validator = $this->app->make('validator')->make( ['postal_code' => 'not-a-postal-code', 'country' => 'NL'], ['postal_code' => 'postal_code_with:country'] ); $this->assertFalse($validator->passes()); $this->assertContains('validation.postal_code_with', $validator->errors()->all()); }
Test if the 'postal_code_with' rule fails invalid input. @return void
testValidationFailsInvalidPostalCode
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeWithTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeWithTest.php
MIT
public function testValidationFailsInvalidPostalCodeInArray(): void { $validator = $this->app->make('validator')->make( ['postal_codes' => ['not-a-postal-code'], 'countries' => ['NL']], ['postal_codes.*' => 'postal_code_with:countries.*'] ); $this->assertFalse($validator->passes()); $this->assertContains('validation.postal_code_with', $validator->errors()->all()); }
Test if the 'postal_code_with' rule fails invalid input. @return void
testValidationFailsInvalidPostalCodeInArray
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeWithTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeWithTest.php
MIT
public function testValidationFailsNullPostalCode(): void { $validator = $this->app->make('validator')->make( ['postal_code' => null, 'country' => 'DE'], ['postal_code' => 'postal_code_with:country'] ); $this->assertFalse($validator->passes()); $this->assertContains('validation.postal_code_with', $validator->errors()->all()); }
Test if the 'postal_code' rule fails null input. @return void @link https://github.com/axlon/laravel-postal-code-validation/issues/23
testValidationFailsNullPostalCode
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeWithTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeWithTest.php
MIT
public function testValidationIgnoresMissingFields(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB', 'empty' => '', 'null' => null, 'country' => 'NL'], ['postal_code' => 'postal_code_with:empty,missing,null,country'] ); $this->assertTrue($validator->passes()); $this->assertEmpty($validator->errors()->all()); }
Test if the 'postal_code_with' rule ignores references that aren't present. @return void
testValidationIgnoresMissingFields
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeWithTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeWithTest.php
MIT
public function testValidationPassesValidPostalCode(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB', 'country' => 'NL'], ['postal_code' => 'postal_code_with:country'] ); $this->assertTrue($validator->passes()); $this->assertEmpty($validator->errors()->all()); }
Test if the 'postal_code_with' rule passes valid input. @return void
testValidationPassesValidPostalCode
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeWithTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeWithTest.php
MIT
public function testValidationPassesValidPostalCodeInArray(): void { $validator = $this->app->make('validator')->make( ['postal_codes' => ['1234 AB'], 'countries' => ['NL']], ['postal_codes.*' => 'postal_code_with:countries.*'] ); $this->assertTrue($validator->passes()); $this->assertEmpty($validator->errors()->all()); }
Test if the 'postal_code_with' rule passes valid input. @return void
testValidationPassesValidPostalCodeInArray
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeWithTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeWithTest.php
MIT
public function testValidationThrowsWithoutParameters(): void { $validator = $this->app->make('validator')->make( ['postal_code' => '1234 AB'], ['postal_code' => 'postal_code_with'] ); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Validation rule postal_code_with requires at least 1 parameter.'); $validator->validate(); }
Test if an exception is thrown when calling the 'postal_code' rule without arguments. @return void
testValidationThrowsWithoutParameters
php
axlon/laravel-postal-code-validation
tests/Integration/PostalCodeWithTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/PostalCodeWithTest.php
MIT
public function testPostalCodeReplacer(): void { $locale = is_callable([$this->app, 'getLocale']) ? $this->app->getLocale() : 'en'; $translator = $this->app->make('translator'); $validator = $this->app->make('validator')->make( ['postal_code' => 'not-a-postal-code'], ['postal_code' => 'postal_code:NL'] ); $translator->addLines([ 'validation.postal_code' => ':attribute invalid, should be a :countries postal code (e.g. :examples)', ], $locale); $this->assertContains( 'postal code invalid, should be a NL postal code (e.g. 1234 AB)', $validator->errors()->all() ); }
Test the error replacer for the 'postal_code' rule. @return void
testPostalCodeReplacer
php
axlon/laravel-postal-code-validation
tests/Integration/ReplacerTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/ReplacerTest.php
MIT
public function testPostalCodeForReplacer(): void { $locale = is_callable([$this->app, 'getLocale']) ? $this->app->getLocale() : 'en'; $translator = $this->app->make('translator'); $validator = $this->app->make('validator')->make( ['postal_code' => 'not-a-postal-code', 'country' => 'NL'], ['postal_code' => 'postal_code_for:country'] ); $translator->addLines([ 'validation.postal_code_for' => ':attribute invalid, should be a :countries postal code (e.g. :examples)', ], $locale); $this->assertContains( 'postal code invalid, should be a NL postal code (e.g. 1234 AB)', $validator->errors()->all() ); }
Test the error replacer for the 'postal_code_for' rule. @return void
testPostalCodeForReplacer
php
axlon/laravel-postal-code-validation
tests/Integration/ReplacerTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/ReplacerTest.php
MIT
protected function setUpApplication(): void { if (!isset(self::$resolver)) { $this->markTestSkipped('Application cannot be bootstrapped'); } $this->app = self::$resolver->call($this); }
Set up a new application instance. @return void
setUpApplication
php
axlon/laravel-postal-code-validation
tests/Integration/TestCase.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/TestCase.php
MIT
public static function resolveUsing(Closure $resolver): void { self::$resolver = $resolver; }
Set the application resolver. @param \Closure $resolver @return void
resolveUsing
php
axlon/laravel-postal-code-validation
tests/Integration/TestCase.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Integration/TestCase.php
MIT
public function testExampleRetrieval(): void { $this->assertEquals('1234 AB', $this->examples->get('NL')); $this->assertEquals('4000', $this->examples->get('be')); # Lowercase country code $this->assertNull($this->examples->get('GH')); # Country code without a pattern $this->assertNull($this->examples->get('XX')); # Non-existent country code }
Test the retrieval of valid postal code examples. @return void
testExampleRetrieval
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeExamplesTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeExamplesTest.php
MIT
public function testDependentRuleCreation(): void { $this->assertEquals('postal_code_with:', (string)PostalCode::forInput()); $this->assertEquals('postal_code_with:foo', (string)PostalCode::forInput('foo')); $this->assertEquals('postal_code_with:foo,bar,baz', (string)PostalCode::forInput('foo', 'bar')->or('baz')); $this->assertEquals('postal_code_with:foo', (string)PostalCode::with('foo')); $this->assertEquals('postal_code_with:foo,bar,baz', (string)PostalCode::with('foo')->or('bar')->or('baz')); }
Test the creation of dependent postal code rules. @return void
testDependentRuleCreation
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeRuleTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeRuleTest.php
MIT
public function testExplicitRuleCreation(): void { $this->assertEquals('postal_code:', (string)PostalCode::forCountry()); $this->assertEquals('postal_code:foo', (string)PostalCode::forCountry('foo')); $this->assertEquals('postal_code:foo,bar,baz', (string)PostalCode::forCountry('foo', 'bar')->or('baz')); $this->assertEquals('postal_code:foo', (string)PostalCode::for('foo')); $this->assertEquals('postal_code:foo,bar,baz', (string)PostalCode::for('foo')->or('bar')->or('baz')); }
Test the creation of explicit postal code rules. @return void
testExplicitRuleCreation
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeRuleTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeRuleTest.php
MIT
public static function provideExamples(): Collection { $data = require __DIR__ . '/../../resources/examples.php'; return collect($data)->map(function (string $example, string $country) { return [$country, $example]; }); }
Get the examples. @return \Illuminate\Support\Collection
provideExamples
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeValidatorTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeValidatorTest.php
MIT
public function testCanaryIslands(): void { $this->assertTrue($this->validator->passes('IC', '38580')); }
@link https://github.com/axlon/laravel-postal-code-validation/issues/35
testCanaryIslands
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeValidatorTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeValidatorTest.php
MIT
public function testExamplesAreValidPatterns(string $country, string $example): void { $this->assertTrue($this->validator->passes($country, $example)); }
Test if the shipped examples pass validation. @param string $country @param string $example @return void @dataProvider provideExamples
testExamplesAreValidPatterns
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeValidatorTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeValidatorTest.php
MIT
public function testGreatBritainInwardCodeMaxLength(): void { $this->assertFalse($this->validator->passes('GB', 'NN1 5LLL')); }
Test whether Great Britain validation fails on an inward code that is too long. @link https://github.com/axlon/laravel-postal-code-validation/issues/13 @return void
testGreatBritainInwardCodeMaxLength
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeValidatorTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeValidatorTest.php
MIT
public function testLowerCaseCountryCode(): void { $this->assertTrue($this->validator->supports('nl')); $this->assertNotNull($this->validator->patternFor('nl')); $this->assertTrue($this->validator->passes('nl', '1234 AB')); }
Test whether lower case country codes can be used. @return void
testLowerCaseCountryCode
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeValidatorTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeValidatorTest.php
MIT
public function testNullPattern(): void { $this->assertTrue($this->validator->supports('GH')); $this->assertNull($this->validator->patternFor('GH')); $this->assertTrue($this->validator->passes('GH', 'any value')); }
Test whether null patterns match any value. @return void
testNullPattern
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeValidatorTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeValidatorTest.php
MIT
public function testPatternOverride(): void { $this->validator->override('BE', '/override/'); $this->assertEquals('/override/', $this->validator->patternFor('BE')); $this->assertTrue($this->validator->fails('BE', '4000')); $this->assertTrue($this->validator->passes('BE', 'override')); }
Test pattern override registration. @return void
testPatternOverride
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeValidatorTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeValidatorTest.php
MIT
public function testPatternOverrideViaArray(): void { $this->validator->override(['FR' => '/override/']); $this->assertEquals('/override/', $this->validator->patternFor('FR')); $this->assertTrue($this->validator->fails('FR', '33380')); $this->assertTrue($this->validator->passes('FR', 'override')); }
Test pattern override registration using an associative array. @return void
testPatternOverrideViaArray
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeValidatorTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeValidatorTest.php
MIT
public function testUnsupportedCountryCode(): void { $this->assertFalse($this->validator->supports('XX')); $this->assertNull($this->validator->patternFor('XX')); $this->assertTrue($this->validator->fails('any value')); }
Test whether unsupported country codes always fail validation. @return void
testUnsupportedCountryCode
php
axlon/laravel-postal-code-validation
tests/Unit/PostalCodeValidatorTest.php
https://github.com/axlon/laravel-postal-code-validation/blob/master/tests/Unit/PostalCodeValidatorTest.php
MIT