_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q250800
HandlerResolver.resolve
validation
public function resolve($handler) { if (!is_string($handler)) { return $handler; } $handler = $this->container->resolve($handler); if (!is_callable($handler) && !$handler instanceof ErrorHandlerInterface) { $type = is_object($handler) ? get_class($handler) : gettype($handler); throw new \UnexpectedValueException("Resolved error handler is not a valid handler - must be callable or an instance of Autarky\Errors\ErrorHandlerInterface, $type given"); } return $handler; }
php
{ "resource": "" }
q250801
Modal.renderCloseButton
validation
protected function renderCloseButton() { if (($closeButton = $this->closeButton) !== false) { $tag = ArrayHelper::remove($closeButton, 'tag', 'button'); $label = ArrayHelper::remove($closeButton, 'label', 'Close'); if ($tag === 'button' && !isset($closeButton['type'])) { $closeButton['type'] = 'button'; } return Html::tag($tag, $label, $closeButton); } else { return null; } }
php
{ "resource": "" }
q250802
ErrorHandlerManager.makeResponse
validation
protected function makeResponse($response, Exception $exception) { if (!$response instanceof Response) { $response = new Response($response); } if (!$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) { if ($exception instanceof HttpExceptionInterface) { $response->setStatusCode($exception->getStatusCode()); $response->headers->add($exception->getHeaders()); } else { $response->setStatusCode(500); } } return $response; }
php
{ "resource": "" }
q250803
ErrorHandlerManager.matchesTypehint
validation
protected function matchesTypehint($handler, Exception $exception) { if ($handler instanceof ErrorHandlerInterface) { return true; } if (is_array($handler)) { $reflection = (new ReflectionMethod($handler[0], $handler[1])); } else { $reflection = (new ReflectionFunction($handler)); } $params = $reflection->getParameters(); // if the handler takes no parameters it is considered global and should // handle every exception if (empty($params)) { return true; } $handlerHint = $params[0] ->getClass(); // likewise, if the first handler parameter has no typehint, consider it // a global handler that handles everything if (!$handlerHint) { return true; } return $handlerHint->isInstance($exception); }
php
{ "resource": "" }
q250804
ErrorHandlerManager.callHandler
validation
protected function callHandler($handler, Exception $exception) { if ($handler instanceof ErrorHandlerInterface) { return $handler->handle($exception); } return call_user_func($handler, $exception); }
php
{ "resource": "" }
q250805
ErrorHandlerManager.makeFatalErrorException
validation
protected function makeFatalErrorException() { $error = error_get_last(); if ($error !== null) { return new FatalErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']); } return null; }
php
{ "resource": "" }
q250806
Route.addBeforeHook
validation
public function addBeforeHook($hook) { if (!isset($this->options['before'])) { $this->options['before'] = []; } $this->options['before'][] = $hook; }
php
{ "resource": "" }
q250807
Route.addAfterHook
validation
public function addAfterHook($hook) { if (!isset($this->options['after'])) { $this->options['after'] = []; } $this->options['after'][] = $hook; }
php
{ "resource": "" }
q250808
Application.config
validation
public function config($configurator) { if ($this->booted) { $this->invokeConfigurator($configurator); } else { $this->configurators->push($configurator); } }
php
{ "resource": "" }
q250809
Application.invokeConfigurator
validation
protected function invokeConfigurator($configurator) { if (is_callable($configurator)) { call_user_func($configurator, $this); return; } if (is_string($configurator)) { $configurator = $this->container->resolve($configurator); } if ($configurator instanceof ConfiguratorInterface) { $configurator->configure(); } else { throw new \UnexpectedValueException('Invalid configurator'); } }
php
{ "resource": "" }
q250810
Application.setContainer
validation
public function setContainer(ContainerInterface $container) { $this->container = $container; $container->instance('Autarky\Application', $this); $container->instance('Symfony\Component\HttpFoundation\RequestStack', $this->requests); }
php
{ "resource": "" }
q250811
Application.addMiddleware
validation
public function addMiddleware($middleware, $priority = null) { $this->middlewares->insert($middleware, (int) $priority); }
php
{ "resource": "" }
q250812
Application.bootConsole
validation
public function bootConsole() { $this->console = new ConsoleApplication('Autarky', static::VERSION); $this->console->setAutarkyApplication($this); $this->boot(); return $this->console; }
php
{ "resource": "" }
q250813
Application.boot
validation
public function boot() { if ($this->booted) return; $this->booting = true; $this->registerProviders(); foreach ($this->configurators as $configurator) { $this->invokeConfigurator($configurator); } $this->resolveStack(); $this->booted = true; }
php
{ "resource": "" }
q250814
Application.registerProviders
validation
protected function registerProviders() { $dependants = []; foreach ($this->providers as $provider) { if (is_string($provider)) { $provider = new $provider(); } $this->registerProvider($provider); if ($provider instanceof DependantProviderInterface) { $dependants[] = $provider; } } foreach ($dependants as $dependant) { $this->checkProviderDependencies($dependant); } }
php
{ "resource": "" }
q250815
Application.registerProvider
validation
protected function registerProvider(ProviderInterface $provider) { if ($provider instanceof AbstractProvider) { $provider->setApplication($this); } $provider->register(); if ($this->console && $provider instanceof ConsoleProviderInterface) { $provider->registerConsole($this->console); } }
php
{ "resource": "" }
q250816
Application.resolveStack
validation
protected function resolveStack() { if ($this->stack !== null) { return $this->stack; } $this->stack = new StackBuilder; foreach ($this->middlewares as $middleware) { call_user_func_array([$this->stack, 'push'], (array) $middleware); } return $this->stack; }
php
{ "resource": "" }
q250817
Application.resolveKernel
validation
protected function resolveKernel() { if ($this->kernel !== null) { return $this->kernel; } $class = 'Symfony\Component\EventDispatcher\EventDispatcherInterface'; $eventDispatcher = $this->container->isBound($class) ? $this->container->resolve($class) : null; $kernel = new Kernel( $this->getRouter(), $this->requests, $this->errorHandler, $eventDispatcher ); return $this->kernel = $this->resolveStack() ->resolve($kernel); }
php
{ "resource": "" }
q250818
BaseWidgetTrait.registerMaterializePlugin
validation
protected function registerMaterializePlugin($name) { $view = $this->getView(); if ($this->materializeAsset) { MaterializeAsset::register($view); } if ($this->customAsset) { MaterializeCustomAsset::register($view); } $id = $this->options['id']; if ($this->clientOptions !== false && is_array($this->clientOptions)) { $options = empty($this->clientOptions) ? '' : Json::htmlEncode($this->clientOptions); $js = "Materialize.$name.apply(null, $options);"; $view->registerJs($js); } $this->registerClientEvents(); }
php
{ "resource": "" }
q250819
BaseWidgetTrait.registerPlugin
validation
protected function registerPlugin($name) { $view = $this->getView(); if ($this->materializeAsset) { MaterializeAsset::register($view); } if ($this->customAsset) { MaterializeCustomAsset::register($view); } $id = $this->options['id']; if ($this->clientOptions !== false) { $options = empty($this->clientOptions) ? '' : Json::encode($this->clientOptions); $js = "jQuery('#$id').$name($options);"; $view->registerJs($js); } $this->registerClientEvents(); }
php
{ "resource": "" }
q250820
ChannelManager.setChannel
validation
public function setChannel($channel, LoggerInterface $logger) { if (isset($this->channels[$channel])) { throw new InvalidArgumentException("Channel $channel is already defined"); } $this->channels[$channel] = $logger; }
php
{ "resource": "" }
q250821
ChannelManager.setDeferredChannel
validation
public function setDeferredChannel($channel, callable $callback) { if (isset($this->channels[$channel])) { throw new InvalidArgumentException("Channel $channel is already defined"); } $this->deferredChannels[$channel] = $callback; }
php
{ "resource": "" }
q250822
ChannelManager.getChannel
validation
public function getChannel($channel = null) { $channel = $channel ?: $this->defaultChannel; if (isset($this->deferredChannels[$channel])) { $this->setChannel($channel, $this->deferredChannels[$channel]()); unset($this->deferredChannels[$channel]); } if (isset($this->channels[$channel])) { return $this->channels[$channel]; } throw new InvalidArgumentException("Undefined channel: $channel"); }
php
{ "resource": "" }
q250823
Moo_EditableFieldNumeric.getFieldValidationOptions
validation
public function getFieldValidationOptions() { $min = ($this->getSetting('MinValue')) ? $this->getSetting('MinValue') : ''; $max = ($this->getSetting('MaxValue')) ? $this->getSetting('MaxValue') : ''; return [ new NumericField($this->getSettingName('MinValue'), _t('Moo_EditableField.MINVALUE', 'Min Value'), $min), new NumericField($this->getSettingName('MaxValue'), _t('Moo_EditableField.MAXVALUE', 'Max Value'), $max), ]; }
php
{ "resource": "" }
q250824
Router.addCachedRoute
validation
public function addCachedRoute(Route $route) { $this->routes->attach($route); if ($name = $route->getName()) { $this->addNamedRoute($name, $route); } }
php
{ "resource": "" }
q250825
Router.getRouteForRequest
validation
public function getRouteForRequest(Request $request) { $method = $request->getMethod(); $path = $request->getPathInfo() ?: '/'; $result = $this->getDispatcher() ->dispatch($method, $path); if ($result[0] == \FastRoute\Dispatcher::NOT_FOUND) { throw new NotFoundHttpException("No route match for path $path"); } else if ($result[0] == \FastRoute\Dispatcher::METHOD_NOT_ALLOWED) { throw new MethodNotAllowedHttpException($result[1], "Method $method not allowed for path $path"); } else if ($result[0] !== \FastRoute\Dispatcher::FOUND) { throw new \RuntimeException('Unknown result from FastRoute: '.$result[0]); } return $this->matchRoute($result[1], $result[2], $request); }
php
{ "resource": "" }
q250826
ExternalURL.Nice
validation
public function Nice() { if ($this->value && $parts = parse_url($this->URL())) { $remove = array('scheme', 'user', 'pass', 'port', 'query', 'fragment'); foreach ($remove as $part) { unset($parts[$part]); } return rtrim(http_build_url($parts), "/"); } }
php
{ "resource": "" }
q250827
ExternalURL.scaffoldFormField
validation
public function scaffoldFormField($title = null, $params = null) { $field = new ExternalURLField($this->name, $title); $field->setMaxLength($this->getSize()); return $field; }
php
{ "resource": "" }
q250828
Xml.getAttribute
validation
protected function getAttribute(SimpleXmlElement $node, $name) { $attributes = $node->attributes(); return (string) $attributes[$name]; }
php
{ "resource": "" }
q250829
Xml.isAttributeSet
validation
protected function isAttributeSet(SimpleXmlElement $node, $name) { $attributes = $node->attributes(); return isset($attributes[$name]); }
php
{ "resource": "" }
q250830
ActiveField.dropDownListDefault
validation
public function dropDownListDefault($items, $options = []) { Html::addCssClass($options, 'browser-default'); return parent::dropDownList($items, $options); }
php
{ "resource": "" }
q250831
ActiveField.radioWithGap
validation
public function radioWithGap($options = [], $enclosedByLabel = true) { Html::addCssClass($options, $this->radioGapCssClass); return self::radio($options, $enclosedByLabel); }
php
{ "resource": "" }
q250832
ActiveField.radioListWithGap
validation
public function radioListWithGap($items, $options = []) { $this->addListInputCssClass($options, $this->radioGapCssClass); return self::radioList($items, $options); }
php
{ "resource": "" }
q250833
ActiveField.checkboxFilled
validation
public function checkboxFilled($options = [], $enclosedByLabel = true) { Html::addCssClass($options, $this->checkboxFilledCssClass); return parent::checkbox($options, $enclosedByLabel); }
php
{ "resource": "" }
q250834
ActiveField.checkboxListFilled
validation
public function checkboxListFilled($items, $options = []) { $this->addListInputCssClass($options, $this->checkboxFilledCssClass); return self::checkboxList($items, $options); }
php
{ "resource": "" }
q250835
SessionProvider.makeSessionHandler
validation
public function makeSessionHandler() { $handler = $this->dic->resolve('Autarky\Http\SessionHandlerFactory') ->makeHandler($this->config->get('session.handler')); if ($this->config->get('session.write_check') === true) { $handler = new WriteCheckSessionHandler($handler); } return $handler; }
php
{ "resource": "" }
q250836
SessionProvider.makeSessionStorage
validation
public function makeSessionStorage() { $storage = $this->config->get('session.storage'); if ($storage == 'mock_array') { return new MockArraySessionStorage; } if ($storage == 'mock_file') { return new MockFileSessionStorage; } $handler = $this->dic->resolve('SessionHandlerInterface'); if ($storage == 'bridge') { return new PhpBridgeSessionStorage($handler); } $options = $this->config->get('session.storage_options', []); if ($storage == 'native') { return new NativeSessionStorage($options, $handler); } if (!is_string($storage)) { $storage = gettype($storage); } throw new \RuntimeException("Unknown session storage driver: $storage"); }
php
{ "resource": "" }
q250837
SessionProvider.makeSession
validation
public function makeSession() { $session = new Session( $this->dic->resolve('Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface'), $this->dic->resolve('Symfony\Component\HttpFoundation\Session\Attribute\AttributeBagInterface'), $this->dic->resolve('Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface') ); $session->setName($this->config->get('session.cookie.name', 'autarky_session')); return $session; }
php
{ "resource": "" }
q250838
ControllerTrait.flashMessages
validation
protected function flashMessages($messages) { $flashBag = $this->getSession() ->getFlashBag(); foreach ((array) $messages as $message) { $flashBag->add('_messages', $message); } }
php
{ "resource": "" }
q250839
ControllerTrait.flashInput
validation
protected function flashInput(Request $request = null) { if ($request === null) { $request = $this->container ->resolve('Symfony\Component\HttpFoundation\RequestStack') ->getCurrentRequest(); } $this->flash('_old_input', $request->request->all()); }
php
{ "resource": "" }
q250840
ControllerTrait.redirect
validation
protected function redirect($name, array $params = array(), $statusCode = 302) { return new RedirectResponse($this->url($name, $params), $statusCode); }
php
{ "resource": "" }
q250841
Vector.length
validation
public function length() { $sumOfSquares = 0; foreach ($this->components() as $component) { $sumOfSquares += pow($component, 2); } return sqrt($sumOfSquares); }
php
{ "resource": "" }
q250842
Vector.add
validation
public function add(self $b) { $this->_checkVectorSpace($b); $bComponents = $b->components(); $sum = []; foreach ($this->components() as $i => $component) { $sum[$i] = $component + $bComponents[$i]; } return new static($sum); }
php
{ "resource": "" }
q250843
Vector.dotProduct
validation
public function dotProduct(self $b) { $this->_checkVectorSpace($b); $bComponents = $b->components(); $product = 0; foreach ($this->components() as $i => $component) { $product += $component * $bComponents[$i]; } return $product; }
php
{ "resource": "" }
q250844
Vector.crossProduct
validation
public function crossProduct(self $b) { $this->_checkVectorSpace($b); if ($this->dimension() !== 3) { throw new Exception('Both vectors must be 3-dimensional'); } $tc = $this->components(); $bc = $b->components(); list($k0, $k1, $k2) = array_keys($tc); $product = [ $k0 => $tc[$k1] * $bc[$k2] - $tc[$k2] * $bc[$k1], $k1 => $tc[$k2] * $bc[$k0] - $tc[$k0] * $bc[$k2], $k2 => $tc[$k0] * $bc[$k1] - $tc[$k1] * $bc[$k0], ]; return new static($product); }
php
{ "resource": "" }
q250845
Vector.scalarTripleProduct
validation
public function scalarTripleProduct(self $b, self $c) { return $this->dotProduct($b->crossProduct($c)); }
php
{ "resource": "" }
q250846
Vector.vectorTripleProduct
validation
public function vectorTripleProduct(self $b, self $c) { return $this->crossProduct($b->crossProduct($c)); }
php
{ "resource": "" }
q250847
Vector.multiplyByScalar
validation
public function multiplyByScalar($scalar) { $result = []; foreach ($this->components() as $i => $component) { $result[$i] = $component * $scalar; } return new static($result); }
php
{ "resource": "" }
q250848
Vector.projectOnto
validation
public function projectOnto(self $b) { $bUnit = $b->normalize(); return $bUnit->multiplyByScalar($this->dotProduct($bUnit)); }
php
{ "resource": "" }
q250849
Vector.angleBetween
validation
public function angleBetween(self $b) { $denominator = $this->length() * $b->length(); if ($denominator == 0) { throw new Exception('Cannot divide by zero'); } return acos($this->dotProduct($b) / $denominator); }
php
{ "resource": "" }
q250850
Vector._checkVectorSpace
validation
protected function _checkVectorSpace(self $b) { if (!$this->isSameDimension($b)) { throw new Exception('The vectors must be of the same dimension'); } if (!$this->isSameVectorSpace($b)) { throw new Exception('The vectors\' components must have the same keys'); } }
php
{ "resource": "" }
q250851
UrlGenerator.getRouteUrl
validation
public function getRouteUrl($name, array $params = array(), $relative = false) { $route = $this->router->getRoute($name); $routeParams = []; $query = []; foreach ($params as $key => $value) { if (is_int($key)) { $routeParams[] = $value; } else { $query[$key] = $value; } } $path = $this->routePathGenerator->getRoutePath($route, $routeParams); if ($query) { $path .= '?'.http_build_query($query); } if ($relative) { $root = $this->requests->getCurrentRequest() ->getBaseUrl(); } else { $root = $this->getRootUrl(); } return $root . $path; }
php
{ "resource": "" }
q250852
UrlGenerator.getAssetUrl
validation
public function getAssetUrl($path, $relative = false) { if (substr($path, 0, 1) !== '/') { $path = '/'.$path; } if ($this->assetRoot !== null) { $base = $this->assetRoot; } else if ($relative) { $base = $this->requests ->getCurrentRequest() ->getBaseUrl(); } else { $base = $this->getRootUrl(); } return $base . $path; }
php
{ "resource": "" }
q250853
UrlGenerator.getRootUrl
validation
public function getRootUrl() { $request = $this->requests->getCurrentRequest(); $host = $request->getHttpHost(); $base = $request->getBaseUrl(); return rtrim("//$host/$base", '/'); }
php
{ "resource": "" }
q250854
GuzzleServiceProvider.register
validation
public function register(Container $app) { $app['guzzle.handler_stack'] = function () { $stack = HandlerStack::create(); return $stack; }; $app['guzzle'] = function () use ($app) { $client = new HttpClient([ 'handler' => $app['guzzle.handler_stack'] ]); return $client; }; }
php
{ "resource": "" }
q250855
ApiKeyAuthenticationProvider.authenticate
validation
public function authenticate(TokenInterface $token) { $user = $this->userProvider->loadUserByApiKey($this->encoder->encodePassword($token->getCredentials())); if (!$user || !($user instanceof UserInterface)) { throw new AuthenticationException('Bad credentials'); } $token = new ApiKeyToken($token->getCredentials(), $user->getRoles()); $token->setUser($user); return $token; }
php
{ "resource": "" }
q250856
AgnosticReader.addManagerRegistry
validation
public function addManagerRegistry(ManagerRegistry $registry) { if (!in_array($registry, $this->registries, true)) { $this->registries[] = $registry; } }
php
{ "resource": "" }
q250857
Application.registerCommands
validation
public function registerCommands(array $commands, callable $handler) { foreach ($commands as $command) { $handler_id = "app.handler." . join('', array_slice(explode("\\", $command), -1)); $this[$handler_id] = $handler; } }
php
{ "resource": "" }
q250858
Application.registerSubscriber
validation
public function registerSubscriber($class, callable $callback) { $service_id = "event." . strtolower(str_replace("\\", ".", $class)); $this[$service_id] = $callback; $this["dispatcher"]->addSubscriberService($service_id, $class); }
php
{ "resource": "" }
q250859
Application.registerStackMiddleware
validation
public function registerStackMiddleware($class) { if (func_num_args() === 0) { throw new \InvalidArgumentException("Missing argument(s) when calling registerStackMiddlerware"); } if (! class_exists($class) && ! is_callable($class)) { throw new \InvalidArgumentException("{$class} not found or not callable"); } call_user_func_array([$this->builder, "push"], func_get_args()); }
php
{ "resource": "" }
q250860
Recaptcha.checkAnswer
validation
public function checkAnswer($extraParams = array()) { $remoteIp = $_SERVER["REMOTE_ADDR"]; $challenge = $_POST["recaptcha_challenge_field"]; $response = $_POST["recaptcha_response_field"]; if ( ! $this->getPrivateKey()) { throw new \Exception("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>"); } if ( ! $remoteIp) { throw new \Exception("For security reasons, you must pass the remote ip to reCAPTCHA"); } if ( ! $challenge) { // discard spam submissions $this->valid = false; $this->error = 'incorrect-captcha-sol'; } else { // or check user input $response = $this->httpPost(self::RECAPTCHA_VERIFY_SERVER, '/recaptcha/api/verify', array( 'privatekey' => $this->getPrivateKey(), 'remoteip' => $remoteIp, 'challenge' => $challenge, 'response' => $response, ) + $extraParams ); $answers = explode("\n", $response[1]); if (trim($answers[0]) == 'true') { $this->valid = true; } else { $this->valid = false; $this->error = $answers[1]; } } return $this; }
php
{ "resource": "" }
q250861
Recaptcha.httpPost
validation
protected function httpPost($host, $path, array $data, $port = 80) { $req = $this->qsencode($data); $http_request = "POST {$path} HTTP/1.0\r\n"; $http_request .= "Host: {$host}\r\n"; $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $http_request .= "Content-Length: " . strlen($req) . "\r\n"; $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; $http_request .= "\r\n"; $http_request .= $req; $response = ''; if(false == ($fs = @fsockopen($host, (int)$port, $errno, $errstr, 10))) { throw new \Exception('Could not open socket'); } fwrite($fs, $http_request); while ( ! feof($fs)) { $response .= fgets($fs, 1160); // One TCP-IP packet } fclose($fs); $response = explode("\r\n\r\n", $response, 2); return $response; }
php
{ "resource": "" }
q250862
Recaptcha.qsencode
validation
protected function qsencode(array $data = array()) { $req = ''; if ($data) { foreach ($data as $key => $value) { $req .= $key . '=' . urlencode(stripslashes($value)) . '&'; } $req = substr($req, 0, strlen($req) - 1); // Cut the last '&' } return $req; }
php
{ "resource": "" }
q250863
ConnectionManager.getPdo
validation
public function getPdo($connection = null) { if ($connection === null) { $connection = $this->defaultConnection; } if (isset($this->instances[$connection])) { return $this->instances[$connection]; } $config = $this->getConnectionConfig($connection); return $this->instances[$connection] = $this->factory->makePdo($config, $connection); }
php
{ "resource": "" }
q250864
ConnectionManager.getConnectionConfig
validation
public function getConnectionConfig($connection = null) { if ($connection === null) { $connection = $this->defaultConnection; } $config = $this->config->get("database.connections.$connection"); if (!$config) { if (!is_string($connection)) { $connection = gettype($connection); } throw new \InvalidArgumentException("No config found for connection: $connection"); } return $config; }
php
{ "resource": "" }
q250865
SessionHandlerFactory.makeHandler
validation
public function makeHandler($ident) { if (!isset($this->factories[$ident])) { throw new \InvalidArgumentException("Unknown session handler: $ident"); } return $this->factories[$ident](); }
php
{ "resource": "" }
q250866
AbstractSuperHeroApi.getById
validation
public function getById($characterId) { try { $result = $this->client->get($this->slug . '/' . $characterId); } catch (RequestException $e) { $return['request'] = $e->getRequest() . "\n"; if ($e->hasResponse()) { return $return['response'] = $e->getResponse() . "\n"; } } return $result->json(); }
php
{ "resource": "" }
q250867
AbstractSuperHeroApi.getAll
validation
public function getAll(array $filterAttributes = []) { $filters = ['query' => [$filterAttributes]]; try { $result = $this->client->get($this->slug, $filters); } catch (RequestException $e) { $return['request'] = $e->getRequest() . "\n"; if ($e->hasResponse()) { return $return['response'] = $e->getResponse() . "\n"; } } return $result->json(); }
php
{ "resource": "" }
q250868
AbstractRouter.matchParams
validation
protected function matchParams(Route $route, array $params) : bool { $matchers = $route->getMatchers(); foreach ($params as $name => $value) { if (!isset($matchers[$name])) { continue; } $valueMatchers = $matchers[$name]; foreach ($valueMatchers as $matcher) { if (!$matcher($value)) { $this->logger->debug(sprintf( 'Value "%s" for param "%s" did not match criteria of matcher "%s"', $value, $name, get_class($matcher) )); return false; } } } return true; }
php
{ "resource": "" }
q250869
AbstractRouter.validateParams
validation
protected function validateParams(Route $route, array $params, array $requiredParams) { $identifier = $this->getRouteIdentifier($route); $givenParams = array_keys($params); $missingParams = array_diff($requiredParams, $givenParams); if (count($missingParams) > 0) { throw new \InvalidArgumentException( sprintf( 'Error while validating params "%s": Required parameters "%s" are missing', $identifier, implode(', ', $missingParams) ) ); } if (!$this->matchParams($route, $params)) { throw new \InvalidArgumentException( sprintf( 'Error while validing params for target "%s": Params don\'t fulfill their matcher\'s criteria', $identifier ) ); } }
php
{ "resource": "" }
q250870
AbstractRouter.getRouteIdentifier
validation
protected function getRouteIdentifier(Route $route) : string { return empty($route->getName()) ? $route->getTarget() : $route->getName(); }
php
{ "resource": "" }
q250871
Ftp.verifyAndMoveUploadedFile
validation
public function verifyAndMoveUploadedFile( $originSize, $tmpDestination, $publicDestination ) { $remoteTempSize = $this->getSize($tmpDestination); $this->logger->debug('Temp size: ' . $remoteTempSize); $this->logger->debug('Origin size: ' . $originSize); if ($remoteTempSize <= 0) { throw new VerifySizeException('Uploaded file has size ' . $remoteTempSize); } if ($remoteTempSize !== $originSize) { throw new VerifySizeException( sprintf( 'Uploaded file has wrong size. Expected %s, got %s.', $originSize, $remoteTempSize ) ); } $this->logger->info('OK: Uploaded temp file has right size.'); if (!$this->move($tmpDestination, $publicDestination)) { throw new FtpException('Error renaming uploaded file from temp to public.'); } $remotePublicSize = $this->getSize($publicDestination); $this->logger->debug('Renamed size: ' . $remotePublicSize); if ($remotePublicSize <= 0) { throw new VerifySizeException('Renamed file has size ' . $remotePublicSize); } if ($remotePublicSize !== $originSize) { throw new VerifySizeException( sprintf( 'Renamed file has wrong size. Expected %s, got %s.', $originSize, $remotePublicSize ) ); } $this->logger->info('OK: Renamed file has right size.'); return true; }
php
{ "resource": "" }
q250872
Moo_EditableField.setSetting
validation
public function setSetting($key, $value) { $settings = $this->getSettings(); $settings[$key] = $value; $this->setSettings($settings); }
php
{ "resource": "" }
q250873
Moo_EditableField.getSetting
validation
public function getSetting($setting) { $settings = $this->getSettings(); if (isset($settings) && count($settings) > 0) { if (isset($settings[$setting])) { return $settings[$setting]; } } return ''; }
php
{ "resource": "" }
q250874
Moo_EditableField.onBeforeWrite
validation
public function onBeforeWrite() { $return = parent::onBeforeWrite(); // Field name must be unique $exists = self::get()->filter('Name', $this->Name)->exclude('ID', $this->ID); if ($exists->count()) { throw new ValidationException( _t('Moo_EditableField.UNIQUENAME', 'Field name "{name}" must be unique', '', ['name' => $this->Name]) ); } // Filter field name from un-supported HTML attribute value $this->Name = preg_replace('/[^a-zA-Z0-9_]+/', '', $this->Name); // Get custom settings from the current object of request POST $customSettings = $this->getSettings(); if (empty($customSettings)) { $customSettings = (array) Controller::curr()->getRequest()->postVar('CustomSettings'); } // Filter out any un-supported settings by the subclasss if (!empty($this->customSettingsFields)) { $customSettings = array_intersect_key($customSettings, array_flip((array) $this->customSettingsFields)); } // Set the filtered settings $this->setSettings($customSettings); return $return; }
php
{ "resource": "" }
q250875
Moo_EditableField.getFormField
validation
public function getFormField() { if (null === $this->field) { $this->field = $this->initFormField(); } return $this->field; }
php
{ "resource": "" }
q250876
LockingFilesystem.read
validation
public function read($path, $blocking = false) { $size = filesize($path); if ($size === 0) { return ''; } $flockFlags = $blocking ? LOCK_SH : LOCK_SH | LOCK_NB; $file = fopen($path, 'r'); if (!flock($file, $flockFlags)) { fclose($file); throw new IOException("Could not aquire file lock for file: $path"); } $contents = fread($file, $size); flock($file, LOCK_UN | LOCK_NB); fclose($file); return $contents; }
php
{ "resource": "" }
q250877
LockingFilesystem.write
validation
public function write($path, $contents, $blocking = false) { $flockFlags = $blocking ? LOCK_EX : LOCK_EX | LOCK_NB; $file = fopen($path, 'c'); if (!flock($file, $flockFlags)) { fclose($file); throw new IOException("Could not aquire file lock for file: $path"); } ftruncate($file, 0); fwrite($file, $contents); fflush($file); flock($file, LOCK_UN | LOCK_NB); fclose($file); }
php
{ "resource": "" }
q250878
ApiKeyAuthenticationListener.handle
validation
public function handle(GetResponseEvent $event) { $apiKey = $this->getApiKeyFromQueryOrHeader($event->getRequest()); if (false === $apiKey) { return; } try { $token = $this->authenticationManager->authenticate(new ApiKeyToken($apiKey)); $this->tokenStorage->setToken($token); } catch (AuthenticationException $failed) { $this->tokenStorage->setToken(null); $this->doFailureResponse($event); } }
php
{ "resource": "" }
q250879
ExternalURLField.getAttributes
validation
public function getAttributes() { $attributes = array( 'placeholder' => $this->config['defaultparts']['scheme'] . "://example.com" //example url ); if ($this->config['html5validation']) { $attributes += array( 'type' => 'url', //html5 field type 'pattern' => 'https?://.+', //valid urls only ); } return array_merge( parent::getAttributes(), $attributes ); }
php
{ "resource": "" }
q250880
ExternalURLField.setValue
validation
public function setValue($url) { if ($url) { $url = $this->rebuildURL($url); } parent::setValue($url); }
php
{ "resource": "" }
q250881
ExternalURLField.rebuildURL
validation
protected function rebuildURL($url) { $defaults = $this->config['defaultparts']; if (!preg_match('#^[a-zA-Z]+://#', $url)) { $url = $defaults['scheme'] . "://" . $url; } $parts = parse_url($url); if (!$parts) { //can't parse url, abort return ""; } foreach ($parts as $part => $value) { if ($this->config['removeparts'][$part] === true) { unset($parts[$part]); } } //set defaults, if missing foreach ($defaults as $part => $default) { if (!isset($parts[$part])) { $parts[$part] = $default; } } return rtrim(http_build_url($defaults, $parts), "/"); }
php
{ "resource": "" }
q250882
ExternalURLField.validate
validation
public function validate($validator) { $this->value = trim($this->value); $regex = $this->config['validregex']; if ($this->value && $regex && !preg_match($regex, $this->value)) { $validator->validationError( $this->name, _t('ExternalURLField.VALIDATION', "Please enter a valid URL"), "validation" ); return false; } return true; }
php
{ "resource": "" }
q250883
PathResolver.resolve
validation
public function resolve($path) { $paths = []; foreach ($this->paths as $configuredPath) { $paths[] = $configuredPath.'/'.$path; } $parts = explode('/', $path); // this doesn't change behaviour but will save some performance if (count($parts) == 1) { return $paths; } $current = ''; $mountPaths = []; foreach ($parts as $part) { if ($current) { $current .= '/'.$part; } else { $current = $part; } if (isset($this->mounts[$current])) { foreach ($this->mounts[$current] as $mount) { // relative to mount directory $relativePath = str_replace($current, '', $path); $mountPaths[] = $mount.$relativePath; } } } return array_merge($mountPaths, $paths); }
php
{ "resource": "" }
q250884
DriverFactory.getDriver
validation
public static function getDriver(MappingDriver $originalDriver, $namespace) { /*if (\Doctrine\Common\Version::compare('2.3.0') > -1) { throw new \Exception('The DMR library requires Doctrine 2.3.0 or higher.'); }*/ if ($originalDriver instanceof MappingDriverChain) { $driver = new Driver\Chain(); foreach ($originalDriver->getDrivers() as $nestedNamespace => $nestedDriver) { $driver->addDriver(static::getDriver($nestedDriver, $namespace), $nestedNamespace); } if ($originalDriver->getDefaultDriver() !== null) { $driver->setDefaultDriver(static::getDriver($originalDriver->getDefaultDriver(), $namespace)); } return $driver; } preg_match('/(?P<type>Xml|Yaml|Annotation)Driver$/', get_class($originalDriver), $m); $type = isset($m['type']) ? $m['type'] : null; $driverClass = sprintf('%s\Mapping\Driver\%s', $namespace, $type); // Fallback driver if (!$type || !class_exists($driverClass)) { $driverClass = sprintf('%s\Mapping\Driver\Annotation', $namespace); if (!class_exists($driverClass)) { throw new \RuntimeException(sprintf('Failed to fallback to annotation driver: (%s), extension driver was not found.', $driverClass)); } } $driver = new $driverClass(); $driver->setOriginalDriver($originalDriver); if ($driver instanceof Driver\File) { $driver->setLocator($originalDriver->getLocator()); } elseif ($driver instanceof AnnotationDriverInterface) { $reader = static::getAnnotationReader(); $driver->setAnnotationReader($reader); } return $driver; }
php
{ "resource": "" }
q250885
Psr7Router.mapParams
validation
protected function mapParams(array $params) : array { unset($params[0]); foreach ($params as $name => $value) { if (!is_string($name)) { unset($params[$name]); } else { $params[$name] = urldecode($value[0]); } } return $params; }
php
{ "resource": "" }
q250886
ConnectionFactory.makePdo
validation
public function makePdo(array $config, $connection = null) { if (!isset($config['driver']) && !isset($config['dsn'])) { throw new InvalidArgumentException('DSN or driver must be set'); } $options = isset($config['pdo_options']) ? $config['pdo_options'] : []; unset($config['pdo_options']); $options = array_replace($this->defaultPdoOptions, $options); $initCommands = isset($config['pdo_init_commands']) ? $config['pdo_init_commands'] : []; unset($config['pdo_init_commands']); // SQLite needs special treatment if (isset($config['driver']) && $config['driver'] == 'sqlite') { $this->validate($config, 'path', $connection); $dsn = $this->makeSqliteDsn($config['path']); return $this->makePdoInner($dsn, null, null, $options, $initCommands); } elseif (isset($config['dsn']) && strpos($config['dsn'], 'sqlite:') === 0) { return $this->makePdoInner($config['dsn'], null, null, $options, $initCommands); } $this->validate($config, 'username', $connection, false); $username = $config['username']; unset($config['username']); $this->validate($config, 'password', $connection, true); $password = $config['password']; unset($config['password']); if (isset($config['dsn'])) { $dsn = $config['dsn']; } else { $driver = $config['driver']; unset($config['driver']); $this->validate($config, 'host', $connection); $this->validate($config, 'dbname', $connection); $dsn = $this->makeDsn($driver, $config); } return $this->makePdoInner($dsn, $username, $password, $options, $initCommands); }
php
{ "resource": "" }
q250887
RouteBuilder.build
validation
public function build() : Route { return new $this->routeClass($this->methods, $this->path, $this->target, $this->matchers, $this->name); }
php
{ "resource": "" }
q250888
RouteBuilder.whateverMatches
validation
public function whateverMatches(string $param) : RouteBuilder { if (array_key_exists($param, $this->matchers)) { unset($this->matchers[$param]); } return $this; }
php
{ "resource": "" }
q250889
ConstantSetMatcher.getConstantValues
validation
protected function getConstantValues(string $classIdentifier, string $regex) : array { $reflectionClass = new \ReflectionClass($classIdentifier); $constants = $reflectionClass->getConstants(); $validValues = array_filter($constants, function ($constantName) use ($regex) { return preg_match($regex, $constantName); }, ARRAY_FILTER_USE_KEY); return $validValues; }
php
{ "resource": "" }
q250890
File.getMapping
validation
public function getMapping($className) { // Try loading mapping from original driver first $mapping = null; if (null != $this->originalDriver) { if ($this->originalDriver instanceof FileDriver) { $mapping = $this->originalDriver->getElement($className); } } // If no mapping found try to load mapping file again if (null == $mapping) { $mappings = $this->loadMappingFile($this->locator->findMappingFile($className)); $mapping = $mappings[$className]; } return $mapping; }
php
{ "resource": "" }
q250891
Moo_EditableFieldMultipleOption.delete
validation
public function delete() { $options = $this->Options(); if ($options) { foreach ($options as $option) { $option->delete(); } } parent::delete(); }
php
{ "resource": "" }
q250892
Moo_EditableFieldMultipleOption.duplicate
validation
public function duplicate($doWrite = true) { $clonedNode = parent::duplicate($doWrite); if ($this->Options()) { foreach ($this->Options() as $field) { $newField = $field->duplicate(); $newField->ParentID = $clonedNode->ID; $newField->write(); } } return $clonedNode; }
php
{ "resource": "" }
q250893
Moo_EditableFieldMultipleOption.initFormField
validation
protected function initFormField() { $options = $this->Options()->map('EscapedTitle', 'Title'); return new OptionsetField($this->Name, $this->Title, $options); }
php
{ "resource": "" }
q250894
LoaderFactory.addLoader
validation
public function addLoader($extensions, $loaderClass) { foreach ((array) $extensions as $extension) { $this->extensions[] = $extension; if (is_string($loaderClass)) { $this->loaderClasses[$extension] = $loaderClass; } elseif ($loaderClass instanceof LoaderInterface) { $this->loaders[$extension] = $loaderClass; } } }
php
{ "resource": "" }
q250895
LoaderFactory.getForPath
validation
public function getForPath($path) { $extension = $this->getExtension($path); if (!isset($this->loaders[$extension])) { $this->resolveLoader($extension); } return $this->loaders[$extension]; }
php
{ "resource": "" }
q250896
Configuration.override
validation
public function override($name, array $routeData) { if (!isset($this->routes[$name])) { throw new \InvalidArgumentException("No route for name $name defined"); } $this->routes[$name] = $routeData + $this->routes[$name]; }
php
{ "resource": "" }
q250897
Configuration.merge
validation
public function merge(array $routes) { foreach ($routes as $name => $route) { $this->override($name, $route); } }
php
{ "resource": "" }
q250898
Configuration.mount
validation
public function mount($prefix = null) { if ($prefix) { $this->router->group(['prefix' => $prefix], function() { $this->registerRoutes(); }); } else { $this->registerRoutes(); } }
php
{ "resource": "" }
q250899
IOFactory.createWriter
validation
public static function createWriter(Spreadsheet $spreadsheet, $writerType) { if (!isset(self::$writers[$writerType])) { throw new Writer\Exception("No writer found for type $writerType"); } // Instantiate writer $className = self::$writers[$writerType]; $writer = new $className($spreadsheet); return $writer; }
php
{ "resource": "" }