_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
33
8k
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
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; #
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));
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
php
{ "resource": "" }
q5004
MarkupValidatorMessage.setType
train
public function setType($type) { if ($type === null) { $type = self::TYPE_UNDEFINED;
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) );
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);
php
{ "resource": "" }
q5007
ProtectedResourceTarget.detectResourcesBaseUri
train
protected function detectResourcesBaseUri() { $uri = ''; $request = $this->getHttpRequest(); if ($request instanceof HttpRequest) {
php
{ "resource": "" }
q5008
ServiceManager.getService
train
public function getService($name) { try { if (!$this->isRegisteredService($name)) { $this->registerService($name); } return $this->di->get($name); }
php
{ "resource": "" }
q5009
ServiceManager.hasService
train
public function hasService($name) { try { $service = $this->getService($name); return !empty($service);
php
{ "resource": "" }
q5010
ControllerAbstract.jsonResponse
train
protected function jsonResponse($data = array()) { $this->view->disable();
php
{ "resource": "" }
q5011
PackageConverter.getForce
train
protected function getForce(PropertyMappingConfigurationInterface $configuration = null) { if ($configuration === null) { throw new InvalidPropertyMappingConfigurationException('Missing property configuration', 1457516367);
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) {
php
{ "resource": "" }
q5013
Html.formatKey
train
public static function formatKey($key, $options = null) { $options = Helper::getOptions($options, [ "underscores" => true, "ucwords" => true, ]); if ($options["underscores"]) {
php
{ "resource": "" }
q5014
Html.string
train
public static function string($string, $options = null) { $options = Helper::getOptions($options, [ "alt" => "n/a", ]); $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);
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);
php
{ "resource": "" }
q5017
Loader.toNamespace
train
private function toNamespace($str) { $stringParts = preg_split('/_+/', $str); foreach($stringParts as $key => $stringPart){ $stringParts[$key] =
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]);
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,
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,
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",
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", ], [
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
php
{ "resource": "" }
q5024
TaskAbstract.containHelpOption
train
private function containHelpOption($args) { return array_key_exists(self::HELP_OPTION, $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 =
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]',
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
php
{ "resource": "" }
q5028
TaskAbstract.validate
train
protected function validate() { $args = $this->dispatcher->getParam('args'); if (isset($this->actions[$this->actionName])) {
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));
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,
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
php
{ "resource": "" }
q5032
Route.group
train
public function group(string $groupName, \Closure $callback) { $this->currentGroupName = $groupName; $this->isGroupe = TRUE; $this->isGroupeMiddlewares = FALSE;
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;
php
{ "resource": "" }
q5034
Route.getRuntimeRoutes
train
public function getRuntimeRoutes() { $runtimeRoutes = []; foreach ($this->virtualRoutes as $virtualRoute) {
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);
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]; }
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) {
php
{ "resource": "" }
q5038
Bootstrap.run
train
public static function run() { try { $router = new Router(); (new ModuleLoader())->loadModules($router); $router->findRoute(); Environment::load();
php
{ "resource": "" }
q5039
Mailer.getLastMessage
train
public function getLastMessage() { $filename = $this->getTempFilename(); if (file_exists($filename)) { $result = unserialize(file_get_contents($filename)); } else {
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
php
{ "resource": "" }
q5041
MongoAbstract.getTotalPages
train
public function getTotalPages() { if (empty($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 {
php
{ "resource": "" }
q5043
Palette.getPictureGeneratorUrl
train
protected function getPictureGeneratorUrl($image, $imageQuery = NULL) { if(!is_null($imageQuery))
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)
php
{ "resource": "" }
q5045
Router.get
train
public function get(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_GET, $this->prefix.$pattern, $this->routerStages);
php
{ "resource": "" }
q5046
Router.post
train
public function post(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_POST, $this->prefix.$pattern, $this->routerStages);
php
{ "resource": "" }
q5047
Router.put
train
public function put(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_PUT, $this->prefix.$pattern, $this->routerStages);
php
{ "resource": "" }
q5048
Router.patch
train
public function patch(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_PATCH, $this->prefix.$pattern, $this->routerStages);
php
{ "resource": "" }
q5049
Router.delete
train
public function delete(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_DELETE, $this->prefix.$pattern, $this->routerStages);
php
{ "resource": "" }
q5050
Router.options
train
public function options(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_OPTIONS, $this->prefix.$pattern, $this->routerStages);
php
{ "resource": "" }
q5051
Router.head
train
public function head(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_HEAD, $this->prefix.$pattern, $this->routerStages);
php
{ "resource": "" }
q5052
Router.purge
train
public function purge(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_PURGE, $this->prefix.$pattern, $this->routerStages);
php
{ "resource": "" }
q5053
Router.trace
train
public function trace(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_TRACE, $this->prefix.$pattern, $this->routerStages);
php
{ "resource": "" }
q5054
Router.connect
train
public function connect(string $pattern, $stages): void { $pipeline = new HttpPipeline(RequestMethodInterface::METHOD_CONNECT, $this->prefix.$pattern, $this->routerStages);
php
{ "resource": "" }
q5055
Router.map
train
public function map(string $pattern, array $verbs, $stages): void { $pipeline = new HttpPipeline($verbs, $this->prefix.$pattern, $this->routerStages);
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
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
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
php
{ "resource": "" }
q5059
Csv.addRow
train
public function addRow(array $row) { if (is_array($this->fields)) { $assoc = $row; $row = [];
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();
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
php
{ "resource": "" }
q5062
Csv.putContents
train
public static function putContents($filename, array $data) { $csv = new static(); foreach ($data as $row) {
php
{ "resource": "" }
q5063
HooksTrait.redirectToAction
train
protected function redirectToAction($action) { return $this->response->redirect([
php
{ "resource": "" }
q5064
HooksTrait.beforeCreate
train
protected function beforeCreate() { $this->dispatcher->getEventsManager()->fire(Events
php
{ "resource": "" }
q5065
HooksTrait.afterCreate
train
protected function afterCreate() { $this->dispatcher->getEventsManager()->fire(Events::AFTER_CREATE,
php
{ "resource": "" }
q5066
HooksTrait.beforeUpdate
train
protected function beforeUpdate() { $this->dispatcher->getEventsManager()->fire(Events
php
{ "resource": "" }
q5067
HooksTrait.afterUpdate
train
protected function afterUpdate() { $this->dispatcher->getEventsManager()->fire(Events::AFTER_UPDATE,
php
{ "resource": "" }
q5068
HooksTrait.afterDelete
train
protected function afterDelete() { $this->dispatcher->getEventsManager()->fire(Events::AFTER_DELETE,
php
{ "resource": "" }
q5069
HooksTrait.afterDeleteException
train
protected function afterDeleteException() { $this->dispatcher->getEventsManager()->fire(Events::AFTER_DELETE_EXCEPTION,
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) {
php
{ "resource": "" }
q5071
MappingResolverTrait.removeMapping
train
public function removeMapping($attributeName) { if ($this->hasMapping($attributeName)) {
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)) {
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.'
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);
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)) {
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) {
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){
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;
php
{ "resource": "" }
q5079
UserPassword.fromPlain
train
public static function fromPlain($aPlainPassword, UserPasswordEncoder $anEncoder, $salt = null) { if (null === $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')) {
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
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) {
php
{ "resource": "" }
q5083
Config.get
train
public static function get($key, $default = NULL) { if (isset(self::$configs[$key]))
php
{ "resource": "" }
q5084
Payment.getCustomParamsArray
train
private function getCustomParamsArray() { $customParams = $this->customParams; ksort($customParams); foreach ($customParams as $key => $value) {
php
{ "resource": "" }
q5085
Payment.getCustomParamsString
train
private function getCustomParamsString() { $customParams = $this->getCustomParamsArray(); foreach ($customParams as $key => $value) {
php
{ "resource": "" }
q5086
AssetsTask.publishAction
train
public function publishAction() { $this->putText("Copying Vegas CMF assets..."); $this->copyCmfAssets();
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;
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');
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
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);
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;
php
{ "resource": "" }
q5092
FakerProvider.articleTitle
train
public function articleTitle() { $title = $this->getTitle(); $search = [ '{{ noun }}', '{{ verb }}', '{{ adjective }}', '{{ adverb }}', ]; $replace = [
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)),
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),
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();
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; } /**
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) {
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(
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);
php
{ "resource": "" }