_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q14200 | PostsController.collectTags | train | private function collectTags($incomingTags)
{
$allTags = WinkTag::all();
return collect($incomingTags)->map(function ($incomingTag) use ($allTags) {
$tag = $allTags->where('slug', Str::slug($incomingTag['name']))->first();
if (! $tag) {
$tag = WinkTag::create([
'id' => $id = Str::uuid(),
'name' => $incomingTag['name'],
'slug' => Str::slug($incomingTag['name']),
]);
}
return (string) $tag->id;
})->toArray();
} | php | {
"resource": ""
} |
q14201 | TeamController.delete | train | public function delete($id)
{
$entry = WinkAuthor::findOrFail($id);
if ($entry->posts()->count()) {
return response()->json(['message' => 'Please remove the author\'s posts first.'], 402);
}
if ($entry->id == auth('wink')->user()->id) {
return response()->json(['message' => 'You cannot delete yourself.'], 402);
}
$entry->delete();
} | php | {
"resource": ""
} |
q14202 | WinkServiceProvider.registerRoutes | train | private function registerRoutes()
{
$path = config('wink.path');
$middlewareGroup = config('wink.middleware_group');
Route::namespace('Wink\Http\Controllers')
->middleware($middlewareGroup)
->as('wink.')
->prefix($path)
->group(function () {
Route::get('/login', 'LoginController@showLoginForm')->name('auth.login');
Route::post('/login', 'LoginController@login')->name('auth.attempt');
Route::get('/password/forgot', 'ForgotPasswordController@showResetRequestForm')->name('password.forgot');
Route::post('/password/forgot', 'ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('/password/reset/{token}', 'ForgotPasswordController@showNewPassword')->name('password.reset');
});
Route::namespace('Wink\Http\Controllers')
->middleware([$middlewareGroup, Authenticate::class])
->as('wink.')
->prefix($path)
->group(function () {
$this->loadRoutesFrom(__DIR__.'/Http/routes.php');
});
} | php | {
"resource": ""
} |
q14203 | ForgotPasswordController.sendResetLinkEmail | train | public function sendResetLinkEmail()
{
validator(request()->all(), [
'email' => 'required|email',
])->validate();
if ($author = WinkAuthor::whereEmail(request('email'))->first()) {
cache(['password.reset.'.$author->id => $token = Str::random()],
now()->addMinutes(30)
);
Mail::to($author->email)->send(new ResetPasswordEmail(
encrypt($author->id.'|'.$token)
));
}
return redirect()->route('wink.password.forgot')->with('sent', true);
} | php | {
"resource": ""
} |
q14204 | ForgotPasswordController.showNewPassword | train | public function showNewPassword($token)
{
try {
$token = decrypt($token);
[$authorId, $token] = explode('|', $token);
$author = WinkAuthor::findOrFail($authorId);
} catch (Throwable $e) {
return redirect()->route('wink.password.forgot')->with('invalidResetToken', true);
}
if (cache('password.reset.'.$authorId) != $token) {
return redirect()->route('wink.password.forgot')->with('invalidResetToken', true);
}
cache()->forget('password.reset.'.$authorId);
$author->password = \Hash::make($password = Str::random());
$author->save();
return view('wink::reset-password', [
'password' => $password,
]);
} | php | {
"resource": ""
} |
q14205 | PagesController.index | train | public function index()
{
$entries = WinkPage::when(request()->has('search'), function ($q) {
$q->where('title', 'LIKE', '%'.request('search').'%');
})
->orderBy('created_at', 'DESC')
->paginate(30);
return PagesResource::collection($entries);
} | php | {
"resource": ""
} |
q14206 | Response.makeFromExisting | train | public static function makeFromExisting(IlluminateResponse $old)
{
$new = static::create($old->getOriginalContent(), $old->getStatusCode());
$new->headers = $old->headers;
return $new;
} | php | {
"resource": ""
} |
q14207 | Response.withHeader | train | public function withHeader($key, $value, $replace = true)
{
return $this->header($key, $value, $replace);
} | php | {
"resource": ""
} |
q14208 | Request.createFromIlluminate | train | public function createFromIlluminate(IlluminateRequest $old)
{
$new = new static(
$old->query->all(), $old->request->all(), $old->attributes->all(),
$old->cookies->all(), $old->files->all(), $old->server->all(), $old->content
);
if ($session = $old->getSession()) {
$new->setLaravelSession($old->getSession());
}
$new->setRouteResolver($old->getRouteResolver());
$new->setUserResolver($old->getUserResolver());
return $new;
} | php | {
"resource": ""
} |
q14209 | Laravel.getRoutes | train | public function getRoutes($version = null)
{
if (! is_null($version)) {
return $this->routes[$version];
}
return $this->routes;
} | php | {
"resource": ""
} |
q14210 | Laravel.gatherRouteMiddlewares | train | public function gatherRouteMiddlewares($route)
{
if (method_exists($this->router, 'gatherRouteMiddleware')) {
return $this->router->gatherRouteMiddleware($route);
}
return $this->router->gatherRouteMiddlewares($route);
} | php | {
"resource": ""
} |
q14211 | Fractal.shouldEagerLoad | train | protected function shouldEagerLoad($response)
{
if ($response instanceof IlluminatePaginator) {
$response = $response->getCollection();
}
return $response instanceof EloquentCollection && $this->eagerLoading;
} | php | {
"resource": ""
} |
q14212 | Fractal.parseFractalIncludes | train | public function parseFractalIncludes(Request $request)
{
$includes = $request->input($this->includeKey);
if (! is_array($includes)) {
$includes = array_map('trim', array_filter(explode($this->includeSeparator, $includes)));
}
$this->fractal->parseIncludes($includes);
} | php | {
"resource": ""
} |
q14213 | Fractal.mergeEagerLoads | train | protected function mergeEagerLoads($transformer, $requestedIncludes)
{
$includes = array_merge($requestedIncludes, $transformer->getDefaultIncludes());
$eagerLoads = [];
foreach ($includes as $key => $value) {
$eagerLoads[] = is_string($key) ? $key : $value;
}
if (property_exists($transformer, 'lazyLoadedIncludes')) {
$eagerLoads = array_diff($eagerLoads, $transformer->lazyLoadedIncludes);
}
return $eagerLoads;
} | php | {
"resource": ""
} |
q14214 | Factory.item | train | public function item($item, $transformer, $parameters = [], Closure $after = null)
{
$class = get_class($item);
if ($parameters instanceof \Closure) {
$after = $parameters;
$parameters = [];
}
$binding = $this->transformer->register($class, $transformer, $parameters, $after);
return new Response($item, 200, [], $binding);
} | php | {
"resource": ""
} |
q14215 | Binding.resolveTransformer | train | public function resolveTransformer()
{
if (is_string($this->resolver)) {
return $this->container->make($this->resolver);
} elseif (is_callable($this->resolver)) {
return call_user_func($this->resolver, $this->container);
} elseif (is_object($this->resolver)) {
return $this->resolver;
}
throw new RuntimeException('Unable to resolve transformer binding.');
} | php | {
"resource": ""
} |
q14216 | RouteCollection.addLookups | train | protected function addLookups(Route $route)
{
$action = $route->getAction();
if (isset($action['as'])) {
$this->names[$action['as']] = $route;
}
if (isset($action['controller'])) {
$this->actions[$action['controller']] = $route;
}
} | php | {
"resource": ""
} |
q14217 | RouteCollection.getByName | train | public function getByName($name)
{
return isset($this->names[$name]) ? $this->names[$name] : null;
} | php | {
"resource": ""
} |
q14218 | RouteCollection.getByAction | train | public function getByAction($action)
{
return isset($this->actions[$action]) ? $this->actions[$action] : null;
} | php | {
"resource": ""
} |
q14219 | Routes.routeRateLimit | train | protected function routeRateLimit($route)
{
list($limit, $expires) = [$route->getRateLimit(), $route->getRateLimitExpiration()];
if ($limit && $expires) {
return sprintf('%s req/s', round($limit / ($expires * 60), 2));
}
} | php | {
"resource": ""
} |
q14220 | Routes.filterByVersions | train | protected function filterByVersions(array $route)
{
foreach ($this->option('versions') as $version) {
if (Str::contains($route['versions'], $version)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q14221 | Routes.filterByScopes | train | protected function filterByScopes(array $route)
{
foreach ($this->option('scopes') as $scope) {
if (Str::contains($route['scopes'], $scope)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q14222 | Factory.register | train | public function register($class, $resolver, array $parameters = [], Closure $after = null)
{
return $this->bindings[$class] = $this->createBinding($resolver, $parameters, $after);
} | php | {
"resource": ""
} |
q14223 | Factory.transform | train | public function transform($response)
{
$binding = $this->getBinding($response);
return $this->adapter->transform($response, $binding->resolveTransformer(), $binding, $this->getRequest());
} | php | {
"resource": ""
} |
q14224 | Factory.getBinding | train | protected function getBinding($class)
{
if ($this->isCollection($class) && ! $class->isEmpty()) {
return $this->getBindingFromCollection($class);
}
$class = is_object($class) ? get_class($class) : $class;
if (! $this->hasBinding($class)) {
throw new RuntimeException('Unable to find bound transformer for "'.$class.'" class.');
}
return $this->bindings[$class];
} | php | {
"resource": ""
} |
q14225 | Factory.createBinding | train | protected function createBinding($resolver, array $parameters = [], Closure $callback = null)
{
return new Binding($this->container, $resolver, $parameters, $callback);
} | php | {
"resource": ""
} |
q14226 | Factory.hasBinding | train | protected function hasBinding($class)
{
if ($this->isCollection($class) && ! $class->isEmpty()) {
$class = $class->first();
}
$class = is_object($class) ? get_class($class) : $class;
return isset($this->bindings[$class]);
} | php | {
"resource": ""
} |
q14227 | Factory.getRequest | train | public function getRequest()
{
$request = $this->container['request'];
if ($request instanceof IlluminateRequest && ! $request instanceof Request) {
$request = (new Request())->createFromIlluminate($request);
}
return $request;
} | php | {
"resource": ""
} |
q14228 | Lumen.normalizeRequestUri | train | protected function normalizeRequestUri(Request $request)
{
$query = $request->server->get('QUERY_STRING');
$uri = '/'.trim(str_replace('?'.$query, '', $request->server->get('REQUEST_URI')), '/').($query ? '?'.$query : '');
$request->server->set('REQUEST_URI', $uri);
} | php | {
"resource": ""
} |
q14229 | Lumen.breakUriSegments | train | protected function breakUriSegments($uri)
{
if (! Str::contains($uri, '?}')) {
return (array) $uri;
}
$segments = preg_split(
'/\/(\{.*?\})/',
preg_replace('/\{(.*?)\?\}/', '{$1}', $uri),
-1,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
);
$uris = [];
while ($segments) {
$uris[] = implode('/', $segments);
array_pop($segments);
}
return $uris;
} | php | {
"resource": ""
} |
q14230 | Lumen.removeMiddlewareFromApp | train | protected function removeMiddlewareFromApp()
{
if ($this->middlewareRemoved) {
return;
}
$this->middlewareRemoved = true;
$reflection = new ReflectionClass($this->app);
$property = $reflection->getProperty('middleware');
$property->setAccessible(true);
$oldMiddlewares = $property->getValue($this->app);
$newMiddlewares = [];
foreach ($oldMiddlewares as $middle) {
if ((new ReflectionClass($middle))->hasMethod('terminate') && $middle != 'Dingo\Api\Http\Middleware\Request') {
$newMiddlewares = array_merge($newMiddlewares, [$middle]);
}
}
$property->setValue($this->app, $newMiddlewares);
$property->setAccessible(false);
} | php | {
"resource": ""
} |
q14231 | Lumen.getIterableRoutes | train | public function getIterableRoutes($version = null)
{
$iterable = [];
foreach ($this->getRoutes($version) as $version => $collector) {
$routeData = $collector->getData();
// The first element in the array are the static routes that do not have any parameters.
foreach ($this->normalizeStaticRoutes($routeData[0]) as $method => $routes) {
if ($method === 'HEAD') {
continue;
}
foreach ($routes as $route) {
$route['methods'] = $this->setRouteMethods($route, $method);
$iterable[$version][] = $route;
}
}
// The second element is the more complicated regex routes that have parameters.
foreach ($routeData[1] as $method => $routes) {
if ($method === 'HEAD') {
continue;
}
foreach ($routes as $data) {
foreach ($data['routeMap'] as list($route, $parameters)) {
$route['methods'] = $this->setRouteMethods($route, $method);
$iterable[$version][] = $route;
}
}
}
}
return new ArrayIterator($iterable);
} | php | {
"resource": ""
} |
q14232 | Request.terminate | train | public function terminate($request, $response)
{
if (! ($request = $this->app['request']) instanceof HttpRequest) {
return;
}
// Laravel's route middlewares can be terminated just like application
// middleware, so we'll gather all the route middleware here.
// On Lumen this will simply be an empty array as it does
// not implement terminable route middleware.
$middlewares = $this->gatherRouteMiddlewares($request);
// Because of how middleware is executed on Lumen we'll need to merge in the
// application middlewares now so that we can terminate them. Laravel does
// not need this as it handles things a little more gracefully so it
// can terminate the application ones itself.
if (class_exists(Application::class, false)) {
$middlewares = array_merge($middlewares, $this->middleware);
}
foreach ($middlewares as $middleware) {
if ($middleware instanceof Closure) {
continue;
}
list($name, $parameters) = $this->parseMiddleware($middleware);
$instance = $this->app->make($name);
if (method_exists($instance, 'terminate')) {
$instance->terminate($request, $response);
}
}
} | php | {
"resource": ""
} |
q14233 | Route.setupRouteProperties | train | protected function setupRouteProperties(Request $request, $route)
{
list($this->uri, $this->methods, $this->action) = $this->adapter->getRouteProperties($route, $request);
$this->versions = Arr::pull($this->action, 'version');
$this->conditionalRequest = Arr::pull($this->action, 'conditionalRequest', true);
$this->middleware = (array) Arr::pull($this->action, 'middleware', []);
$this->throttle = Arr::pull($this->action, 'throttle');
$this->scopes = Arr::pull($this->action, 'scopes', []);
$this->authenticationProviders = Arr::pull($this->action, 'providers', []);
$this->rateLimit = Arr::pull($this->action, 'limit', 0);
$this->rateExpiration = Arr::pull($this->action, 'expires', 0);
// Now that the default route properties have been set we'll go ahead and merge
// any controller properties to fully configure the route.
$this->mergeControllerProperties();
// If we have a string based throttle then we'll new up an instance of the
// throttle through the container.
if (is_string($this->throttle)) {
$this->throttle = $this->container->make($this->throttle);
}
} | php | {
"resource": ""
} |
q14234 | Route.mergeControllerProperties | train | protected function mergeControllerProperties()
{
if (isset($this->action['uses']) && is_string($this->action['uses']) && Str::contains($this->action['uses'],
'@')) {
$this->action['controller'] = $this->action['uses'];
$this->makeControllerInstance();
}
if (! $this->controllerUsesHelpersTrait()) {
return;
}
$controller = $this->getControllerInstance();
$controllerMiddleware = [];
if (method_exists($controller, 'getMiddleware')) {
$controllerMiddleware = $controller->getMiddleware();
} elseif (method_exists($controller, 'getMiddlewareForMethod')) {
$controllerMiddleware = $controller->getMiddlewareForMethod($this->controllerMethod);
}
$this->middleware = array_merge($this->middleware, $controllerMiddleware);
if ($property = $this->findControllerPropertyOptions('throttles')) {
$this->throttle = $property['class'];
}
if ($property = $this->findControllerPropertyOptions('scopes')) {
$this->scopes = array_merge($this->scopes, $property['scopes']);
}
if ($property = $this->findControllerPropertyOptions('authenticationProviders')) {
$this->authenticationProviders = array_merge($this->authenticationProviders, $property['providers']);
}
if ($property = $this->findControllerPropertyOptions('rateLimit')) {
$this->rateLimit = $property['limit'];
$this->rateExpiration = $property['expires'];
}
} | php | {
"resource": ""
} |
q14235 | Route.findControllerPropertyOptions | train | protected function findControllerPropertyOptions($name)
{
$properties = [];
foreach ($this->getControllerInstance()->{'get'.ucfirst($name)}() as $property) {
if (isset($property['options']) && ! $this->optionsApplyToControllerMethod($property['options'])) {
continue;
}
unset($property['options']);
$properties = array_merge_recursive($properties, $property);
}
return $properties;
} | php | {
"resource": ""
} |
q14236 | Route.optionsApplyToControllerMethod | train | protected function optionsApplyToControllerMethod(array $options)
{
if (empty($options)) {
return true;
} elseif (isset($options['only']) && in_array($this->controllerMethod,
$this->explodeOnPipes($options['only']))) {
return true;
} elseif (isset($options['except'])) {
return ! in_array($this->controllerMethod, $this->explodeOnPipes($options['except']));
} elseif (in_array($this->controllerMethod, $this->explodeOnPipes($options))) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q14237 | Route.controllerUsesHelpersTrait | train | protected function controllerUsesHelpersTrait()
{
if (! $controller = $this->getControllerInstance()) {
return false;
}
$traits = [];
do {
$traits = array_merge(class_uses($controller, false), $traits);
} while ($controller = get_parent_class($controller));
foreach ($traits as $trait => $same) {
$traits = array_merge(class_uses($trait, false), $traits);
}
return isset($traits[Helpers::class]);
} | php | {
"resource": ""
} |
q14238 | Route.makeControllerInstance | train | protected function makeControllerInstance()
{
list($this->controllerClass, $this->controllerMethod) = explode('@', $this->action['uses']);
$this->container->instance($this->controllerClass,
$this->controller = $this->container->make($this->controllerClass));
return $this->controller;
} | php | {
"resource": ""
} |
q14239 | Route.isProtected | train | public function isProtected()
{
if (isset($this->middleware['api.auth']) || in_array('api.auth', $this->middleware)) {
if ($this->controller && isset($this->middleware['api.auth'])) {
return $this->optionsApplyToControllerMethod($this->middleware['api.auth']);
}
return true;
}
return false;
} | php | {
"resource": ""
} |
q14240 | JWT.getToken | train | protected function getToken(Request $request)
{
try {
$this->validateAuthorizationHeader($request);
$token = $this->parseAuthorizationHeader($request);
} catch (Exception $exception) {
if (! $token = $request->query('token', false)) {
throw $exception;
}
}
return $token;
} | php | {
"resource": ""
} |
q14241 | JsonOptionalFormatting.isCustomIndentStyleRequired | train | protected function isCustomIndentStyleRequired()
{
return $this->isJsonPrettyPrintEnabled() &&
isset($this->options['indent_style']) &&
in_array($this->options['indent_style'], $this->indentStyles);
} | php | {
"resource": ""
} |
q14242 | JsonOptionalFormatting.performJsonEncoding | train | protected function performJsonEncoding($content, array $jsonEncodeOptions = [])
{
$jsonEncodeOptions = $this->filterJsonEncodeOptions($jsonEncodeOptions);
$optionsBitmask = $this->calucateJsonEncodeOptionsBitmask($jsonEncodeOptions);
if (($encodedString = json_encode($content, $optionsBitmask)) === false) {
throw new \ErrorException('Error encoding data in JSON format: '.json_last_error());
}
return $encodedString;
} | php | {
"resource": ""
} |
q14243 | JsonOptionalFormatting.indentPrettyPrintedJson | train | protected function indentPrettyPrintedJson($jsonString, $indentStyle, $defaultIndentSize = 2)
{
$indentChar = $this->getIndentCharForIndentStyle($indentStyle);
$indentSize = $this->getPrettyPrintIndentSize() ?: $defaultIndentSize;
// If the given indentation style is allowed to have various indent size
// (number of chars, that are used to indent one level in each line),
// indent the JSON string with given (or default) indent size.
if ($this->hasVariousIndentSize($indentStyle)) {
return $this->peformIndentation($jsonString, $indentChar, $indentSize);
}
// Otherwise following the convention, that indent styles, that does not
// allowed to have various indent size (e.g. tab) are indented using
// one tabulation character per one indent level in each line.
return $this->peformIndentation($jsonString, $indentChar);
} | php | {
"resource": ""
} |
q14244 | JsonOptionalFormatting.peformIndentation | train | protected function peformIndentation($jsonString, $indentChar = "\t", $indentSize = 1, $defaultSpaces = 4)
{
$pattern = '/(^|\G) {'.$defaultSpaces.'}/m';
$replacement = str_repeat($indentChar, $indentSize).'$1';
return preg_replace($pattern, $replacement, $jsonString);
} | php | {
"resource": ""
} |
q14245 | ServiceProvider.config | train | protected function config($item, $instantiate = true)
{
$value = $this->app['config']->get('api.'.$item);
if (is_array($value)) {
return $instantiate ? $this->instantiateConfigValues($item, $value) : $value;
}
return $instantiate ? $this->instantiateConfigValue($item, $value) : $value;
} | php | {
"resource": ""
} |
q14246 | ServiceProvider.instantiateConfigValues | train | protected function instantiateConfigValues($item, array $values)
{
foreach ($values as $key => $value) {
$values[$key] = $this->instantiateConfigValue($item, $value);
}
return $values;
} | php | {
"resource": ""
} |
q14247 | Accept.validate | train | public function validate(Request $request)
{
try {
$this->accept->parse($request, $this->strict);
} catch (BadRequestHttpException $exception) {
if ($request->getMethod() === 'OPTIONS') {
return true;
}
throw $exception;
}
} | php | {
"resource": ""
} |
q14248 | LaravelServiceProvider.updateRouterBindings | train | protected function updateRouterBindings()
{
foreach ($this->getRouterBindings() as $key => $binding) {
$this->app['api.router.adapter']->getRouter()->bind($key, $binding);
}
} | php | {
"resource": ""
} |
q14249 | Router.version | train | public function version($version, $second, $third = null)
{
if (func_num_args() == 2) {
list($version, $callback, $attributes) = array_merge(func_get_args(), [[]]);
} else {
list($version, $attributes, $callback) = func_get_args();
}
$attributes = array_merge($attributes, ['version' => $version]);
$this->group($attributes, $callback);
} | php | {
"resource": ""
} |
q14250 | Router.resource | train | public function resource($name, $controller, array $options = [])
{
if ($this->container->bound(ResourceRegistrar::class)) {
$registrar = $this->container->make(ResourceRegistrar::class);
} else {
$registrar = new ResourceRegistrar($this);
}
$registrar->register($name, $controller, $options);
} | php | {
"resource": ""
} |
q14251 | Router.mergeLastGroupAttributes | train | protected function mergeLastGroupAttributes(array $attributes)
{
if (empty($this->groupStack)) {
return $this->mergeGroup($attributes, []);
}
return $this->mergeGroup($attributes, end($this->groupStack));
} | php | {
"resource": ""
} |
q14252 | Router.dispatch | train | public function dispatch(Request $request)
{
$this->currentRoute = null;
$this->container->instance(Request::class, $request);
$this->routesDispatched++;
try {
$response = $this->adapter->dispatch($request, $request->version());
} catch (Exception $exception) {
if ($request instanceof InternalRequest) {
throw $exception;
}
$this->exception->report($exception);
$response = $this->exception->handle($exception);
}
return $this->prepareResponse($response, $request, $request->format());
} | php | {
"resource": ""
} |
q14253 | Router.createRoute | train | public function createRoute($route)
{
return new Route($this->adapter, $this->container, $this->container['request'], $route);
} | php | {
"resource": ""
} |
q14254 | Router.getRoutes | train | public function getRoutes($version = null)
{
$routes = $this->adapter->getIterableRoutes($version);
if (! is_null($version)) {
$routes = [$version => $routes];
}
$collections = [];
foreach ($routes as $key => $value) {
$collections[$key] = new RouteCollection($this->container['request']);
foreach ($value as $route) {
$route = $this->createRoute($route);
$collections[$key]->add($route);
}
}
return is_null($version) ? $collections : $collections[$version];
} | php | {
"resource": ""
} |
q14255 | Router.setAdapterRoutes | train | public function setAdapterRoutes(array $routes)
{
$this->adapter->setRoutes($routes);
$this->container->instance('api.routes', $this->getRoutes());
} | php | {
"resource": ""
} |
q14256 | Auth.filterProviders | train | protected function filterProviders(array $providers)
{
if (empty($providers)) {
return $this->providers;
}
return array_intersect_key($this->providers, array_flip($providers));
} | php | {
"resource": ""
} |
q14257 | Auth.extend | train | public function extend($key, $provider)
{
if (is_callable($provider)) {
$provider = call_user_func($provider, $this->container);
}
$this->providers[$key] = $provider;
} | php | {
"resource": ""
} |
q14258 | RateLimit.handle | train | public function handle($request, Closure $next)
{
if ($request instanceof InternalRequest) {
return $next($request);
}
$route = $this->router->getCurrentRoute();
if ($route->hasThrottle()) {
$this->handler->setThrottle($route->getThrottle());
}
$this->handler->rateLimitRequest($request, $route->getRateLimit(), $route->getRateLimitExpiration());
if ($this->handler->exceededRateLimit()) {
throw new RateLimitExceededException('You have exceeded your rate limit.', null, $this->getHeaders());
}
$response = $next($request);
if ($this->handler->requestWasRateLimited()) {
return $this->responseWithHeaders($response);
}
return $response;
} | php | {
"resource": ""
} |
q14259 | RateLimit.responseWithHeaders | train | protected function responseWithHeaders($response)
{
foreach ($this->getHeaders() as $key => $value) {
$response->headers->set($key, $value);
}
return $response;
} | php | {
"resource": ""
} |
q14260 | RateLimit.getHeaders | train | protected function getHeaders()
{
return [
'X-RateLimit-Limit' => $this->handler->getThrottleLimit(),
'X-RateLimit-Remaining' => $this->handler->getRemainingLimit(),
'X-RateLimit-Reset' => $this->handler->getRateLimitReset(),
];
} | php | {
"resource": ""
} |
q14261 | Docs.getDocName | train | protected function getDocName()
{
$name = $this->option('name') ?: $this->name;
if (! $name) {
$this->comment('A name for the documentation was not supplied. Use the --name option or set a default in the configuration.');
exit;
}
return $name;
} | php | {
"resource": ""
} |
q14262 | Docs.getVersion | train | protected function getVersion()
{
$version = $this->option('use-version') ?: $this->version;
if (! $version) {
$this->comment('A version for the documentation was not supplied. Use the --use-version option or set a default in the configuration.');
exit;
}
return $version;
} | php | {
"resource": ""
} |
q14263 | Docs.getControllers | train | protected function getControllers()
{
$controllers = new Collection;
if ($controller = $this->option('use-controller')) {
$this->addControllerIfNotExists($controllers, app($controller));
return $controllers;
}
foreach ($this->router->getRoutes() as $collections) {
foreach ($collections as $route) {
if ($controller = $route->getControllerInstance()) {
$this->addControllerIfNotExists($controllers, $controller);
}
}
}
return $controllers;
} | php | {
"resource": ""
} |
q14264 | Docs.addControllerIfNotExists | train | protected function addControllerIfNotExists(Collection $controllers, $controller)
{
$class = get_class($controller);
if ($controllers->has($class)) {
return;
}
$reflection = new ReflectionClass($controller);
$interface = Arr::first($reflection->getInterfaces(), function ($key, $value) {
return ends_with($key, 'Docs');
});
if ($interface) {
$controller = $interface;
}
$controllers->put($class, $controller);
} | php | {
"resource": ""
} |
q14265 | Dispatcher.attach | train | public function attach(array $files)
{
foreach ($files as $key => $file) {
if (is_array($file)) {
$file = new UploadedFile($file['path'], basename($file['path']), $file['mime'], $file['size']);
} elseif (is_string($file)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new UploadedFile($file, basename($file), finfo_file($finfo, $file), $this->files->size($file));
} elseif (! $file instanceof UploadedFile) {
continue;
}
$this->uploads[$key] = $file;
}
return $this;
} | php | {
"resource": ""
} |
q14266 | Dispatcher.json | train | public function json($content)
{
if (is_array($content)) {
$content = json_encode($content);
}
$this->content = $content;
return $this->header('Content-Type', 'application/json');
} | php | {
"resource": ""
} |
q14267 | Dispatcher.with | train | public function with($parameters)
{
$this->parameters = array_merge($this->parameters, is_array($parameters) ? $parameters : func_get_args());
return $this;
} | php | {
"resource": ""
} |
q14268 | Dispatcher.queueRequest | train | protected function queueRequest($verb, $uri, $parameters, $content = '')
{
if (! empty($content)) {
$this->content = $content;
}
// Sometimes after setting the initial request another request might be made prior to
// internally dispatching an API request. We need to capture this request as well
// and add it to the request stack as it has become the new parent request to
// this internal request. This will generally occur during tests when
// using the crawler to navigate pages that also make internal
// requests.
if (end($this->requestStack) != $this->container['request']) {
$this->requestStack[] = $this->container['request'];
}
$this->requestStack[] = $request = $this->createRequest($verb, $uri, $parameters);
return $this->dispatch($request);
} | php | {
"resource": ""
} |
q14269 | Dispatcher.dispatch | train | protected function dispatch(InternalRequest $request)
{
$this->routeStack[] = $this->router->getCurrentRoute();
$this->clearCachedFacadeInstance();
try {
$this->container->instance('request', $request);
$response = $this->router->dispatch($request);
if (! $response->isSuccessful() && ! $response->isRedirection()) {
throw new InternalHttpException($response);
}
if (! $this->raw) {
$response = $response->getOriginalContent();
}
} catch (HttpExceptionInterface $exception) {
$this->refreshRequestStack();
throw $exception;
}
$this->refreshRequestStack();
return $response;
} | php | {
"resource": ""
} |
q14270 | Json.formatEloquentModel | train | public function formatEloquentModel($model)
{
$key = Str::singular($model->getTable());
if (! $model::$snakeAttributes) {
$key = Str::camel($key);
}
return $this->encode([$key => $model->toArray()]);
} | php | {
"resource": ""
} |
q14271 | Json.formatEloquentCollection | train | public function formatEloquentCollection($collection)
{
if ($collection->isEmpty()) {
return $this->encode([]);
}
$model = $collection->first();
$key = Str::plural($model->getTable());
if (! $model::$snakeAttributes) {
$key = Str::camel($key);
}
return $this->encode([$key => $collection->toArray()]);
} | php | {
"resource": ""
} |
q14272 | Json.encode | train | protected function encode($content)
{
$jsonEncodeOptions = [];
// Here is a place, where any available JSON encoding options, that
// deal with users' requirements to JSON response formatting and
// structure, can be conveniently applied to tweak the output.
if ($this->isJsonPrettyPrintEnabled()) {
$jsonEncodeOptions[] = JSON_PRETTY_PRINT;
}
$encodedString = $this->performJsonEncoding($content, $jsonEncodeOptions);
if ($this->isCustomIndentStyleRequired()) {
$encodedString = $this->indentPrettyPrintedJson(
$encodedString,
$this->options['indent_style']
);
}
return $encodedString;
} | php | {
"resource": ""
} |
q14273 | Handler.rateLimitRequest | train | public function rateLimitRequest(Request $request, $limit = 0, $expires = 0)
{
$this->request = $request;
// If the throttle instance is already set then we'll just carry on as
// per usual.
if ($this->throttle instanceof Throttle) {
// If the developer specified a certain amount of requests or expiration
// time on a specific route then we'll always use the route specific
// throttle with the given values.
} elseif ($limit > 0 || $expires > 0) {
$this->throttle = new Route(['limit' => $limit, 'expires' => $expires]);
$this->keyPrefix = sha1($request->path());
// Otherwise we'll use the throttle that gives the consumer the largest
// amount of requests. If no matching throttle is found then rate
// limiting will not be imposed for the request.
} else {
$this->throttle = $this->getMatchingThrottles()->sort(function ($a, $b) {
return $a->getLimit() < $b->getLimit();
})->first();
}
if (is_null($this->throttle)) {
return;
}
if ($this->throttle instanceof HasRateLimiter) {
$this->setRateLimiter([$this->throttle, 'getRateLimiter']);
}
$this->prepareCacheStore();
$this->cache('requests', 0, $this->throttle->getExpires());
$this->cache('expires', $this->throttle->getExpires(), $this->throttle->getExpires());
$this->cache('reset', time() + ($this->throttle->getExpires() * 60), $this->throttle->getExpires());
$this->increment('requests');
} | php | {
"resource": ""
} |
q14274 | Handler.prepareCacheStore | train | protected function prepareCacheStore()
{
if ($this->retrieve('expires') != $this->throttle->getExpires()) {
$this->forget('requests');
$this->forget('expires');
$this->forget('reset');
}
} | php | {
"resource": ""
} |
q14275 | Handler.cache | train | protected function cache($key, $value, $minutes)
{
$this->cache->add($this->key($key), $value, Carbon::now()->addMinutes($minutes));
} | php | {
"resource": ""
} |
q14276 | Handler.extend | train | public function extend($throttle)
{
if (is_callable($throttle)) {
$throttle = call_user_func($throttle, $this->container);
}
$this->throttles->push($throttle);
} | php | {
"resource": ""
} |
q14277 | Autoloader.loadPlugins | train | public function loadPlugins()
{
$this->checkCache();
$this->validatePlugins();
$this->countPlugins();
array_map(static function () {
include_once WPMU_PLUGIN_DIR . '/' . func_get_args()[0];
}, array_keys(self::$cache['plugins']));
$this->pluginHooks();
} | php | {
"resource": ""
} |
q14278 | Autoloader.checkCache | train | private function checkCache()
{
$cache = get_site_option('bedrock_autoloader');
if ($cache === false || (isset($cache['plugins'], $cache['count']) && count($cache['plugins']) !== $cache['count'])) {
$this->updateCache();
return;
}
self::$cache = $cache;
} | php | {
"resource": ""
} |
q14279 | Autoloader.validatePlugins | train | private function validatePlugins()
{
foreach (self::$cache['plugins'] as $plugin_file => $plugin_info) {
if (!file_exists(WPMU_PLUGIN_DIR . '/' . $plugin_file)) {
$this->updateCache();
break;
}
}
} | php | {
"resource": ""
} |
q14280 | Autoloader.countPlugins | train | private function countPlugins()
{
if (isset(self::$count)) {
return self::$count;
}
$count = count(glob(WPMU_PLUGIN_DIR . '/*/', GLOB_ONLYDIR | GLOB_NOSORT));
if (!isset(self::$cache['count']) || $count !== self::$cache['count']) {
self::$count = $count;
$this->updateCache();
}
return self::$count;
} | php | {
"resource": ""
} |
q14281 | Serialization.serialize | train | public static function serialize($filename, $instance, $force = false)
{
if ($filename == '') {
throw new \danog\MadelineProto\Exception('Empty filename');
}
if ($instance->API->asyncInitPromise) {
return $instance->call(static function () use ($filename, $instance, $force) {
yield $instance->API->asyncInitPromise;
$instance->API->asyncInitPromise = null;
return self::serialize($filename, $instance, $force);
});
}
if (isset($instance->API->setdem) && $instance->API->setdem) {
$instance->API->setdem = false;
$instance->API->__construct($instance->API->settings);
}
if ($instance->API === null && !$instance->getting_api_id) {
return false;
}
$instance->serialized = time();
$realpaths = self::realpaths($filename);
if (!file_exists($realpaths['lockfile'])) {
touch($realpaths['lockfile']);
clearstatcache();
}
$realpaths['lockfile'] = fopen($realpaths['lockfile'], 'w');
\danog\MadelineProto\Logger::log('Waiting for exclusive lock of serialization lockfile...');
flock($realpaths['lockfile'], LOCK_EX);
\danog\MadelineProto\Logger::log('Lock acquired, serializing');
try {
if (!$instance->getting_api_id) {
$update_closure = $instance->API->settings['updates']['callback'];
if ($instance->API->settings['updates']['callback'] instanceof \Closure) {
$instance->API->settings['updates']['callback'] = [$instance->API, 'noop'];
}
$logger_closure = $instance->API->settings['logger']['logger_param'];
if ($instance->API->settings['logger']['logger_param'] instanceof \Closure) {
$instance->API->settings['logger']['logger_param'] = [$instance->API, 'noop'];
}
}
$wrote = file_put_contents($realpaths['tempfile'], serialize($instance));
rename($realpaths['tempfile'], $realpaths['file']);
} finally {
if (!$instance->getting_api_id) {
$instance->API->settings['updates']['callback'] = $update_closure;
$instance->API->settings['logger']['logger_param'] = $logger_closure;
}
flock($realpaths['lockfile'], LOCK_UN);
fclose($realpaths['lockfile']);
}
return $wrote;
} | php | {
"resource": ""
} |
q14282 | ObfuscatedStream.bufferReadAsync | train | public function bufferReadAsync(int $length): \Generator
{
return @$this->decrypt->encrypt(yield $this->read_buffer->bufferRead($length));
} | php | {
"resource": ""
} |
q14283 | ObfuscatedStream.setExtra | train | public function setExtra($extra)
{
if (isset($extra['secret']) && strlen($extra['secret']) > 17) {
$extra['secret'] = hex2bin($extra['secret']);
}
if (isset($extra['secret']) && strlen($extra['secret']) == 17) {
$extra['secret'] = substr($extra['secret'], 0, 16);
}
$this->extra = $extra;
} | php | {
"resource": ""
} |
q14284 | DefaultStream.read | train | public function read(): Promise
{
return $this->stream ? $this->stream->read() : new \Amp\Success(null);
} | php | {
"resource": ""
} |
q14285 | HttpStream.setExtra | train | public function setExtra($extra)
{
if (isset($extra['user']) && isset($extra['password'])) {
$this->header = \base64_encode($extra['user'].':'.$extra['password'])."\r\n";
}
} | php | {
"resource": ""
} |
q14286 | MyTelegramOrgWrapper.get_headers | train | private function get_headers($httpType, $cookies)
{
// Common header flags.
$headers = [];
$headers[] = 'Dnt: 1';
$headers[] = 'Connection: keep-alive';
$headers[] = 'Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4';
$headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36';
// Add additional headers based on the type of request.
switch ($httpType) {
case 'origin':
$headers[] = 'Origin: '.self::MY_TELEGRAM_URL;
$headers[] = 'Accept-Encoding: gzip, deflate, br';
$headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
$headers[] = 'Accept: application/json, text/javascript, */*; q=0.01';
$headers[] = 'Referer: '.self::MY_TELEGRAM_URL.'/auth';
$headers[] = 'X-Requested-With: XMLHttpRequest';
break;
case 'refer':
$headers[] = 'Accept-Encoding: gzip, deflate, sdch, br';
$headers[] = 'Upgrade-Insecure-Requests: 1';
$headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
$headers[] = 'Referer: '.self::MY_TELEGRAM_URL;
$headers[] = 'Cache-Control: max-age=0';
break;
case 'app':
$headers[] = 'Origin: '.self::MY_TELEGRAM_URL;
$headers[] = 'Accept-Encoding: gzip, deflate, br';
$headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
$headers[] = 'Accept: */*';
$headers[] = 'Referer: '.self::MY_TELEGRAM_URL.'/apps';
$headers[] = 'X-Requested-With: XMLHttpRequest';
break;
}
// Add every cookie to the header.
foreach ($cookies as $cookie) {
$headers[] = 'Cookie: '.$cookie;
}
return $headers;
} | php | {
"resource": ""
} |
q14287 | ConnectionContext.setUri | train | public function setUri($uri): self
{
$this->uri = $uri instanceof Uri ? $uri : new Uri($uri);
return $this;
} | php | {
"resource": ""
} |
q14288 | ConnectionContext.getIntDc | train | public function getIntDc()
{
$dc = intval($this->dc);
if ($this->test) {
$dc += 10000;
}
if (strpos($this->dc, '_media')) {
$dc = -$dc;
}
return $dc;
} | php | {
"resource": ""
} |
q14289 | ConnectionContext.addStream | train | public function addStream(string $streamName, $extra = null): self
{
$this->nextStreams[] = [$streamName, $extra];
$this->key = count($this->nextStreams) - 1;
return $this;
} | php | {
"resource": ""
} |
q14290 | ConnectionContext.getStreamAsync | train | public function getStreamAsync(string $buffer = ''): \Generator
{
list($clazz, $extra) = $this->nextStreams[$this->key--];
$obj = new $clazz();
if ($obj instanceof ProxyStreamInterface) {
$obj->setExtra($extra);
}
yield $obj->connect($this, $buffer);
return $obj;
} | php | {
"resource": ""
} |
q14291 | ConnectionContext.getName | train | public function getName(): string
{
$string = $this->getStringUri();
if ($this->isSecure()) {
$string .= ' (TLS)';
}
$string .= ' DC ';
$string .= $this->getDc();
$string .= ', via ';
$string .= $this->getIpv6() ? 'ipv6' : 'ipv4';
$string .= ' using ';
foreach (array_reverse($this->nextStreams) as $k => $stream) {
if ($k) {
$string .= ' => ';
}
$string .= preg_replace('/.*\\\\/', '', $stream[0]);
if ($stream[1]) {
$string .= ' ('.json_encode($stream[1]).')';
}
}
return $string;
} | php | {
"resource": ""
} |
q14292 | AnnotationsBuilder.setProperties | train | private function setProperties()
{
\danog\MadelineProto\Logger::log('Generating properties...', \danog\MadelineProto\Logger::NOTICE);
$fixture = DocBlockFactory::createInstance();
$class = new \ReflectionClass(APIFactory::class);
$content = file_get_contents($filename = $class->getFileName());
foreach ($class->getProperties() as $property) {
if ($raw_docblock = $property->getDocComment()) {
$docblock = $fixture->create($raw_docblock);
if ($docblock->hasTag('internal')) {
$content = str_replace("\n ".$raw_docblock."\n public \$".$property->getName().';', '', $content);
}
}
}
foreach ($this->get_method_namespaces() as $namespace) {
$content = preg_replace('/(class( \\w+[,]?){0,}\\n{\\n)/', '${1}'." /**\n"." * @internal this is a internal property generated by build_docs.php, don't change manually\n"." *\n"." * @var {$namespace}\n"." */\n"." public \${$namespace};\n", $content);
}
file_put_contents($filename, $content);
} | php | {
"resource": ""
} |
q14293 | HashedBufferedStream.getReadHash | train | public function getReadHash(): string
{
$hash = hash_final($this->read_hash, true);
if ($this->rev) {
$hash = strrev($hash);
}
$this->read_hash = null;
$this->read_check_after = 0;
$this->read_check_pos = 0;
return $hash;
} | php | {
"resource": ""
} |
q14294 | HashedBufferedStream.getWriteHash | train | public function getWriteHash(): string
{
$hash = hash_final($this->write_hash, true);
if ($this->rev) {
$hash = strrev($hash);
}
$this->write_hash = null;
$this->write_check_after = 0;
$this->write_check_pos = 0;
return $hash;
} | php | {
"resource": ""
} |
q14295 | HashedBufferedStream.bufferReadAsync | train | public function bufferReadAsync(int $length): \Generator
{
if ($this->read_check_after && $length + $this->read_check_pos >= $this->read_check_after) {
if ($length + $this->read_check_pos > $this->read_check_after) {
throw new \danog\MadelineProto\Exception('Tried to read too much out of frame data');
}
$data = yield $this->read_buffer->bufferRead($length);
hash_update($this->read_hash, $data);
$hash = $this->getReadHash();
if ($hash !== yield $this->read_buffer->bufferRead(strlen($hash))) {
throw new \danog\MadelineProto\Exception('Hash mismatch');
}
return $data;
}
$data = yield $this->read_buffer->bufferRead($length);
hash_update($this->read_hash, $data);
if ($this->read_check_after) {
$this->read_check_pos += $length;
}
return $data;
} | php | {
"resource": ""
} |
q14296 | HashedBufferedStream.setExtra | train | public function setExtra($hash)
{
$rev = strpos($hash, '_rev');
$this->rev = false;
if ($rev !== false) {
$hash = substr($hash, 0, $rev);
$this->rev = true;
}
$this->hash_name = $hash;
} | php | {
"resource": ""
} |
q14297 | FullStream.connect | train | public function connect(ConnectionContext $ctx, string $header = ''): Promise
{
$this->in_seq_no = -1;
$this->out_seq_no = -1;
$this->stream = new HashedBufferedStream();
$this->stream->setExtra('crc32b_rev');
return $this->stream->connect($ctx, $header);
} | php | {
"resource": ""
} |
q14298 | BufferedRawStream.bufferWrite | train | public function bufferWrite(string $data): Promise
{
if ($this->append_after) {
$this->append_after -= strlen($data);
if ($this->append_after === 0) {
$data .= $this->append;
$this->append = '';
} elseif ($this->append_after < 0) {
$this->append_after = 0;
$this->append = '';
throw new Exception('Tried to send too much out of frame data, cannot append');
}
}
return $this->write($data);
} | php | {
"resource": ""
} |
q14299 | Connection.connectAsync | train | public function connectAsync(ConnectionContext $ctx): \Generator
{
$this->API->logger->logger("Trying connection via $ctx", \danog\MadelineProto\Logger::WARNING);
$this->ctx = $ctx->getCtx();
$this->datacenter = $ctx->getDc();
$this->stream = yield $ctx->getStream();
if (isset($this->old)) {
unset($this->old);
}
if (!isset($this->writer)) {
$this->writer = new WriteLoop($this->API, $this->datacenter);
}
if (!isset($this->reader)) {
$this->reader = new ReadLoop($this->API, $this->datacenter);
}
if (!isset($this->checker)) {
$this->checker = new CheckLoop($this->API, $this->datacenter);
}
if (!isset($this->waiter)) {
$this->waiter = new HttpWaitLoop($this->API, $this->datacenter);
}
if (!isset($this->updater)) {
$this->updater = new UpdateLoop($this->API, $this->datacenter);
}
foreach ($this->new_outgoing as $message_id) {
if ($this->outgoing_messages[$message_id]['unencrypted']) {
$promise = $this->outgoing_messages[$message_id]['promise'];
\Amp\Loop::defer(function () use ($promise) {
$promise->fail(new Exception('Restart'));
});
unset($this->new_outgoing[$message_id]);
unset($this->outgoing_messages[$message_id]);
}
}
$this->http_req_count = 0;
$this->http_res_count = 0;
$this->writer->start();
$this->reader->start();
if (!$this->checker->start()) {
$this->checker->resume();
}
$this->waiter->start();
if ($this->datacenter === $this->API->settings['connection_settings']['default_dc']) {
$this->updater->start();
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.