_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q5000
Helper.dateDiff
train
public static function dateDiff($from, $to = null) { if (!$to) { $to = $from; $from = date("d/m/Y"); } if (!$dateFrom = static::date("U", $from)) { return; } if (!$dateTo = static::date("U", $to)) { return; } $diff = $dateTo - $dateFrom; $days = round($diff / 86400); return $days; }
php
{ "resource": "" }
q5001
Helper.getBestDivisor
train
public static function getBestDivisor($rows, $options = null) { $options = static::getOptions($options, [ "min" => 5, "max" => 10, ]); if ($rows <= $options["max"]) { return $rows; } $divisor = false; $divisorDiff = false; for ($i = $options["max"]; $i >= $options["min"]; $i--) { $remain = $rows % $i; # Calculate how close the remainder is to the postentional divisor $quality = $i - $remain; # If no divisor has been set yet then set it to this one, and record it's quality if (!$num) { $divisor = $i; $divisorQuality = $quality; continue; } # If the potentional divisor is a better match than the currently selected one then select it instead if ($quality < $divisorQuality) { $divisor = $i; $divisorQuality = $quality; } } return $divisor; }
php
{ "resource": "" }
q5002
Helper.createPassword
train
public static function createPassword($options = null) { $options = static::getOptions($options, [ "bad" => ["1", "l", "I", "5", "S", "0", "O", "o"], "exclude" => [], "length" => 10, "lowercase" => true, "uppercase" => true, "numbers" => true, "specialchars" => true, ]); $password = ""; if (!$options["lowercase"] && !$options["specialchars"] && !$options["numbers"] && !$options["uppercase"]) { return $password; } $exclude = array_merge($options["bad"], $options["exclude"]); # Keep adding characters until the password is at least as long as required while (mb_strlen($password) < $options["length"]) { # Add a few characters from each acceptable set if ($options["lowercase"]) { $max = rand(1, 3); for ($i = 0; $i < $max; ++$i) { $password .= chr(rand(97, 122)); } } if ($options["specialchars"]) { $max = rand(1, 3); for ($i = 0; $i < $max; ++$i) { switch (rand(0, 3)) { case 0: $password .= chr(rand(33, 47)); break; case 1: $password .= chr(rand(58, 64)); break; case 2: $password .= chr(rand(91, 93)); break; case 3: $password .= chr(rand(123, 126)); break; } } } if ($options["numbers"]) { $max = rand(1, 3); for ($i = 0; $i < $max; ++$i) { $password .= chr(rand(48, 57)); } } if ($options["uppercase"]) { $max = rand(1, 3); for ($i = 0; $i < $max; ++$i) { $password .= chr(rand(65, 90)); } } # Remove excluded characters $password = str_replace($exclude, "", $password); } # Reduce the length of the generated password to the required length $password = mb_substr($password, 0, $options["length"]); return $password; }
php
{ "resource": "" }
q5003
Helper.checkPassword
train
public static function checkPassword($password, $options = null) { $options = static::getOptions($options, [ "length" => 8, "unique" => 4, "lowercase" => true, "uppercase" => true, "alpha" => true, "numeric" => true, ]); $problems = []; $len = mb_strlen($password); if ($len < $options["length"]) { $problems["length"] = "Passwords must be at least " . $options["length"] . " characters long"; } $unique = []; for ($i = 0; $i < $len; ++$i) { $char = mb_substr($password, $i, 1); if (!in_array($char, $unique)) { $unique[] = $char; } } if (count($unique) < $options["unique"]) { $problems["unique"] = "Passwords must contain at least " . $options["unique"] . " unique characters"; } if (!preg_match("/[a-z]/", $password)) { $problems["lowercase"] = "Passwords must contain at least 1 lowercase letter"; } if (!preg_match("/[A-Z]/", $password)) { $problems["uppercase"] = "Passwords must contain at least 1 uppercase letter"; } if (!preg_match("/[a-z]/i", $password)) { $problems["alpha"] = "Passwords must contain at least 1 letter"; } if (!preg_match("/[0-9]/", $password)) { $problems["numeric"] = "Passwords must contain at least 1 number"; } return $problems; }
php
{ "resource": "" }
q5004
MarkupValidatorMessage.setType
train
public function setType($type) { if ($type === null) { $type = self::TYPE_UNDEFINED; } $this->type = $type; return $this; }
php
{ "resource": "" }
q5005
Bootstrap.initEventsManager
train
public function initEventsManager() { $taskListener = new TaskListener(); //extracts default events manager $eventsManager = $this->di->getShared('eventsManager'); //attaches new event console:beforeTaskHandle and console:afterTaskHandle $eventsManager->attach( 'console:beforeHandleTask', $taskListener->beforeHandleTask($this->arguments) ); $eventsManager->attach( 'console:afterHandleTask', $taskListener->afterHandleTask() ); $this->application->setEventsManager($eventsManager); }
php
{ "resource": "" }
q5006
RetryCount.create
train
public static function create($body, DescriptionFactory $descriptionFactory = null, Context $context = null) { Assert::integerish($body, self::MSG); Assert::greaterThanEq($body, 0, self::MSG); Assert::notNull($descriptionFactory); return new static($descriptionFactory->create($body, $context)); }
php
{ "resource": "" }
q5007
ProtectedResourceTarget.detectResourcesBaseUri
train
protected function detectResourcesBaseUri() { $uri = ''; $request = $this->getHttpRequest(); if ($request instanceof HttpRequest) { $uri = $request->getBaseUri(); } return (string)$uri; }
php
{ "resource": "" }
q5008
ServiceManager.getService
train
public function getService($name) { try { if (!$this->isRegisteredService($name)) { $this->registerService($name); } return $this->di->get($name); } catch (\Phalcon\DI\Exception $ex) { throw new Exception($ex->getMessage().', using: '.$name); } }
php
{ "resource": "" }
q5009
ServiceManager.hasService
train
public function hasService($name) { try { $service = $this->getService($name); return !empty($service); } catch (\Vegas\DI\Service\Exception $ex) { return false; } }
php
{ "resource": "" }
q5010
ControllerAbstract.jsonResponse
train
protected function jsonResponse($data = array()) { $this->view->disable(); $this->response->setContentType('application/json', 'UTF-8'); return $this->response->setJsonContent($data); }
php
{ "resource": "" }
q5011
PackageConverter.getForce
train
protected function getForce(PropertyMappingConfigurationInterface $configuration = null) { if ($configuration === null) { throw new InvalidPropertyMappingConfigurationException('Missing property configuration', 1457516367); } return (boolean)$configuration->getConfigurationValue(PackageConverter::class, self::FORCE); }
php
{ "resource": "" }
q5012
Html.getCurrencies
train
public static function getCurrencies($symbols = null) { $currencies = Cache::call("get-currencies", function() { $currencies = Yaml::decodeFromFile(__DIR__ . "/../data/currencies.yaml"); if ($currencies instanceof SerialObject) { $currencies = $currencies->asArray(); } return array_map(function($data) { if (!isset($data["prefix"])) { $data["prefix"] = ""; } if (!isset($data["suffix"])) { $data["suffix"] = ""; } return $data; }, $currencies); }); if ($symbols) { return $currencies; } $return = []; foreach ($currencies as $key => $val) { $return[$key] = $val["title"]; } return $return; }
php
{ "resource": "" }
q5013
Html.formatKey
train
public static function formatKey($key, $options = null) { $options = Helper::getOptions($options, [ "underscores" => true, "ucwords" => true, ]); if ($options["underscores"]) { $val = str_replace("_", "&nbsp;", $key); } if ($options["ucwords"]) { $val = ucwords($val); } return $val; }
php
{ "resource": "" }
q5014
Html.string
train
public static function string($string, $options = null) { $options = Helper::getOptions($options, [ "alt" => "n/a", ]); $string = trim($string); if (!$string) { return $options["alt"]; } return $string; }
php
{ "resource": "" }
q5015
Html.stringLimit
train
public static function stringLimit($string, $options = null) { $options = Helper::getOptions($options, [ "length" => 30, "extra" => 0, "alt" => "n/a", "words" => true, "suffix" => "...", ]); if (!$string = trim($string)) { return $options["alt"]; } if ($options["words"]) { while (mb_strlen($string) > ($options["length"] + $options["extra"])) { $string = mb_substr($string, 0, $options["length"]); $string = trim($string); $words = explode(" ", $string); array_pop($words); $string = implode(" ", $words); $string .= $options["suffix"]; } } else { $length = $options["length"] + $options["extra"] + mb_strlen($options["suffix"]); if (mb_strlen($string) > $length) { $string = mb_substr($string, 0, $length); $string .= $options["suffix"]; } } return $string; }
php
{ "resource": "" }
q5016
Loader.parseArguments
train
public function parseArguments(Console $console, $arguments) { $this->consoleApp = $console; if (count($arguments) == 1) { throw new TaskNotFoundException(); } $taskName = $this->lookupTaskClass($arguments); //prepares an array containing arguments for CLI handler $parsedArguments = array( 'task' => $taskName, 'action' => isset($arguments[2]) ? $arguments[2] : false ); //adds additional arguments $parsedArguments[] = count($arguments) > 3 ? array_slice($arguments, 3) : array(); return $parsedArguments; }
php
{ "resource": "" }
q5017
Loader.toNamespace
train
private function toNamespace($str) { $stringParts = preg_split('/_+/', $str); foreach($stringParts as $key => $stringPart){ $stringParts[$key] = ucfirst(strtolower($stringPart)); } return implode('\\', $stringParts) . '\\'; }
php
{ "resource": "" }
q5018
Loader.loadAppTask
train
private function loadAppTask(array $task) { //if task name contains more than 2 parts then it comes from module if (count($task) > 2) { $moduleName = ucfirst($task[1]); $taskName = ucfirst($task[2]); $taskName = $this->loadAppModuleTask($moduleName, $taskName); } else { $taskName = ucfirst($task[1]); } return $taskName; }
php
{ "resource": "" }
q5019
Loader.loadAppModuleTask
train
private function loadAppModuleTask($moduleName, $taskName) { $modules = $this->consoleApp->getModules(); //checks if indicated module has been registered if (!isset($modules[$moduleName])) { throw new TaskNotFoundException(); } //creates full namespace for task class placed in application module $fullNamespace = strtr('\:moduleName\Tasks\:taskName', array( ':moduleName' => $moduleName, ':taskName' => $taskName )); //registers task class in Class Loader $this->registerClass($fullNamespace . 'Task'); //returns converted name of task (namespace of class containing task) return $fullNamespace; }
php
{ "resource": "" }
q5020
Loader.loadCoreTask
train
private function loadCoreTask(array $task) { //creates full namespace for task placed in Vegas library if (count($task) == 3) { $namespace = $this->toNamespace($task[1]); $taskName = ucfirst($task[2]); } else { //for \Vegas namespace tasks are placed in \Vegas\Task namespace $namespace = ''; $taskName = ucfirst($task[1]); } $fullNamespace = strtr('\Vegas\:namespaceTask\\:taskName', array( ':namespace' => $namespace, ':taskName' => $taskName )); //registers task class in Class Loader $this->registerClass($fullNamespace . 'Task'); //returns converted name of task (namespace of class containing task) return $fullNamespace; }
php
{ "resource": "" }
q5021
Topics.createForumTopic
train
public function createForumTopic($forumID, $authorID, $title, $post, $extra = []) { $data = ["forum" => $forumID, "author" => $authorID, "title" => $title, "post" => $post]; $data = array_merge($data, $extra); $validator = \Validator::make($data, [ "forum" => "required|numeric", "author" => "required|numeric", "title" => "required|string", "post" => "required|string", "author_name" => "required_if:author,0|string", "prefix" => "string", "tags" => "string|is_csv_alphanumeric", "date" => "date_format:YYYY-mm-dd H:i:s", "ip_address" => "ip", "locked" => "in:0,1", "open_time" => "date_format:YYYY-mm-dd H:i:s", "close_time" => "date_format:YYYY-mm-dd H:i:s", "hidden" => "in:-1,0,1", "pinned" => "in:0,1", "featured" => "in:0,1", ], [ "is_csv_alphanumeric" => "The :attribute must be a comma separated string.", ]); if ($validator->fails()) { $message = head(array_flatten($validator->messages())); throw new Exceptions\InvalidFormat($message); } return $this->postRequest("forums/topics", $data); }
php
{ "resource": "" }
q5022
Topics.updateForumTopic
train
public function updateForumTopic($topicID, $data = []) { $validator = \Validator::make($data, [ "forum" => "numeric", "author" => "numeric", "author_name" => "required_if:author,0|string", "title" => "string", "post" => "string", "prefix" => "string", "tags" => "string|is_csv_alphanumeric", "date" => "date_format:YYYY-mm-dd H:i:s", "ip_address" => "ip", "locked" => "in:0,1", "open_time" => "date_format:YYYY-mm-dd H:i:s", "close_time" => "date_format:YYYY-mm-dd H:i:s", "hidden" => "in:-1,0,1", "pinned" => "in:0,1", "featured" => "in:0,1", ], [ "is_csv_alphanumeric" => "The :attribute must be a comma separated string.", ]); if ($validator->fails()) { $message = head(array_flatten($validator->messages())); throw new Exceptions\InvalidFormat($message); } return $this->postRequest("forums/topics/" . $topicID, $data); }
php
{ "resource": "" }
q5023
TaskAbstract.beforeExecuteRoute
train
public function beforeExecuteRoute() { //sets active task and action names $this->actionName = $this->dispatcher->getActionName(); $this->taskName = $this->dispatcher->getTaskName(); $this->setupOptions(); //if -h or --help option was typed in command line then show only help $this->args = $this->dispatcher->getParam('args'); if ($this->containHelpOption($this->args)) { $this->renderActionHelp(); //stop dispatching return false; } try { $this->validate($this->args); } catch (InvalidArgumentException $ex) { $this->throwError(strtr(':command: Invalid argument `:argument` for option `:option`', [ ':command' => sprintf('%s %s', $this->dispatcher->getParam('activeTask'), $this->dispatcher->getParam('activeAction')), ':option' => $ex->getOption(), ':argument' => $ex->getArgument() ])); } catch (InvalidOptionException $ex) { $this->throwError(strtr(':command: Invalid option `:option`', [ ':command' => sprintf('%s %s', $this->dispatcher->getParam('activeTask'), $this->dispatcher->getParam('activeAction')), ':option' => $ex->getOption() ])); } return true; }
php
{ "resource": "" }
q5024
TaskAbstract.containHelpOption
train
private function containHelpOption($args) { return array_key_exists(self::HELP_OPTION, $args) || array_key_exists(self::HELP_SHORTOPTION, $args); }
php
{ "resource": "" }
q5025
TaskAbstract.getOption
train
protected function getOption($name, $default = null) { $matchedOption = null; foreach ($this->actions[$this->actionName]->getOptions() as $option) { if ($option->matchParam($name)) { $matchedOption = $option; } } $value = $matchedOption->getValue($this->args, $default); return $value; }
php
{ "resource": "" }
q5026
TaskAbstract.renderActionHelp
train
protected function renderActionHelp() { $action = $this->actions[$this->actionName]; //puts name of action $this->appendLine($this->getColoredString($action->getDescription(), 'green')); $this->appendLine(''); //puts usage hint $this->appendLine('Usage:'); $this->appendLine($this->getColoredString(sprintf( ' %s %s [options]', $this->dispatcher->getParam('activeTask'), $this->dispatcher->getParam('activeAction') ), 'dark_gray')); $this->appendLine(''); //puts available options $this->appendLine($this->getColoredString('Options:', 'gray')); foreach ($action->getOptions() as $option) { $this->appendLine($this->getColoredString(sprintf( ' --%s -%s %s', $option->getName(), $option->getShortName(), $option->getDescription() ), 'light_green')); } }
php
{ "resource": "" }
q5027
TaskAbstract.renderTaskHelp
train
protected function renderTaskHelp() { $this->appendLine($this->getColoredString('Available actions', 'dark_gray')); $this->appendLine(PHP_EOL); foreach ($this->actions as $action) { $this->appendLine(sprintf( ' %s %s', $this->getColoredString($action->getName(), 'light_green'), $this->getColoredString($action->getDescription(), 'green')) ); } }
php
{ "resource": "" }
q5028
TaskAbstract.validate
train
protected function validate() { $args = $this->dispatcher->getParam('args'); if (isset($this->actions[$this->actionName])) { $action = $this->actions[$this->actionName]; $action->validate($args); } }
php
{ "resource": "" }
q5029
AuthController.storeIntendedUrl
train
protected function storeIntendedUrl() { // Do not store the URL if it was the login itself $previousUrl = url()->previous(); $loginUrl = url()->route($this->core->prefixRoute(NamedRoute::AUTH_LOGIN)); if ($previousUrl == $loginUrl) return; session()->put('url.intended', $previousUrl); }
php
{ "resource": "" }
q5030
MatchableRequest.toRegex
train
private function toRegex(string $pattern): string { while (\preg_match(self::OPTIONAL_PLACEHOLDER_REGEX, $pattern)) { $pattern = \preg_replace(self::OPTIONAL_PLACEHOLDER_REGEX, '($1)?', $pattern); } $pattern = \preg_replace_callback(self::REQUIRED_PLACEHOLDER_REGEX, function (array $match = []) { $match = \array_pop($match); $pos = \mb_strpos($match, self::REGEX_PREFIX); if (false !== $pos) { $parameterName = \mb_substr($match, 0, $pos); $parameterRegex = \mb_substr($match, $pos + 2); return "(?<$parameterName>$parameterRegex)"; } return "(?<$match>[^/]+)"; }, $pattern); return $pattern; }
php
{ "resource": "" }
q5031
Route.add
train
public function add($uri, $method, $controller, $action) { $this->currentRoute = [ 'uri' => $uri, 'method' => $method, 'controller' => $controller, 'action' => $action, 'module' => $this->module, ]; if ($this->currentGroupName) { $this->virtualRoutes[$this->currentGroupName][] = $this->currentRoute; } else { $this->virtualRoutes['*'][] = $this->currentRoute; } return $this; }
php
{ "resource": "" }
q5032
Route.group
train
public function group(string $groupName, \Closure $callback) { $this->currentGroupName = $groupName; $this->isGroupe = TRUE; $this->isGroupeMiddlewares = FALSE; $callback($this); $this->isGroupeMiddlewares = TRUE; $this->currentGroupName = NULL; return $this; }
php
{ "resource": "" }
q5033
Route.middlewares
train
public function middlewares(array $middlewares = []) { if (!$this->isGroupe) { end($this->virtualRoutes['*']); $lastKey = key($this->virtualRoutes['*']); $this->virtualRoutes['*'][$lastKey]['middlewares'] = $middlewares; } else { end($this->virtualRoutes); $lastKeyOfFirstRound = key($this->virtualRoutes); if (!$this->isGroupeMiddlewares) { end($this->virtualRoutes[$lastKeyOfFirstRound]); $lastKeyOfSecondRound = key($this->virtualRoutes[$lastKeyOfFirstRound]); $this->virtualRoutes[$lastKeyOfFirstRound][$lastKeyOfSecondRound]['middlewares'] = $middlewares; } else { $this->isGroupe = FALSE; foreach ($this->virtualRoutes[$lastKeyOfFirstRound] as &$route) { $hasMiddleware = end($route); if (!is_array($hasMiddleware)) { $route['middlewares'] = $middlewares; } else { foreach ($middlewares as $middleware) { $route['middlewares'][] = $middleware; } } } } } }
php
{ "resource": "" }
q5034
Route.getRuntimeRoutes
train
public function getRuntimeRoutes() { $runtimeRoutes = []; foreach ($this->virtualRoutes as $virtualRoute) { foreach ($virtualRoute as $route) { $runtimeRoutes[] = $route; } } return $runtimeRoutes; }
php
{ "resource": "" }
q5035
Ipboard.request
train
private function request($method, $function, $extra = []) { $response = null; try { $response = $this->httpRequest->{$method}($function, $extra)->getBody(); return json_decode($response, false); } catch (ClientException $e) { $this->handleError($e->getResponse()); } }
php
{ "resource": "" }
q5036
Ipboard.handleError
train
private function handleError($response) { $error = json_decode($response->getBody(), false); $errorCode = $error->errorCode; try { if (array_key_exists($errorCode, $this->error_exceptions)) { throw new $this->error_exceptions[$errorCode]; } throw new $this->error_exceptions[$response->getStatusCode()]; } catch (Exception $e) { throw new \Exception("There was a malformed response from IPBoard."); } }
php
{ "resource": "" }
q5037
MarkupValidator.validateMarkup
train
public function validateMarkup(array $messageFilterConfiguration = array()) { $markup = $this->markupProvider->getMarkup(); $messages = $this->markupValidator->validate($markup); $this->messageFilter->setConfiguration($messageFilterConfiguration); $filteredMessages = $this->messageFilter->filterMessages($messages); if (empty($filteredMessages) === false) { $messagesString = $this->messagePrinter->getMessagesString($filteredMessages); $this->fail($messagesString); } // Validation succeeded. $this->assertTrue(true); }
php
{ "resource": "" }
q5038
Bootstrap.run
train
public static function run() { try { $router = new Router(); (new ModuleLoader())->loadModules($router); $router->findRoute(); Environment::load(); Config::load(); Helpers::load(); Libraries::load(); $mvcManager = new MvcManager(); $mvcManager->runMvc(Router::$currentRoute); } catch (\Exception $e) { echo $e->getMessage(); exit; } }
php
{ "resource": "" }
q5039
Mailer.getLastMessage
train
public function getLastMessage() { $filename = $this->getTempFilename(); if (file_exists($filename)) { $result = unserialize(file_get_contents($filename)); } else { throw new Swift_IoException('No last message found in "' . $filename . '" - did you call send()?'); } return $result; }
php
{ "resource": "" }
q5040
MongoAbstract.validate
train
private function validate() { if (empty($this->modelName) && empty($this->model)) { throw new Exception\ModelNotSetException(); } if (empty($this->model)) { $this->model = new $this->modelName(); } if (empty($this->modelName)) { $this->modelName = get_class($this->model); } if (empty($this->db)) { $this->db = $this->model->getConnection(); } }
php
{ "resource": "" }
q5041
MongoAbstract.getTotalPages
train
public function getTotalPages() { if (empty($this->totalPages)) { $this->totalPages = (int)ceil($this->getCursor()->count()/$this->limit); } return $this->totalPages; }
php
{ "resource": "" }
q5042
Palette.getUrl
train
public function getUrl($image, $imageQuery = NULL) { // Experimental support for absolute picture url when is relative generator url set if($imageQuery && Strings::startsWith($imageQuery, '//')) { $imageQuery = Strings::substring($imageQuery, 2); $imageUrl = $this->getPictureGeneratorUrl($image, $imageQuery); if($this->isUrlRelative) { if($this->websiteUrl) { return $this->websiteUrl . $imageUrl; } else { return '//' . $_SERVER['SERVER_ADDR'] . $imageUrl; } } else { return $imageUrl; } } return $this->getPictureGeneratorUrl($image, $imageQuery); }
php
{ "resource": "" }
q5043
Palette.getPictureGeneratorUrl
train
protected function getPictureGeneratorUrl($image, $imageQuery = NULL) { if(!is_null($imageQuery)) { $image .= '@' . $imageQuery; } return $this->generator->loadPicture($image)->getUrl(); }
php
{ "resource": "" }
q5044
Palette.serverResponse
train
public function serverResponse() { try { $this->generator->serverResponse(); } catch(\Exception $exception) { // Handle server generating image response exception if($this->handleExceptions) { if(is_string($this->handleExceptions)) { Debugger::log($exception->getMessage(), $this->handleExceptions); } else { Debugger::log($exception, 'palette'); } } else { throw $exception; } // Return fallback image on exception if fallback image is configured $fallbackImage = $this->generator->getFallbackImage(); if($fallbackImage) { $paletteQuery = preg_replace('/.*@(.*)/', $fallbackImage . '@$1', $_GET['imageQuery']); $picture = $this->generator->loadPicture($paletteQuery); $savePath = $this->generator->getPath($picture); if(!file_exists($savePath)) { $picture->save($savePath); } $picture->output(); } } }
php
{ "resource": "" }
q5045
Router.get
train
public function get(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_GET, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5046
Router.post
train
public function post(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_POST, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5047
Router.put
train
public function put(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_PUT, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5048
Router.patch
train
public function patch(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_PATCH, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5049
Router.delete
train
public function delete(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_DELETE, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5050
Router.options
train
public function options(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_OPTIONS, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5051
Router.head
train
public function head(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_HEAD, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5052
Router.purge
train
public function purge(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_PURGE, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5053
Router.trace
train
public function trace(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_TRACE, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5054
Router.connect
train
public function connect(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_CONNECT, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5055
Router.map
train
public function map(string $pattern, array $verbs, $stages): void { $pipeline = new HttpPipeline($verbs, $this->prefix.$pattern, $this->routerStages); $pipeline->pipe($stages); $this->pipelineCollection->add($pipeline); }
php
{ "resource": "" }
q5056
RequestTrait.fetch
train
protected function fetch($url, array $params = [], array $curl_options = []){ $requestOptions = new RequestOptions; $requestOptions->curl_options = $curl_options; $requestOptions->ca_info = $this->ca_info; return (new Request($requestOptions))->fetch(new URL($url, $params)); }
php
{ "resource": "" }
q5057
Csv.setDelimiter
train
public function setDelimiter($delimiter) { if (!is_string($delimiter) || strlen($delimiter) < 1) { throw new \InvalidArgumentException("Invalid delimiter specified, must be a string at least 1 character long"); } $this->delimiter = $delimiter; return $this; }
php
{ "resource": "" }
q5058
Csv.setLineEnding
train
public function setLineEnding($lineEnding) { if (!is_string($lineEnding) || strlen($lineEnding) < 1) { throw new \InvalidArgumentException("Invalid line ending specified, must be a string at least 1 character long"); } $this->lineEnding = $lineEnding; return $this; }
php
{ "resource": "" }
q5059
Csv.addRow
train
public function addRow(array $row) { if (is_array($this->fields)) { $assoc = $row; $row = []; foreach ($this->fields as $field) { $row[] = isset($assoc[$field]) ? $assoc[$field] : ""; } } $this->data[] = $row; return $this; }
php
{ "resource": "" }
q5060
Csv.asString
train
public function asString() { $tmp = new \SplTempFileObject; foreach ($this->data as $row) { $tmp->fputcsv($row, $this->delimiter); if ($this->lineEnding !== "\n") { $tmp->fseek(-1, \SEEK_CUR); $tmp->fwrite($this->lineEnding); } } # Find out how much data we have written $length = $tmp->ftell(); if ($length < 1) { return ""; } # Reset the internal pointer and return all the data we have written $tmp->fseek(0); return $tmp->fread($length); }
php
{ "resource": "" }
q5061
Csv.getContents
train
public static function getContents($filename) { $file = fopen($filename, "r"); if ($file === false) { throw new \RuntimeException("Cannot read the file: {$filename}"); } $data = []; while ($row = fgetcsv($file)) { $data[] = $row; } fclose($file); return $data; }
php
{ "resource": "" }
q5062
Csv.putContents
train
public static function putContents($filename, array $data) { $csv = new static(); foreach ($data as $row) { $csv->addRow($row); } $csv->write($filename); }
php
{ "resource": "" }
q5063
HooksTrait.redirectToAction
train
protected function redirectToAction($action) { return $this->response->redirect([ 'for' => $this->router->getMatchedRoute()->getName(), 'action' => $action ]); }
php
{ "resource": "" }
q5064
HooksTrait.beforeCreate
train
protected function beforeCreate() { $this->dispatcher->getEventsManager()->fire(Events::BEFORE_CREATE, $this); $this->beforeSave(); }
php
{ "resource": "" }
q5065
HooksTrait.afterCreate
train
protected function afterCreate() { $this->dispatcher->getEventsManager()->fire(Events::AFTER_CREATE, $this); return $this->afterSave(); }
php
{ "resource": "" }
q5066
HooksTrait.beforeUpdate
train
protected function beforeUpdate() { $this->dispatcher->getEventsManager()->fire(Events::BEFORE_UPDATE, $this); $this->beforeSave(); }
php
{ "resource": "" }
q5067
HooksTrait.afterUpdate
train
protected function afterUpdate() { $this->dispatcher->getEventsManager()->fire(Events::AFTER_UPDATE, $this); return $this->afterSave(); }
php
{ "resource": "" }
q5068
HooksTrait.afterDelete
train
protected function afterDelete() { $this->dispatcher->getEventsManager()->fire(Events::AFTER_DELETE, $this); return $this->redirectToAction('index'); }
php
{ "resource": "" }
q5069
HooksTrait.afterDeleteException
train
protected function afterDeleteException() { $this->dispatcher->getEventsManager()->fire(Events::AFTER_DELETE_EXCEPTION, $this); return $this->redirectToAction('index'); }
php
{ "resource": "" }
q5070
MappingResolverTrait.addMapping
train
public function addMapping($attributeName, $mappings) { if (!is_array($mappings)) { $mappings = [$mappings]; } if (!$this->hasMapping($attributeName)) { $this->mappingsContainer[$attributeName] = []; } if ($this->mappingsContainer[$attributeName] !== null) { foreach ($mappings as $mapping) { $this->mappingsContainer[$attributeName][] = $mapping; } } return $this; }
php
{ "resource": "" }
q5071
MappingResolverTrait.removeMapping
train
public function removeMapping($attributeName) { if ($this->hasMapping($attributeName)) { $this->mappingsContainer[$attributeName] = null; } return $this; }
php
{ "resource": "" }
q5072
MappingResolverTrait.resolveMapping
train
public function resolveMapping($attributeName, $value) { //when no mappings was defined, returns raw value if (!$this->hasMapping($attributeName)) { return $value; } $mappings = $this->mappingsContainer[$attributeName]; if (is_array($mappings)) { foreach ($mappings as $mappingResolver) { if (!$mappingResolver instanceof MappingInterface) { //get mapping instance from mapping manager $mappingResolver = MappingManager::find($mappingResolver); } $mappingResolver->resolve($value); } } return $value; }
php
{ "resource": "" }
q5073
SpamProtector.buildUrl
train
protected function buildUrl($type = 'email', $value) { $type = trim(strtolower($type)); if (! in_array($type, ['ip', 'email', 'username'])) { throw new \InvalidArgumentException('Type of '.$type.' is not supported by the API'); } $url = $this->apiUrl.'?'.$type.'='.urlencode($value).'&f=json'; return $url; }
php
{ "resource": "" }
q5074
SpamProtector.sendRequest
train
protected function sendRequest($url) { $response = null; if ($this->curlEnabled) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); } else { $response = file_get_contents($url); } return $response; }
php
{ "resource": "" }
q5075
SpamProtector.isSpam
train
public function isSpam($type = 'email', $value) { $fullApiUrl = $this->buildUrl($type, $value); $response = $this->sendRequest($fullApiUrl); if (! $response) { throw new \Exception('API Check Unsuccessful on url: '.$fullApiUrl); } $result = json_decode($response); // check format if (! isset($result->success) || ! isset($result->{$type}->appears) || ! isset($result->{$type}->frequency) ) { logger($response); if (is_array($response)) { $response = implode(', ', $response); } throw new \Exception('Response has wrong format: '.$response); } // check success if ($result->success == 1 && $result->{$type}->appears == 1) { // check frequency return $result->{$type}->frequency >= $this->frequency; } return false; }
php
{ "resource": "" }
q5076
QueryBuilder.platformPrepareLikeStatement
train
protected function platformPrepareLikeStatement( $prefix = null, $column, $not = null, $bind, $caseSensitive = false ) { $likeStatement = "{$prefix} {$column} {$not} LIKE :{$bind}"; if ($caseSensitive === true) { $likeStatement = "{$prefix} LOWER({$column}) {$not} LIKE :{$bind}"; } return $likeStatement; }
php
{ "resource": "" }
q5077
MultiRequest.createHandle
train
protected function createHandle(){ if(!empty($this->stack)){ $url = array_shift($this->stack); if($url instanceof URL){ $curl = curl_init($url->mergeParams()); curl_setopt_array($curl, $this->curl_options); curl_multi_add_handle($this->curl_multi, $curl); if($this->options->sleep){ usleep($this->options->sleep); } } else{ // retry on next if we don't get what we expect $this->createHandle(); // @codeCoverageIgnore } } }
php
{ "resource": "" }
q5078
MultiRequest.processStack
train
protected function processStack(){ do{ do { $status = curl_multi_exec($this->curl_multi, $active); } while($status === CURLM_CALL_MULTI_PERFORM); // welcome to callback hell. while($state = curl_multi_info_read($this->curl_multi)){ $url = $this->multiResponseHandler->handleResponse(new MultiResponse($state['handle'])); if($url instanceof URL){ $this->stack[] = $url; } curl_multi_remove_handle($this->curl_multi, $state['handle']); curl_close($state['handle']); $this->createHandle(); } if($active){ curl_multi_select($this->curl_multi, $this->options->timeout); } } while($active && $status === CURLM_OK); }
php
{ "resource": "" }
q5079
UserPassword.fromPlain
train
public static function fromPlain($aPlainPassword, UserPasswordEncoder $anEncoder, $salt = null) { if (null === $salt) { $salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36); } $encodedPassword = $anEncoder->encode($aPlainPassword, $salt); return new self($encodedPassword, $salt); }
php
{ "resource": "" }
q5080
RefResolverTrait.readRef
train
public function readRef($fieldName) { $oRef = $this->readNestedAttribute($fieldName); if (!\MongoDBRef::isRef($oRef)) { throw new InvalidReferenceException(); } if (isset($this->dbRefs) && isset($this->dbRefs[$fieldName])) { $modelInstance = $this->instantiateModel($this->dbRefs[$fieldName]); } else if ($this->getDI()->has('mongoMapper')) { $modelInstance = $this->getDI()->get('mongoMapper')->resolveModel($oRef['$ref']); } else { return $oRef; } return forward_static_call(array($modelInstance, 'findById'), $oRef['$id']); }
php
{ "resource": "" }
q5081
Config.load
train
public static function load() { $configFile = MODULES_DIR . DS . RouteController::$currentModule . '/Config/config.php'; if (!file_exists($configFile)) { $configFile = BASE_DIR . '/config/config.php'; if (!file_exists($configFile)) { throw new \Exception(ExceptionMessages::CONFIG_FILE_NOT_FOUND); } } if (empty(self::$configs)) { self::$configs = require_once $configFile; } }
php
{ "resource": "" }
q5082
Config.import
train
public static function import($filename) { $configFile = BASE_DIR . '/config/' . $filename . '.php'; if (!file_exists($configFile)) { throw new \Exception(ExceptionMessages::CONFIG_FILE_NOT_FOUND); } $allConfigs = self::getAll(); foreach ($allConfigs as $key => $config) { if($filename == $key) { throw new \Exception(ExceptionMessages::CONFIG_COLLISION); } } self::$configs[$filename] = require_once BASE_DIR . '/config/' . $filename . '.php'; }
php
{ "resource": "" }
q5083
Config.get
train
public static function get($key, $default = NULL) { if (isset(self::$configs[$key])) return self::$configs[$key]; return $default; }
php
{ "resource": "" }
q5084
Payment.getCustomParamsArray
train
private function getCustomParamsArray() { $customParams = $this->customParams; ksort($customParams); foreach ($customParams as $key => $value) { $customParams[$this->customParamsPrefix . $key] = $value; unset($customParams[$key]); } return $customParams; }
php
{ "resource": "" }
q5085
Payment.getCustomParamsString
train
private function getCustomParamsString() { $customParams = $this->getCustomParamsArray(); foreach ($customParams as $key => $value) { $customParams[$key] = $key . '=' . $value; } return implode(':', $customParams); }
php
{ "resource": "" }
q5086
AssetsTask.publishAction
train
public function publishAction() { $this->putText("Copying Vegas CMF assets..."); $this->copyCmfAssets(); $this->putText("Copying vendor assets:"); $this->copyVendorAssets(); $this->putSuccess("Done."); }
php
{ "resource": "" }
q5087
AssetsTask.copyCmfAssets
train
private function copyCmfAssets() { $vegasCmfPath = APP_ROOT . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'vegas-cmf'; $publicAssetsDir = $this->getOption('d', APP_ROOT.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'assets'); $handle = opendir($vegasCmfPath); if ($handle) { while (false !== ($entry = readdir($handle))) { if ($entry == "." || $entry == "..") { continue; } $assetsDir = $vegasCmfPath.DIRECTORY_SEPARATOR.$entry.DIRECTORY_SEPARATOR.'assets'; if (file_exists($assetsDir)) { $this->copyRecursive($assetsDir, $publicAssetsDir); } } closedir($handle); } }
php
{ "resource": "" }
q5088
AssetsTask.copyVendorAssets
train
private function copyVendorAssets() { $modules = []; $moduleLoader = new Loader($this->di); $moduleLoader->dumpModulesFromVendor($modules); $publicAssetsDir = $this->getOption('d', APP_ROOT.DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'assets'); if ($modules) { foreach ($modules as $moduleName => $module) { $assetsDir = dirname($module['path']) . '/../assets'; if (file_exists($assetsDir)) { $this->putText("- " . $moduleName . "..."); $this->copyRecursive($assetsDir, $publicAssetsDir); } } } }
php
{ "resource": "" }
q5089
AssetsTask.setupOptions
train
public function setupOptions() { $action = new Action('publish', 'Publish all assets'); $dir = new Option('dir', 'd', 'Assets directory. Usage vegas:assets publish -d /path/to/assets'); $action->addOption($dir); $this->addTaskAction($action); }
php
{ "resource": "" }
q5090
PartyService.assignAccountToParty
train
public function assignAccountToParty(Account $account, AbstractParty $party) { if ($party->getAccounts()->contains($account)) { return; } $party->addAccount($account); $accountIdentifier = $this->persistenceManager->getIdentifierByObject($account); // We need to prevent stale object references and therefore only cache the identifier. $this->accountsInPartyRuntimeCache[$accountIdentifier] = $this->persistenceManager->getIdentifierByObject($party); }
php
{ "resource": "" }
q5091
PartyService.getAssignedPartyOfAccount
train
public function getAssignedPartyOfAccount(Account $account) { $accountIdentifier = $this->persistenceManager->getIdentifierByObject($account); // We need to prevent stale object references and therefore only cache the identifier. if (!array_key_exists($accountIdentifier, $this->accountsInPartyRuntimeCache)) { $party = $this->partyRepository->findOneHavingAccount($account); $this->accountsInPartyRuntimeCache[$accountIdentifier] = $party === null ? null : $this->persistenceManager->getIdentifierByObject($party); return $party; } if ($this->accountsInPartyRuntimeCache[$accountIdentifier] !== null) { $partyIdentifier = $this->accountsInPartyRuntimeCache[$accountIdentifier]; return $this->persistenceManager->getObjectByIdentifier($partyIdentifier, AbstractParty::class); } return null; }
php
{ "resource": "" }
q5092
FakerProvider.articleTitle
train
public function articleTitle() { $title = $this->getTitle(); $search = [ '{{ noun }}', '{{ verb }}', '{{ adjective }}', '{{ adverb }}', ]; $replace = [ $this->getNoun(), $this->getVerb(), $this->getAdjective(), $this->getAdverb(), ]; $title = ucfirst(str_replace($search, $replace, $title)); return $title; }
php
{ "resource": "" }
q5093
FakerProvider.articleContent
train
public function articleContent() { $content = $this->getHtmlTemplate(); $search = [ '{{ title }}', '{{ paragraph }}', '{{ paragraphs }}', '{{ words }}', '{{ image }}', '{{ sentence }}', ]; $replace = [ self::articleTitle(), $this->generator->paragraph(), nl2br($this->generator->paragraphs(rand(5, 10), true)), $this->generator->sentence(rand(3, 5)), $this->generator->imageUrl(), $this->generator->sentence(), ]; $content = str_replace($search, $replace, $content); return $content; }
php
{ "resource": "" }
q5094
FakerProvider.articleContentMarkdown
train
public function articleContentMarkdown() { $content = $this->getMarkdownTemplate(); $search = [ '{{ title }}', '{{ paragraph }}', '{{ paragraphs }}', '{{ words }}', '{{ image }}', '{{ sentence }}', ]; $replace = [ self::articleTitle(), $this->generator->paragraph(), $this->generator->paragraphs(rand(5, 10), true), $this->generator->sentence(rand(3, 5)), $this->generator->imageUrl(), $this->generator->sentence(), ]; $content = str_replace($search, $replace, $content); return $content; }
php
{ "resource": "" }
q5095
ServiceProviderLoader.dump
train
public function dump($inputDirectory, $outputDirectory) { $servicesList = array(); //browses directory for searching service provider classes $directoryIterator = new \DirectoryIterator($inputDirectory); foreach ($directoryIterator as $fileInfo) { if ($fileInfo->isDot()) continue; $servicesList[$fileInfo->getBasename('.php')] = $fileInfo->getPathname(); } //saves generated array to php source file FileWriter::writeObject( $outputDirectory . self::SERVICES_STATIC_FILE, $servicesList, true ); ksort($servicesList); return $servicesList; }
php
{ "resource": "" }
q5096
ServiceProviderLoader.autoload
train
public function autoload($inputDirectory, $outputDirectory) { if (!file_exists($outputDirectory . self::SERVICES_STATIC_FILE) || $this->di->get('environment') != Constants::DEFAULT_ENV) { $services = self::dump($inputDirectory, $outputDirectory); } else { $services = require($outputDirectory . self::SERVICES_STATIC_FILE); } self::setupServiceProvidersAutoloader($inputDirectory, $services); //resolves services dependencies $dependencies = array(); $servicesProviders = array(); foreach ($services as $serviceProviderName => $path) { $reflectionClass = new \ReflectionClass($serviceProviderName); $serviceProviderInstance = $reflectionClass->newInstance(); //fetches services dependencies $serviceDependencies = $serviceProviderInstance->getDependencies(); //fetches name of service $serviceName = $reflectionClass->getConstant('SERVICE_NAME'); //all services are in dependencies if (!isset($dependencies[$serviceName])) { $dependencies[$serviceName] = 0; } /** * Creates array of ordered dependencies */ array_walk($serviceDependencies, function($dependency, $key) use (&$dependencies) { if (!isset($dependencies[$dependency])) { $dependencies[$dependency] = 0; } $dependencies[$dependency]++; }); $servicesProviders[$serviceName] = $serviceProviderInstance; } uasort($dependencies, function($a, $b) { return $b-$a; }); //registers ordered dependencies foreach ($dependencies as $serviceProviderName => $dependency) { $servicesProviders[$serviceProviderName]->register($this->di); } }
php
{ "resource": "" }
q5097
ServiceProviderLoader.setupServiceProvidersAutoloader
train
private function setupServiceProvidersAutoloader($inputDirectory, array $services) { //creates the autoloader $loader = new Loader(); //setup default path when is not defined foreach ($services as $className => $path) { if (!$path) { $services[$className] = $inputDirectory . sprintf('%s.php', $className); } } $loader->registerClasses($services, true); $loader->register(); }
php
{ "resource": "" }
q5098
Bootstrap.initDispatcher
train
public function initDispatcher() { $this->di->set('dispatcher', function() { $dispatcher = new Dispatcher(); /** * @var \Phalcon\Events\Manager $eventsManager */ $eventsManager = $this->di->getShared('eventsManager'); $eventsManager->attach( 'dispatch:beforeException', (new ExceptionListener())->beforeException() ); $dispatcher->setEventsManager($eventsManager); return $dispatcher; }); }
php
{ "resource": "" }
q5099
Bootstrap.setup
train
public function setup() { $this->di->set('config', $this->config); $this->initEnvironment($this->config); $this->initErrorHandler($this->config); $this->initLoader($this->config); $this->initModules($this->config); $this->initRoutes($this->config); $this->initServices($this->config); $this->initDispatcher(); $this->application->setDI($this->di); DI::setDefault($this->di); return $this; }
php
{ "resource": "" }