repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
ninjify/nunjuck
src/Environment.php
Environment.setupGlobalVariables
public static function setupGlobalVariables(): void { $_SERVER = array_intersect_key($_SERVER, array_flip([ 'PHP_SELF', 'SCRIPT_NAME', 'SERVER_ADDR', 'SERVER_SOFTWARE', 'HTTP_HOST', 'DOCUMENT_ROOT', 'OS', 'argc', 'argv', ])); $_SERVER['REQUEST_TIME'] = 1234567890; $_ENV = $_GET = $_POST = []; }
php
public static function setupGlobalVariables(): void { $_SERVER = array_intersect_key($_SERVER, array_flip([ 'PHP_SELF', 'SCRIPT_NAME', 'SERVER_ADDR', 'SERVER_SOFTWARE', 'HTTP_HOST', 'DOCUMENT_ROOT', 'OS', 'argc', 'argv', ])); $_SERVER['REQUEST_TIME'] = 1234567890; $_ENV = $_GET = $_POST = []; }
[ "public", "static", "function", "setupGlobalVariables", "(", ")", ":", "void", "{", "$", "_SERVER", "=", "array_intersect_key", "(", "$", "_SERVER", ",", "array_flip", "(", "[", "'PHP_SELF'", ",", "'SCRIPT_NAME'", ",", "'SERVER_ADDR'", ",", "'SERVER_SOFTWARE'", ...
Configure global variables
[ "Configure", "global", "variables" ]
0381d3330e769c4712ab063b32200a1d52333a5c
https://github.com/ninjify/nunjuck/blob/0381d3330e769c4712ab063b32200a1d52333a5c/src/Environment.php#L104-L119
train
ninjify/nunjuck
src/Environment.php
Environment.setupRobotLoader
public static function setupRobotLoader(?callable $callback = null): void { $loader = new RobotLoader(); $loader->setTempDirectory(CACHE_DIR); if ($callback !== null) { $callback($loader); } else { $loader->addDirectory(ENGINE_DIR); $loader->addDirectory(APP_DIR); $loader->setAutoRefresh(true); } $loader->register(); }
php
public static function setupRobotLoader(?callable $callback = null): void { $loader = new RobotLoader(); $loader->setTempDirectory(CACHE_DIR); if ($callback !== null) { $callback($loader); } else { $loader->addDirectory(ENGINE_DIR); $loader->addDirectory(APP_DIR); $loader->setAutoRefresh(true); } $loader->register(); }
[ "public", "static", "function", "setupRobotLoader", "(", "?", "callable", "$", "callback", "=", "null", ")", ":", "void", "{", "$", "loader", "=", "new", "RobotLoader", "(", ")", ";", "$", "loader", "->", "setTempDirectory", "(", "CACHE_DIR", ")", ";", "...
Configure robot loader
[ "Configure", "robot", "loader" ]
0381d3330e769c4712ab063b32200a1d52333a5c
https://github.com/ninjify/nunjuck/blob/0381d3330e769c4712ab063b32200a1d52333a5c/src/Environment.php#L124-L138
train
firebrandhq/silverstripe-hail
src/Forms/GridFieldFetchButton.php
GridFieldFetchButton.getHTMLFragments
public function getHTMLFragments($gridField) { //Disable button if there is already a job running, and add a class to the progress button to trigger the display $jobs = FetchJob::get()->filter(['Status:not' => ['Done', 'Error']]); $current = $jobs->First(); $global = $current && $current->ToFetch === "*" ? "global-fetch" : ""; $disabled = $jobs->Count() > 0 ? "disabled" : ""; $running = $jobs->Count() > 0 ? "hail-fetch-running" : ""; $active = $jobs->Count() > 0 ? "state-active" : ""; $vd = new ViewableData(); $rendered = $vd ->customise([ 'Disabled' => $disabled, 'Running' => $running, 'Active' => $active, 'Global' => $global, ]) ->renderWith('GridFieldFetchButton') ->getValue(); return [ $this->targetFragment => $rendered, ]; }
php
public function getHTMLFragments($gridField) { //Disable button if there is already a job running, and add a class to the progress button to trigger the display $jobs = FetchJob::get()->filter(['Status:not' => ['Done', 'Error']]); $current = $jobs->First(); $global = $current && $current->ToFetch === "*" ? "global-fetch" : ""; $disabled = $jobs->Count() > 0 ? "disabled" : ""; $running = $jobs->Count() > 0 ? "hail-fetch-running" : ""; $active = $jobs->Count() > 0 ? "state-active" : ""; $vd = new ViewableData(); $rendered = $vd ->customise([ 'Disabled' => $disabled, 'Running' => $running, 'Active' => $active, 'Global' => $global, ]) ->renderWith('GridFieldFetchButton') ->getValue(); return [ $this->targetFragment => $rendered, ]; }
[ "public", "function", "getHTMLFragments", "(", "$", "gridField", ")", "{", "//Disable button if there is already a job running, and add a class to the progress button to trigger the display", "$", "jobs", "=", "FetchJob", "::", "get", "(", ")", "->", "filter", "(", "[", "'S...
Returns the Fetch Button html @param GridField $gridField @return array
[ "Returns", "the", "Fetch", "Button", "html" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Forms/GridFieldFetchButton.php#L37-L60
train
flipboxfactory/craft-ember
src/queries/OrderByTrait.php
OrderByTrait.applyOrderByParams
protected function applyOrderByParams(Connection $db) { if ($this->orderBy === null) { return; } // Any other empty value means we should set it if (empty($this->orderBy)) { $this->applyEmptyOrderByParams($db); } $this->orderBy($this->orderBy); }
php
protected function applyOrderByParams(Connection $db) { if ($this->orderBy === null) { return; } // Any other empty value means we should set it if (empty($this->orderBy)) { $this->applyEmptyOrderByParams($db); } $this->orderBy($this->orderBy); }
[ "protected", "function", "applyOrderByParams", "(", "Connection", "$", "db", ")", "{", "if", "(", "$", "this", "->", "orderBy", "===", "null", ")", "{", "return", ";", "}", "// Any other empty value means we should set it", "if", "(", "empty", "(", "$", "this"...
Applies the 'fixedOrder' and 'orderBy' params to the query being prepared. @param Connection|null $db The database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used.
[ "Applies", "the", "fixedOrder", "and", "orderBy", "params", "to", "the", "query", "being", "prepared", "." ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/queries/OrderByTrait.php#L52-L64
train
firebrandhq/silverstripe-hail
src/Models/Article.php
Article.fetchImages
public function fetchImages() { try { $api_client = new Client(); $list = $api_client->getImagesByArticles($this->HailID); } catch (\Exception $ex) { return; } $hailIdList = []; // Clean before importing $this->ImageGallery()->removeAll(); foreach ($list as $hailData) { // Build up Hail ID list $hailIdList[] = $hailData['id']; // Check if we can find an existing item. $hailObj = Image::get()->filter(['HailID' => $hailData['id']])->First(); if (!$hailObj) { $hailObj = new Image(); } $hailObj->OrganisationID = $this->OrganisationID; $hailObj->HailOrgID = $this->HailOrgID; $hailObj->HailOrgName = $this->HailOrgName; $hailObj->importHailData($hailData); $this->ImageGallery()->add($hailObj); } }
php
public function fetchImages() { try { $api_client = new Client(); $list = $api_client->getImagesByArticles($this->HailID); } catch (\Exception $ex) { return; } $hailIdList = []; // Clean before importing $this->ImageGallery()->removeAll(); foreach ($list as $hailData) { // Build up Hail ID list $hailIdList[] = $hailData['id']; // Check if we can find an existing item. $hailObj = Image::get()->filter(['HailID' => $hailData['id']])->First(); if (!$hailObj) { $hailObj = new Image(); } $hailObj->OrganisationID = $this->OrganisationID; $hailObj->HailOrgID = $this->HailOrgID; $hailObj->HailOrgName = $this->HailOrgName; $hailObj->importHailData($hailData); $this->ImageGallery()->add($hailObj); } }
[ "public", "function", "fetchImages", "(", ")", "{", "try", "{", "$", "api_client", "=", "new", "Client", "(", ")", ";", "$", "list", "=", "$", "api_client", "->", "getImagesByArticles", "(", "$", "this", "->", "HailID", ")", ";", "}", "catch", "(", "...
Fetch the image gallery of this article from the Hail API @return void @throws
[ "Fetch", "the", "image", "gallery", "of", "this", "article", "from", "the", "Hail", "API" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/Article.php#L187-L218
train
firebrandhq/silverstripe-hail
src/Models/Article.php
Article.fetchVideos
public function fetchVideos() { try { $api_client = new Client(); $list = $api_client->getVideosByArticles($this->HailID); } catch (\Exception $ex) { return; } $hailIdList = []; // CLean before importing $this->VideoGallery()->removeAll(); foreach ($list as $hailData) { // Build up Hail ID list $hailIdList[] = $hailData['id']; // Check if we can find an existing item. $hailObj = Video::get()->filter(['HailID' => $hailData['id']])->First(); if (!$hailObj) { $hailObj = new Video(); } $hailObj->OrganisationID = $this->OrganisationID; $hailObj->HailOrgID = $this->HailOrgID; $hailObj->HailOrgName = $this->HailOrgName; $hailObj->importHailData($hailData); $this->VideoGallery()->add($hailObj); } }
php
public function fetchVideos() { try { $api_client = new Client(); $list = $api_client->getVideosByArticles($this->HailID); } catch (\Exception $ex) { return; } $hailIdList = []; // CLean before importing $this->VideoGallery()->removeAll(); foreach ($list as $hailData) { // Build up Hail ID list $hailIdList[] = $hailData['id']; // Check if we can find an existing item. $hailObj = Video::get()->filter(['HailID' => $hailData['id']])->First(); if (!$hailObj) { $hailObj = new Video(); } $hailObj->OrganisationID = $this->OrganisationID; $hailObj->HailOrgID = $this->HailOrgID; $hailObj->HailOrgName = $this->HailOrgName; $hailObj->importHailData($hailData); $this->VideoGallery()->add($hailObj); } }
[ "public", "function", "fetchVideos", "(", ")", "{", "try", "{", "$", "api_client", "=", "new", "Client", "(", ")", ";", "$", "list", "=", "$", "api_client", "->", "getVideosByArticles", "(", "$", "this", "->", "HailID", ")", ";", "}", "catch", "(", "...
Fetch the video gallery of this article from the Hail API @return void @throws
[ "Fetch", "the", "video", "gallery", "of", "this", "article", "from", "the", "Hail", "API" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/Article.php#L226-L255
train
firebrandhq/silverstripe-hail
src/Models/Article.php
Article.Link
public function Link() { $ctrl = Controller::curr(); if ($ctrl instanceof HailPageController) { $link = $ctrl->Link(); } else { //If outside HailPageController try to find the first Hail Page $page = HailPage::get()->first(); if (!empty($page)) { $link = $page->Link(); } } if (!isset($link)) { return ""; } return $link . "article/" . $this->HailID . '/' . Convert::raw2url($this->Title); }
php
public function Link() { $ctrl = Controller::curr(); if ($ctrl instanceof HailPageController) { $link = $ctrl->Link(); } else { //If outside HailPageController try to find the first Hail Page $page = HailPage::get()->first(); if (!empty($page)) { $link = $page->Link(); } } if (!isset($link)) { return ""; } return $link . "article/" . $this->HailID . '/' . Convert::raw2url($this->Title); }
[ "public", "function", "Link", "(", ")", "{", "$", "ctrl", "=", "Controller", "::", "curr", "(", ")", ";", "if", "(", "$", "ctrl", "instanceof", "HailPageController", ")", "{", "$", "link", "=", "$", "ctrl", "->", "Link", "(", ")", ";", "}", "else",...
Return the Article link for the current HailPageController @return string
[ "Return", "the", "Article", "link", "for", "the", "current", "HailPageController" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/Article.php#L262-L280
train
firebrandhq/silverstripe-hail
src/Models/Article.php
Article.getLinkForPage
public function getLinkForPage($page) { return $page->Link() . "article/" . $this->HailID . '/' . Convert::raw2url($this->Title); }
php
public function getLinkForPage($page) { return $page->Link() . "article/" . $this->HailID . '/' . Convert::raw2url($this->Title); }
[ "public", "function", "getLinkForPage", "(", "$", "page", ")", "{", "return", "$", "page", "->", "Link", "(", ")", ".", "\"article/\"", ".", "$", "this", "->", "HailID", ".", "'/'", ".", "Convert", "::", "raw2url", "(", "$", "this", "->", "Title", ")...
Return the Article link for specified HailPage @param HailPage $page @return string
[ "Return", "the", "Article", "link", "for", "specified", "HailPage" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/Article.php#L288-L291
train
firebrandhq/silverstripe-hail
src/Models/Article.php
Article.getTagList
public function getTagList() { $string = ''; foreach ($this->PublicTags() as $t) { $string .= Convert::raw2url($t->Name) . ' '; } return trim($string); }
php
public function getTagList() { $string = ''; foreach ($this->PublicTags() as $t) { $string .= Convert::raw2url($t->Name) . ' '; } return trim($string); }
[ "public", "function", "getTagList", "(", ")", "{", "$", "string", "=", "''", ";", "foreach", "(", "$", "this", "->", "PublicTags", "(", ")", "as", "$", "t", ")", "{", "$", "string", ".=", "Convert", "::", "raw2url", "(", "$", "t", "->", "Name", "...
List of this Article's public tag names separated by spaces. Suitable to be used as CSS classes. @return string
[ "List", "of", "this", "Article", "s", "public", "tag", "names", "separated", "by", "spaces", "." ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/Article.php#L340-L347
train
firebrandhq/silverstripe-hail
src/Models/Article.php
Article.getAllImages
public function getAllImages() { $images = new ArrayList(); if ($this->hasHeroImage()) { $images->push($this->HeroImage()); } if ($this->hasGalleryImages()) { $images->merge($this->ImageGallery()); } $images->removeDuplicates('HailID'); return $images; }
php
public function getAllImages() { $images = new ArrayList(); if ($this->hasHeroImage()) { $images->push($this->HeroImage()); } if ($this->hasGalleryImages()) { $images->merge($this->ImageGallery()); } $images->removeDuplicates('HailID'); return $images; }
[ "public", "function", "getAllImages", "(", ")", "{", "$", "images", "=", "new", "ArrayList", "(", ")", ";", "if", "(", "$", "this", "->", "hasHeroImage", "(", ")", ")", "{", "$", "images", "->", "push", "(", "$", "this", "->", "HeroImage", "(", ")"...
List of this Article's images Includes the Hero Image @return ArrayList
[ "List", "of", "this", "Article", "s", "images" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/Article.php#L356-L368
train
firebrandhq/silverstripe-hail
src/Models/Article.php
Article.getAllVideos
public function getAllVideos() { $videos = new ArrayList(); if ($this->hasHeroVideo()) { $videos->push($this->HeroVideo()); } if ($this->hasGalleryVideos()) { $videos->merge($this->VideoGallery()); } $videos->removeDuplicates('HailID'); return $videos; }
php
public function getAllVideos() { $videos = new ArrayList(); if ($this->hasHeroVideo()) { $videos->push($this->HeroVideo()); } if ($this->hasGalleryVideos()) { $videos->merge($this->VideoGallery()); } $videos->removeDuplicates('HailID'); return $videos; }
[ "public", "function", "getAllVideos", "(", ")", "{", "$", "videos", "=", "new", "ArrayList", "(", ")", ";", "if", "(", "$", "this", "->", "hasHeroVideo", "(", ")", ")", "{", "$", "videos", "->", "push", "(", "$", "this", "->", "HeroVideo", "(", ")"...
List of this Article's videos Includes the Hero Video @return ArrayList
[ "List", "of", "this", "Article", "s", "videos" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Models/Article.php#L377-L389
train
czim/laravel-processor
src/PipelineProcessor.php
PipelineProcessor.doProcessing
protected function doProcessing() { $this->prepareProcessContext(); // initialization process pipeline $initSteps = $this->initProcessSteps(); if ( ! empty($initSteps)) { $this->context = app(Pipeline::class) ->send($this->context) ->through($initSteps) ->then(function (ProcessContextInterface $context) { return $context; }); $this->afterInitSteps(); } // main pipeline (actual processing) $steps = $this->processSteps(); if ($this->databaseTransaction) DB::beginTransaction(); try { $this->context = app(Pipeline::class) ->send($this->context) ->through($steps) ->then(function(ProcessContextInterface $context) { if ($this->databaseTransaction) DB::commit(); return $context; }); } catch (Exception $e) { if ($this->databaseTransaction) DB::rollBack(); $this->onExceptionInPipeline($e); throw $e; } $this->afterPipeline(); $this->populateResult(); }
php
protected function doProcessing() { $this->prepareProcessContext(); // initialization process pipeline $initSteps = $this->initProcessSteps(); if ( ! empty($initSteps)) { $this->context = app(Pipeline::class) ->send($this->context) ->through($initSteps) ->then(function (ProcessContextInterface $context) { return $context; }); $this->afterInitSteps(); } // main pipeline (actual processing) $steps = $this->processSteps(); if ($this->databaseTransaction) DB::beginTransaction(); try { $this->context = app(Pipeline::class) ->send($this->context) ->through($steps) ->then(function(ProcessContextInterface $context) { if ($this->databaseTransaction) DB::commit(); return $context; }); } catch (Exception $e) { if ($this->databaseTransaction) DB::rollBack(); $this->onExceptionInPipeline($e); throw $e; } $this->afterPipeline(); $this->populateResult(); }
[ "protected", "function", "doProcessing", "(", ")", "{", "$", "this", "->", "prepareProcessContext", "(", ")", ";", "// initialization process pipeline", "$", "initSteps", "=", "$", "this", "->", "initProcessSteps", "(", ")", ";", "if", "(", "!", "empty", "(", ...
Performs the actual processing
[ "Performs", "the", "actual", "processing" ]
3d0025cd463653b7a8981ff52cebdafbe978f000
https://github.com/czim/laravel-processor/blob/3d0025cd463653b7a8981ff52cebdafbe978f000/src/PipelineProcessor.php#L77-L131
train
flipboxfactory/craft-ember
src/helpers/ObjectHelper.php
ObjectHelper.findClassFromConfig
public static function findClassFromConfig(&$config, bool $removeClass = false) { // Normalize the config if (is_string($config)) { // Set as class $class = $config; // Clear class from config $config = ''; } elseif (is_object($config)) { return get_class($config); } else { // Force Array if (!is_array($config)) { $config = ArrayHelper::toArray($config, [], false); } if ($removeClass) { if (!$class = ArrayHelper::remove($config, 'class')) { $class = ArrayHelper::remove($config, 'type'); } } else { $class = ArrayHelper::getValue( $config, 'class', ArrayHelper::getValue($config, 'type') ); } } return $class; }
php
public static function findClassFromConfig(&$config, bool $removeClass = false) { // Normalize the config if (is_string($config)) { // Set as class $class = $config; // Clear class from config $config = ''; } elseif (is_object($config)) { return get_class($config); } else { // Force Array if (!is_array($config)) { $config = ArrayHelper::toArray($config, [], false); } if ($removeClass) { if (!$class = ArrayHelper::remove($config, 'class')) { $class = ArrayHelper::remove($config, 'type'); } } else { $class = ArrayHelper::getValue( $config, 'class', ArrayHelper::getValue($config, 'type') ); } } return $class; }
[ "public", "static", "function", "findClassFromConfig", "(", "&", "$", "config", ",", "bool", "$", "removeClass", "=", "false", ")", "{", "// Normalize the config", "if", "(", "is_string", "(", "$", "config", ")", ")", "{", "// Set as class", "$", "class", "=...
Find a class from a config @param $config @param bool $removeClass @return null|string
[ "Find", "a", "class", "from", "a", "config" ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/helpers/ObjectHelper.php#L126-L157
train
flipboxfactory/craft-ember
src/records/FieldAttributeTrait.php
FieldAttributeTrait.getFieldId
public function getFieldId() { $fieldId = $this->getAttribute('fieldId'); if (null === $fieldId && null !== $this->field) { $fieldId = $this->$fieldId = $this->field->id; } return $fieldId; }
php
public function getFieldId() { $fieldId = $this->getAttribute('fieldId'); if (null === $fieldId && null !== $this->field) { $fieldId = $this->$fieldId = $this->field->id; } return $fieldId; }
[ "public", "function", "getFieldId", "(", ")", "{", "$", "fieldId", "=", "$", "this", "->", "getAttribute", "(", "'fieldId'", ")", ";", "if", "(", "null", "===", "$", "fieldId", "&&", "null", "!==", "$", "this", "->", "field", ")", "{", "$", "fieldId"...
Get associated fieldId @return int|null
[ "Get", "associated", "fieldId" ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/records/FieldAttributeTrait.php#L54-L62
train
faustbrian/Laravel-Alert
src/Alert.php
Alert.success
public function success($message, ?string $title = null): self { return $this->flash($message, config('laravel-alert.classes.success'), $title); }
php
public function success($message, ?string $title = null): self { return $this->flash($message, config('laravel-alert.classes.success'), $title); }
[ "public", "function", "success", "(", "$", "message", ",", "?", "string", "$", "title", "=", "null", ")", ":", "self", "{", "return", "$", "this", "->", "flash", "(", "$", "message", ",", "config", "(", "'laravel-alert.classes.success'", ")", ",", "$", ...
Flash a success alert. @param string|array $message @param string|null $title @return \BrianFaust\Alert\Alert
[ "Flash", "a", "success", "alert", "." ]
d9a039b0395130e882f44b4ceb63b1d77a5429f6
https://github.com/faustbrian/Laravel-Alert/blob/d9a039b0395130e882f44b4ceb63b1d77a5429f6/src/Alert.php#L71-L74
train
davidecesarano/Embryo-Http
Embryo/Http/Message/Traits/RequestTrait.php
RequestTrait.setRequestTarget
protected function setRequestTarget(string $path, string $query) { $target = $path; if ($target === '') { $target = '/'; } if ($query != '') { $target .= '?'.$query; } return $target; }
php
protected function setRequestTarget(string $path, string $query) { $target = $path; if ($target === '') { $target = '/'; } if ($query != '') { $target .= '?'.$query; } return $target; }
[ "protected", "function", "setRequestTarget", "(", "string", "$", "path", ",", "string", "$", "query", ")", "{", "$", "target", "=", "$", "path", ";", "if", "(", "$", "target", "===", "''", ")", "{", "$", "target", "=", "'/'", ";", "}", "if", "(", ...
Sets request target. @param string $path @param string $query @return string
[ "Sets", "request", "target", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/Traits/RequestTrait.php#L48-L59
train
appaydin/pd-mailer
Form/TemplateForm.php
TemplateForm.getLanguageList
public function getLanguageList(ParameterBagInterface $bag) { $allLangs = Intl::getLanguageBundle()->getLanguageNames(); return array_flip(array_intersect_key($allLangs, array_flip($bag->get('pd_mailer.active_language')))); }
php
public function getLanguageList(ParameterBagInterface $bag) { $allLangs = Intl::getLanguageBundle()->getLanguageNames(); return array_flip(array_intersect_key($allLangs, array_flip($bag->get('pd_mailer.active_language')))); }
[ "public", "function", "getLanguageList", "(", "ParameterBagInterface", "$", "bag", ")", "{", "$", "allLangs", "=", "Intl", "::", "getLanguageBundle", "(", ")", "->", "getLanguageNames", "(", ")", ";", "return", "array_flip", "(", "array_intersect_key", "(", "$",...
Return Active Language List. @param ParameterBagInterface $bag @return array|bool
[ "Return", "Active", "Language", "List", "." ]
c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f
https://github.com/appaydin/pd-mailer/blob/c701cf6778e9c8991ae4b74dbf5e7d3d77310c0f/Form/TemplateForm.php#L94-L99
train
Ifnot/statistics
src/Interval.php
Interval.step
public function step($step = null) { if (isset($step)) { $this->step = $step; return $this; } else { return $this->step; } }
php
public function step($step = null) { if (isset($step)) { $this->step = $step; return $this; } else { return $this->step; } }
[ "public", "function", "step", "(", "$", "step", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "step", ")", ")", "{", "$", "this", "->", "step", "=", "$", "step", ";", "return", "$", "this", ";", "}", "else", "{", "return", "$", "this", ...
Set or get the step of the interval @param null $step @return $this|null
[ "Set", "or", "get", "the", "step", "of", "the", "interval" ]
9aba4b193b76cfdd87547b6d319917815704e5b1
https://github.com/Ifnot/statistics/blob/9aba4b193b76cfdd87547b6d319917815704e5b1/src/Interval.php#L44-L52
train
Ifnot/statistics
src/Interval.php
Interval.start
public function start(Carbon $date = null) { if (isset($date)) { $date->hour = 0; $date->minute = 0; $date->second = 0; $this->start = $date; return $this; } else { return $this->start; } }
php
public function start(Carbon $date = null) { if (isset($date)) { $date->hour = 0; $date->minute = 0; $date->second = 0; $this->start = $date; return $this; } else { return $this->start; } }
[ "public", "function", "start", "(", "Carbon", "$", "date", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "date", ")", ")", "{", "$", "date", "->", "hour", "=", "0", ";", "$", "date", "->", "minute", "=", "0", ";", "$", "date", "->", "s...
Set or get the start date of the interval @param Carbon|null $date @return $this|Carbon
[ "Set", "or", "get", "the", "start", "date", "of", "the", "interval" ]
9aba4b193b76cfdd87547b6d319917815704e5b1
https://github.com/Ifnot/statistics/blob/9aba4b193b76cfdd87547b6d319917815704e5b1/src/Interval.php#L60-L73
train
Ifnot/statistics
src/Interval.php
Interval.getStepIndexFromDate
public function getStepIndexFromDate(Carbon $date) { switch ($this->step) { case "yearly": $date->month = 1; case "monthly": $date->day = 1; case "daily": $date->hour = 0; case "hourly": $date->minute = 0; default: $date->second = 0; break; } return $date->format($this->getStepFormat()); }
php
public function getStepIndexFromDate(Carbon $date) { switch ($this->step) { case "yearly": $date->month = 1; case "monthly": $date->day = 1; case "daily": $date->hour = 0; case "hourly": $date->minute = 0; default: $date->second = 0; break; } return $date->format($this->getStepFormat()); }
[ "public", "function", "getStepIndexFromDate", "(", "Carbon", "$", "date", ")", "{", "switch", "(", "$", "this", "->", "step", ")", "{", "case", "\"yearly\"", ":", "$", "date", "->", "month", "=", "1", ";", "case", "\"monthly\"", ":", "$", "date", "->",...
Converting a date to his step index according to the step precision of the interval @param Carbon $date @return string
[ "Converting", "a", "date", "to", "his", "step", "index", "according", "to", "the", "step", "precision", "of", "the", "interval" ]
9aba4b193b76cfdd87547b6d319917815704e5b1
https://github.com/Ifnot/statistics/blob/9aba4b193b76cfdd87547b6d319917815704e5b1/src/Interval.php#L123-L140
train
Ifnot/statistics
src/Interval.php
Interval.getStepFormat
public function getStepFormat() { if ($this->lang == 'en') { switch ($this->step) { case self::$YEARLY: return 'Y'; break; case self::$MONTHLY: return 'Y-m'; break; case self::$DAILY: return 'Y-m-d'; break; case self::$HOURLY: return 'Y-m-d H:00'; break; } } elseif ($this->lang == 'fr') { switch ($this->step) { case self::$YEARLY: return 'Y'; break; case self::$MONTHLY: return 'm/Y'; break; case self::$DAILY: return 'd/m/Y'; break; case self::$HOURLY: return 'd/m/Y H:00'; break; } } return false; }
php
public function getStepFormat() { if ($this->lang == 'en') { switch ($this->step) { case self::$YEARLY: return 'Y'; break; case self::$MONTHLY: return 'Y-m'; break; case self::$DAILY: return 'Y-m-d'; break; case self::$HOURLY: return 'Y-m-d H:00'; break; } } elseif ($this->lang == 'fr') { switch ($this->step) { case self::$YEARLY: return 'Y'; break; case self::$MONTHLY: return 'm/Y'; break; case self::$DAILY: return 'd/m/Y'; break; case self::$HOURLY: return 'd/m/Y H:00'; break; } } return false; }
[ "public", "function", "getStepFormat", "(", ")", "{", "if", "(", "$", "this", "->", "lang", "==", "'en'", ")", "{", "switch", "(", "$", "this", "->", "step", ")", "{", "case", "self", "::", "$", "YEARLY", ":", "return", "'Y'", ";", "break", ";", ...
Get the step index format of the step precision @return array
[ "Get", "the", "step", "index", "format", "of", "the", "step", "precision" ]
9aba4b193b76cfdd87547b6d319917815704e5b1
https://github.com/Ifnot/statistics/blob/9aba4b193b76cfdd87547b6d319917815704e5b1/src/Interval.php#L147-L182
train
Ifnot/statistics
src/Interval.php
Interval.getStepIncrement
public function getStepIncrement() { switch ($this->step) { case self::$YEARLY: return '+1 year'; break; case self::$MONTHLY: return '+1 month'; break; case self::$DAILY: return '+1 day'; break; case self::$HOURLY: return '+1 hour'; break; } }
php
public function getStepIncrement() { switch ($this->step) { case self::$YEARLY: return '+1 year'; break; case self::$MONTHLY: return '+1 month'; break; case self::$DAILY: return '+1 day'; break; case self::$HOURLY: return '+1 hour'; break; } }
[ "public", "function", "getStepIncrement", "(", ")", "{", "switch", "(", "$", "this", "->", "step", ")", "{", "case", "self", "::", "$", "YEARLY", ":", "return", "'+1 year'", ";", "break", ";", "case", "self", "::", "$", "MONTHLY", ":", "return", "'+1 m...
Get the string corresponding to the incrementation of each steps @return string
[ "Get", "the", "string", "corresponding", "to", "the", "incrementation", "of", "each", "steps" ]
9aba4b193b76cfdd87547b6d319917815704e5b1
https://github.com/Ifnot/statistics/blob/9aba4b193b76cfdd87547b6d319917815704e5b1/src/Interval.php#L189-L205
train
davidecesarano/Embryo-Http
Embryo/Http/Factory/ServerRequestFactory.php
ServerRequestFactory.createServerRequestFromServer
public function createServerRequestFromServer(): ServerRequestInterface { $method = $_SERVER['REQUEST_METHOD']; $uri = (new UriFactory)->createUriFromServer($_SERVER); $files = (new UploadedFileFactory)->createUploadedFileFromServer($_FILES); $request = $this->createServerRequest($method, $uri, $_SERVER); $request = $request->withQueryParams($_GET); $request = $request->withParsedBody($_POST); $request = $request->withCookieParams($_COOKIE); $request = $request->withUploadedFiles($files); return $request; }
php
public function createServerRequestFromServer(): ServerRequestInterface { $method = $_SERVER['REQUEST_METHOD']; $uri = (new UriFactory)->createUriFromServer($_SERVER); $files = (new UploadedFileFactory)->createUploadedFileFromServer($_FILES); $request = $this->createServerRequest($method, $uri, $_SERVER); $request = $request->withQueryParams($_GET); $request = $request->withParsedBody($_POST); $request = $request->withCookieParams($_COOKIE); $request = $request->withUploadedFiles($files); return $request; }
[ "public", "function", "createServerRequestFromServer", "(", ")", ":", "ServerRequestInterface", "{", "$", "method", "=", "$", "_SERVER", "[", "'REQUEST_METHOD'", "]", ";", "$", "uri", "=", "(", "new", "UriFactory", ")", "->", "createUriFromServer", "(", "$", "...
Creates a new server-side request from server. @return ServerRequestInterface
[ "Creates", "a", "new", "server", "-", "side", "request", "from", "server", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Factory/ServerRequestFactory.php#L39-L51
train
Vectorface/cache
src/SQLCache.php
SQLCache.get
public function get($key) { try { $stmt = $this->getStatement(__METHOD__, self::GET_SQL); $stmt->execute(array($key)); } catch (\PDOException $e) { return false; } $result = $stmt->fetchColumn(); return empty($result) ? false : unserialize($result); }
php
public function get($key) { try { $stmt = $this->getStatement(__METHOD__, self::GET_SQL); $stmt->execute(array($key)); } catch (\PDOException $e) { return false; } $result = $stmt->fetchColumn(); return empty($result) ? false : unserialize($result); }
[ "public", "function", "get", "(", "$", "key", ")", "{", "try", "{", "$", "stmt", "=", "$", "this", "->", "getStatement", "(", "__METHOD__", ",", "self", "::", "GET_SQL", ")", ";", "$", "stmt", "->", "execute", "(", "array", "(", "$", "key", ")", ...
Attempt to retrieve an entry from the cache. The value will be unserialized before it is returned. @return mixed Returns the value stored for the given key, or false on failure.
[ "Attempt", "to", "retrieve", "an", "entry", "from", "the", "cache", "." ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/SQLCache.php#L95-L105
train
Vectorface/cache
src/SQLCache.php
SQLCache.clean
public function clean() { try { $this->conn->exec(self::CLEAN_SQL); } catch (\PDOException $e) { return false; } return true; }
php
public function clean() { try { $this->conn->exec(self::CLEAN_SQL); } catch (\PDOException $e) { return false; } return true; }
[ "public", "function", "clean", "(", ")", "{", "try", "{", "$", "this", "->", "conn", "->", "exec", "(", "self", "::", "CLEAN_SQL", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "return", "false", ";", "}", "return", "true",...
Remove any expired items from the cache. @return bool True if successful, false otherwise.
[ "Remove", "any", "expired", "items", "from", "the", "cache", "." ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/SQLCache.php#L156-L164
train
Vectorface/cache
src/SQLCache.php
SQLCache.flush
public function flush() { try { $this->conn->exec(self::FLUSH_SQL); } catch (\PDOException $e) { return false; } return true; }
php
public function flush() { try { $this->conn->exec(self::FLUSH_SQL); } catch (\PDOException $e) { return false; } return true; }
[ "public", "function", "flush", "(", ")", "{", "try", "{", "$", "this", "->", "conn", "->", "exec", "(", "self", "::", "FLUSH_SQL", ")", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "return", "false", ";", "}", "return", "true",...
Flush the cache; Empty it of all entries. @return bool True if successful, false otherwise.
[ "Flush", "the", "cache", ";", "Empty", "it", "of", "all", "entries", "." ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/SQLCache.php#L171-L179
train
Vectorface/cache
src/SQLCache.php
SQLCache.getStatement
private function getStatement($method, $sql) { if (empty($this->statements[$method])) { $this->statements[$method] = $this->conn->prepare($sql); } return $this->statements[$method]; }
php
private function getStatement($method, $sql) { if (empty($this->statements[$method])) { $this->statements[$method] = $this->conn->prepare($sql); } return $this->statements[$method]; }
[ "private", "function", "getStatement", "(", "$", "method", ",", "$", "sql", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "statements", "[", "$", "method", "]", ")", ")", "{", "$", "this", "->", "statements", "[", "$", "method", "]", "=", ...
Get a prepared statement for the given method's SQL. The result is stored internally to limit repeated preparing of SQL. @param string $method The method name to for which this statement applies. @param string $sql The SQL statement associated with the given method. @return \PDOStatement Returns the prepared statement for the given method.
[ "Get", "a", "prepared", "statement", "for", "the", "given", "method", "s", "SQL", "." ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/SQLCache.php#L190-L196
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Plugin/Package.php
Package.find
protected function find($directory) { if ($iterator = parent::find($directory)) { foreach ($iterator as $file) { if (is_file($file) && is_readable($file) && $contents = file_get_contents($file)) { if (preg_match($this->packageNamePattern, basename($file))) { $plugin = (object) null; $plugin->name = implode('_v', array_slice(explode('_v', basename($file, '.txt')), 0, -1)); $this->plugin[] = $plugin; $this->package[] = $contents; } } } } return !empty($this->plugin); }
php
protected function find($directory) { if ($iterator = parent::find($directory)) { foreach ($iterator as $file) { if (is_file($file) && is_readable($file) && $contents = file_get_contents($file)) { if (preg_match($this->packageNamePattern, basename($file))) { $plugin = (object) null; $plugin->name = implode('_v', array_slice(explode('_v', basename($file, '.txt')), 0, -1)); $this->plugin[] = $plugin; $this->package[] = $contents; } } } } return !empty($this->plugin); }
[ "protected", "function", "find", "(", "$", "directory", ")", "{", "if", "(", "$", "iterator", "=", "parent", "::", "find", "(", "$", "directory", ")", ")", "{", "foreach", "(", "$", "iterator", "as", "$", "file", ")", "{", "if", "(", "is_file", "("...
Finds plugin packages. @param string $directory @return bool
[ "Finds", "plugin", "packages", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Plugin/Package.php#L47-L63
train
davidecesarano/Embryo-Http
Embryo/Http/Message/Response.php
Response.withStatus
public function withStatus($status, $reasonPhrase = '') { $status = $this->filterStatus($status); $reasonPhrase = $this->filterReasonPhrase($status, $reasonPhrase); $clone = clone $this; $clone->status = $status; $clone->reasonPhrase = $reasonPhrase; return $clone; }
php
public function withStatus($status, $reasonPhrase = '') { $status = $this->filterStatus($status); $reasonPhrase = $this->filterReasonPhrase($status, $reasonPhrase); $clone = clone $this; $clone->status = $status; $clone->reasonPhrase = $reasonPhrase; return $clone; }
[ "public", "function", "withStatus", "(", "$", "status", ",", "$", "reasonPhrase", "=", "''", ")", "{", "$", "status", "=", "$", "this", "->", "filterStatus", "(", "$", "status", ")", ";", "$", "reasonPhrase", "=", "$", "this", "->", "filterReasonPhrase",...
Returns an instance with the specified status code and, optionally, reason phrase. @param int $status @param string $reasonPhrase @return static @throws InvalidArgumentException
[ "Returns", "an", "instance", "with", "the", "specified", "status", "code", "and", "optionally", "reason", "phrase", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/Response.php#L68-L77
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Installer/AdminTheme.php
AdminTheme.getInstallPath
public function getInstallPath(PackageInterface $package) { $textpattern = new Textpattern(); $path = $textpattern->getRelativePath(); $themes = $path . '/admin-themes'; // Textpattern <= 4.5.x uses 'theme' directory. if (!file_exists($themes)) { $themes = $path . '/theme'; } return $themes . '/' . basename($package->getPrettyName()); }
php
public function getInstallPath(PackageInterface $package) { $textpattern = new Textpattern(); $path = $textpattern->getRelativePath(); $themes = $path . '/admin-themes'; // Textpattern <= 4.5.x uses 'theme' directory. if (!file_exists($themes)) { $themes = $path . '/theme'; } return $themes . '/' . basename($package->getPrettyName()); }
[ "public", "function", "getInstallPath", "(", "PackageInterface", "$", "package", ")", "{", "$", "textpattern", "=", "new", "Textpattern", "(", ")", ";", "$", "path", "=", "$", "textpattern", "->", "getRelativePath", "(", ")", ";", "$", "themes", "=", "$", ...
Points the package to the theme directory. @param PackageInterface $package @return string
[ "Points", "the", "package", "to", "the", "theme", "directory", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Installer/AdminTheme.php#L54-L66
train
CradlePHP/cradle-system
src/Fieldset/Validator.php
Validator.getUpdateErrors
public static function getUpdateErrors(array $data, array $errors = []) { if (isset($data['singular']) && empty($data['singular'])) { $errors['singular'] = 'Singular is required'; } if (isset($data['plural']) && empty($data['plural'])) { $errors['plural'] = 'Plural is required'; } if (isset($data['name']) && empty($data['name'])) { $errors['name'] = 'Keyword is required'; } if (!isset($data['fields']) || empty($data['fields'])) { $errors['fields'] = 'Fields is required'; } return self::getOptionalErrors($data, $errors); }
php
public static function getUpdateErrors(array $data, array $errors = []) { if (isset($data['singular']) && empty($data['singular'])) { $errors['singular'] = 'Singular is required'; } if (isset($data['plural']) && empty($data['plural'])) { $errors['plural'] = 'Plural is required'; } if (isset($data['name']) && empty($data['name'])) { $errors['name'] = 'Keyword is required'; } if (!isset($data['fields']) || empty($data['fields'])) { $errors['fields'] = 'Fields is required'; } return self::getOptionalErrors($data, $errors); }
[ "public", "static", "function", "getUpdateErrors", "(", "array", "$", "data", ",", "array", "$", "errors", "=", "[", "]", ")", "{", "if", "(", "isset", "(", "$", "data", "[", "'singular'", "]", ")", "&&", "empty", "(", "$", "data", "[", "'singular'",...
Returns Table Update Errors @param *array $data @param array $errors @return array
[ "Returns", "Table", "Update", "Errors" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Fieldset/Validator.php#L72-L91
train
Vectorface/cache
src/TempFileCache.php
TempFileCache.getTempDir
private function getTempDir($directory) { if (empty($directory) || !is_string($directory)) { $classParts = explode("\\", get_called_class()); return sys_get_temp_dir() . '/' . end($classParts); } elseif (strpos($directory, '/') !== 0) { return sys_get_temp_dir() . '/' . $directory; } else { return $directory; } }
php
private function getTempDir($directory) { if (empty($directory) || !is_string($directory)) { $classParts = explode("\\", get_called_class()); return sys_get_temp_dir() . '/' . end($classParts); } elseif (strpos($directory, '/') !== 0) { return sys_get_temp_dir() . '/' . $directory; } else { return $directory; } }
[ "private", "function", "getTempDir", "(", "$", "directory", ")", "{", "if", "(", "empty", "(", "$", "directory", ")", "||", "!", "is_string", "(", "$", "directory", ")", ")", "{", "$", "classParts", "=", "explode", "(", "\"\\\\\"", ",", "get_called_class...
Generate a consistent temporary directory based on a requested directory name. @param string $directory The name or path of a temporary directory. @return string The directory name, resolved to a full path.
[ "Generate", "a", "consistent", "temporary", "directory", "based", "on", "a", "requested", "directory", "name", "." ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/TempFileCache.php#L50-L60
train
Vectorface/cache
src/TempFileCache.php
TempFileCache.getCacheFiles
private function getCacheFiles() { if (!($files = @scandir($this->directory, 1))) { return false; } $negExtLen = -1 * strlen($this->extension); $return = array(); foreach ($files as $file) { if (substr($file, $negExtLen) === $this->extension) { $return[] = $this->directory . '/' . $file; } } return $return; }
php
private function getCacheFiles() { if (!($files = @scandir($this->directory, 1))) { return false; } $negExtLen = -1 * strlen($this->extension); $return = array(); foreach ($files as $file) { if (substr($file, $negExtLen) === $this->extension) { $return[] = $this->directory . '/' . $file; } } return $return; }
[ "private", "function", "getCacheFiles", "(", ")", "{", "if", "(", "!", "(", "$", "files", "=", "@", "scandir", "(", "$", "this", "->", "directory", ",", "1", ")", ")", ")", "{", "return", "false", ";", "}", "$", "negExtLen", "=", "-", "1", "*", ...
Finds all files with the cache extension in the cache directory @return Array Returns an array of filenames that represent cached entries.
[ "Finds", "all", "files", "with", "the", "cache", "extension", "in", "the", "cache", "directory" ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/TempFileCache.php#L166-L180
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Textpattern/Find.php
Find.find
public function find($directory) { if (($path = $this->isConfig('./textpattern/config.php')) !== false) { return realpath($path); } if (!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { return false; } $iterator = new \RecursiveDirectoryIterator(realpath($directory)); $iterator = new \RecursiveIteratorIterator($iterator); foreach ($iterator as $file) { if (($path = $this->isConfig($file)) !== false) { return $path; } } return false; }
php
public function find($directory) { if (($path = $this->isConfig('./textpattern/config.php')) !== false) { return realpath($path); } if (!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { return false; } $iterator = new \RecursiveDirectoryIterator(realpath($directory)); $iterator = new \RecursiveIteratorIterator($iterator); foreach ($iterator as $file) { if (($path = $this->isConfig($file)) !== false) { return $path; } } return false; }
[ "public", "function", "find", "(", "$", "directory", ")", "{", "if", "(", "(", "$", "path", "=", "$", "this", "->", "isConfig", "(", "'./textpattern/config.php'", ")", ")", "!==", "false", ")", "{", "return", "realpath", "(", "$", "path", ")", ";", "...
Finds the closest Textpattern installation path. @param string The directory @return string|bool The path, or FALSE
[ "Finds", "the", "closest", "Textpattern", "installation", "path", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Textpattern/Find.php#L74-L94
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Textpattern/Find.php
Find.isConfig
protected function isConfig($file) { if (basename($file) === 'config.php' && is_file($file) && is_readable($file)) { $contents = file_get_contents($file); if ($contents && strpos($contents, 'txpcfg') !== false && file_exists(dirname($file) . '/publish.php')) { return dirname($file); } } return false; }
php
protected function isConfig($file) { if (basename($file) === 'config.php' && is_file($file) && is_readable($file)) { $contents = file_get_contents($file); if ($contents && strpos($contents, 'txpcfg') !== false && file_exists(dirname($file) . '/publish.php')) { return dirname($file); } } return false; }
[ "protected", "function", "isConfig", "(", "$", "file", ")", "{", "if", "(", "basename", "(", "$", "file", ")", "===", "'config.php'", "&&", "is_file", "(", "$", "file", ")", "&&", "is_readable", "(", "$", "file", ")", ")", "{", "$", "contents", "=", ...
Whether the file is a config.php. @param string $file The filename @return string|bool Path to the directory, or FALSE
[ "Whether", "the", "file", "is", "a", "config", ".", "php", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Textpattern/Find.php#L102-L113
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Textpattern/Find.php
Find.getRelativePath
public function getRelativePath() { $current = realpath('./'); if ($current !== false && strpos(self::$path.'/', $current.'/') === 0) { return rtrim('./' . substr(self::$path, strlen($current) + 1), '\\/'); } throw new \InvalidArgumentException( 'Unable to resolve relative path to Textpattern installation location '. 'from the current working directory.' ); }
php
public function getRelativePath() { $current = realpath('./'); if ($current !== false && strpos(self::$path.'/', $current.'/') === 0) { return rtrim('./' . substr(self::$path, strlen($current) + 1), '\\/'); } throw new \InvalidArgumentException( 'Unable to resolve relative path to Textpattern installation location '. 'from the current working directory.' ); }
[ "public", "function", "getRelativePath", "(", ")", "{", "$", "current", "=", "realpath", "(", "'./'", ")", ";", "if", "(", "$", "current", "!==", "false", "&&", "strpos", "(", "self", "::", "$", "path", ".", "'/'", ",", "$", "current", ".", "'/'", ...
Gets relative path to the Textpattern installation. The path is relative to the current working directory. @return string The path @throws \InvalidArgumentException
[ "Gets", "relative", "path", "to", "the", "Textpattern", "installation", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Textpattern/Find.php#L123-L135
train
peterkahl/Apple-iOS-build
src/iOSbuild.php
iOSbuild.getVersion
public static function getVersion($needle) { self::populate(); if (array_key_exists($needle, self::$BuildVer)) { return self::$BuildVer[$needle]; } $builds = array(); $versions = array(); foreach (self::$BuildVer as $code => $val) { $builds[] = $code; $versions[] = $val; } $candidate = false; if (preg_match('/^(\d+)([A-Z])(\d+)([a-z])?$/', $needle, $matchNeedle)) { # Walk backwards $count = count($builds); for ($key = $count - 1; $key >= 0; $key--) { preg_match('/^(\d+)([A-Z])(\d+)([a-z])?$/', $builds[$key], $matchCode); if ($matchCode[1] . $matchCode[2] . $matchCode[3] == $matchNeedle[1] . $matchNeedle[2] . $matchNeedle[3]) { return $versions[$key]; } if ($matchCode[1] . $matchCode[2] == $matchNeedle[1] . $matchNeedle[2] && $matchNeedle[3] > $matchCode[3]) { $candidate = $versions[$key]; } } } if (!empty($candidate)) { return preg_replace('/b\d+$/', '', $candidate); } return $candidate; }
php
public static function getVersion($needle) { self::populate(); if (array_key_exists($needle, self::$BuildVer)) { return self::$BuildVer[$needle]; } $builds = array(); $versions = array(); foreach (self::$BuildVer as $code => $val) { $builds[] = $code; $versions[] = $val; } $candidate = false; if (preg_match('/^(\d+)([A-Z])(\d+)([a-z])?$/', $needle, $matchNeedle)) { # Walk backwards $count = count($builds); for ($key = $count - 1; $key >= 0; $key--) { preg_match('/^(\d+)([A-Z])(\d+)([a-z])?$/', $builds[$key], $matchCode); if ($matchCode[1] . $matchCode[2] . $matchCode[3] == $matchNeedle[1] . $matchNeedle[2] . $matchNeedle[3]) { return $versions[$key]; } if ($matchCode[1] . $matchCode[2] == $matchNeedle[1] . $matchNeedle[2] && $matchNeedle[3] > $matchCode[3]) { $candidate = $versions[$key]; } } } if (!empty($candidate)) { return preg_replace('/b\d+$/', '', $candidate); } return $candidate; }
[ "public", "static", "function", "getVersion", "(", "$", "needle", ")", "{", "self", "::", "populate", "(", ")", ";", "if", "(", "array_key_exists", "(", "$", "needle", ",", "self", "::", "$", "BuildVer", ")", ")", "{", "return", "self", "::", "$", "B...
Takes iOS build code and returns corresponding iOS version. @param string $needle @return mixed @throws \Exception
[ "Takes", "iOS", "build", "code", "and", "returns", "corresponding", "iOS", "version", "." ]
90c0e0db5e87f2f4487048ecb6b81a3395e33cab
https://github.com/peterkahl/Apple-iOS-build/blob/90c0e0db5e87f2f4487048ecb6b81a3395e33cab/src/iOSbuild.php#L49-L78
train
peterkahl/Apple-iOS-build
src/iOSbuild.php
iOSbuild.populate
private static function populate() { $arr = array(); $epoch = 0; if (!isset(self::$BuildVer) || !is_array(self::$BuildVer)) { require __DIR__ .'/data.php'; if (empty($arr) || !is_array($arr) || empty($epoch)) { throw new \Exception('Error fetching file data.php'); } self::$DataTimestamp = $epoch; self::$BuildVer = $arr; } }
php
private static function populate() { $arr = array(); $epoch = 0; if (!isset(self::$BuildVer) || !is_array(self::$BuildVer)) { require __DIR__ .'/data.php'; if (empty($arr) || !is_array($arr) || empty($epoch)) { throw new \Exception('Error fetching file data.php'); } self::$DataTimestamp = $epoch; self::$BuildVer = $arr; } }
[ "private", "static", "function", "populate", "(", ")", "{", "$", "arr", "=", "array", "(", ")", ";", "$", "epoch", "=", "0", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "BuildVer", ")", "||", "!", "is_array", "(", "self", "::", "$", "...
Populates associative array of iOS versions. @throws \Exception
[ "Populates", "associative", "array", "of", "iOS", "versions", "." ]
90c0e0db5e87f2f4487048ecb6b81a3395e33cab
https://github.com/peterkahl/Apple-iOS-build/blob/90c0e0db5e87f2f4487048ecb6b81a3395e33cab/src/iOSbuild.php#L87-L98
train
peterkahl/Apple-iOS-build
src/iOSbuild.php
iOSbuild.getCalendarUA
public static function getCalendarUA($min = '5.0') { if (strpos($min, '.') === false && ctype_digit($min)) { $mins[0] = $min; $mins[1] = 0; } else { $mins = explode('.', $min); } $builds = array(); $versions = array(); $n = 0; self::populate(); foreach (self::$BuildVer as $code => $val) { $parts = explode('.', $val); if ($parts[0] >= $mins[0] && $parts[1] >= $mins[1]) { $builds[$n] = $code; $versions[$n] = $val; $n++; } } $ran = mt_rand(0, $n - 1); $ver = preg_replace('/b\d+$/', '', $versions[$ran]); return 'iOS/' . $ver . ' (' . $builds[$ran] . ') dataaccessd/1.0'; }
php
public static function getCalendarUA($min = '5.0') { if (strpos($min, '.') === false && ctype_digit($min)) { $mins[0] = $min; $mins[1] = 0; } else { $mins = explode('.', $min); } $builds = array(); $versions = array(); $n = 0; self::populate(); foreach (self::$BuildVer as $code => $val) { $parts = explode('.', $val); if ($parts[0] >= $mins[0] && $parts[1] >= $mins[1]) { $builds[$n] = $code; $versions[$n] = $val; $n++; } } $ran = mt_rand(0, $n - 1); $ver = preg_replace('/b\d+$/', '', $versions[$ran]); return 'iOS/' . $ver . ' (' . $builds[$ran] . ') dataaccessd/1.0'; }
[ "public", "static", "function", "getCalendarUA", "(", "$", "min", "=", "'5.0'", ")", "{", "if", "(", "strpos", "(", "$", "min", ",", "'.'", ")", "===", "false", "&&", "ctype_digit", "(", "$", "min", ")", ")", "{", "$", "mins", "[", "0", "]", "=",...
Returns a randomly chosen iOS Calendar User Agent string. @param string $min .... minimum version Format: 'MAJOR.MINOR' (1 dot only) @return string @throws \Exception
[ "Returns", "a", "randomly", "chosen", "iOS", "Calendar", "User", "Agent", "string", "." ]
90c0e0db5e87f2f4487048ecb6b81a3395e33cab
https://github.com/peterkahl/Apple-iOS-build/blob/90c0e0db5e87f2f4487048ecb6b81a3395e33cab/src/iOSbuild.php#L133-L156
train
davidecesarano/Embryo-Http
Embryo/Http/Message/Traits/ResponseTrait.php
ResponseTrait.filterStatus
protected function filterStatus(int $status) { $messages = $this->getMessages(); if (!isset($messages[$status])) { throw new \InvalidArgumentException('Invalid HTTP status code'); } return $status; }
php
protected function filterStatus(int $status) { $messages = $this->getMessages(); if (!isset($messages[$status])) { throw new \InvalidArgumentException('Invalid HTTP status code'); } return $status; }
[ "protected", "function", "filterStatus", "(", "int", "$", "status", ")", "{", "$", "messages", "=", "$", "this", "->", "getMessages", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "messages", "[", "$", "status", "]", ")", ")", "{", "throw", "ne...
Validates Http status code. @param int $status @return int @throws InvalidArgumentException
[ "Validates", "Http", "status", "code", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/Traits/ResponseTrait.php#L103-L110
train
davidecesarano/Embryo-Http
Embryo/Http/Message/Traits/ResponseTrait.php
ResponseTrait.filterReasonPhrase
protected function filterReasonPhrase(int $status, string $reasonPhrase = '') { $messages = $this->getMessages(); if ($reasonPhrase === '' && isset($messages[$status])) { $reasonPhrase = $messages[$status]; } return $reasonPhrase; }
php
protected function filterReasonPhrase(int $status, string $reasonPhrase = '') { $messages = $this->getMessages(); if ($reasonPhrase === '' && isset($messages[$status])) { $reasonPhrase = $messages[$status]; } return $reasonPhrase; }
[ "protected", "function", "filterReasonPhrase", "(", "int", "$", "status", ",", "string", "$", "reasonPhrase", "=", "''", ")", "{", "$", "messages", "=", "$", "this", "->", "getMessages", "(", ")", ";", "if", "(", "$", "reasonPhrase", "===", "''", "&&", ...
Validates Http status reason phrase @param int $status @param string $reasonPhrase @return string @throws InvalidArgumentException
[ "Validates", "Http", "status", "reason", "phrase" ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/Traits/ResponseTrait.php#L120-L127
train
davidecesarano/Embryo-Http
Embryo/Http/Message/Traits/ResponseTrait.php
ResponseTrait.withRedirect
public function withRedirect($url, $status = null) { $response = $this->withHeader('Location', (string)$url); if (is_null($status) && $this->getStatusCode() === 200) { $status = 302; } if (!is_null($status)) { return $response->withStatus($status); } return $response; }
php
public function withRedirect($url, $status = null) { $response = $this->withHeader('Location', (string)$url); if (is_null($status) && $this->getStatusCode() === 200) { $status = 302; } if (!is_null($status)) { return $response->withStatus($status); } return $response; }
[ "public", "function", "withRedirect", "(", "$", "url", ",", "$", "status", "=", "null", ")", "{", "$", "response", "=", "$", "this", "->", "withHeader", "(", "'Location'", ",", "(", "string", ")", "$", "url", ")", ";", "if", "(", "is_null", "(", "$...
Prepares the response object to return an HTTP redirect response to the client. @param string|UriInterface $url @param int|null $status @return static
[ "Prepares", "the", "response", "object", "to", "return", "an", "HTTP", "redirect", "response", "to", "the", "client", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/Traits/ResponseTrait.php#L149-L159
train
davidecesarano/Embryo-Http
Embryo/Http/Message/Traits/ResponseTrait.php
ResponseTrait.withJson
public function withJson($data, int $status = null, int $options = 0) { $json = json_encode($data, $options); if ($json === false) { throw new \RuntimeException(json_last_error_msg(), json_last_error()); } $response = $this->write($json); $response = $response->withHeader('Content-Type', 'application/json;charset=utf-8'); if (isset($status)) { return $response->withStatus($status); } return $response; }
php
public function withJson($data, int $status = null, int $options = 0) { $json = json_encode($data, $options); if ($json === false) { throw new \RuntimeException(json_last_error_msg(), json_last_error()); } $response = $this->write($json); $response = $response->withHeader('Content-Type', 'application/json;charset=utf-8'); if (isset($status)) { return $response->withStatus($status); } return $response; }
[ "public", "function", "withJson", "(", "$", "data", ",", "int", "$", "status", "=", "null", ",", "int", "$", "options", "=", "0", ")", "{", "$", "json", "=", "json_encode", "(", "$", "data", ",", "$", "options", ")", ";", "if", "(", "$", "json", ...
Prepares the response object to return an HTTP json response to the client. @param mixed $data @param int $status @param int $options @return static @throws RuntimeException
[ "Prepares", "the", "response", "object", "to", "return", "an", "HTTP", "json", "response", "to", "the", "client", "." ]
5ff81c07fbff3abed051d710f0837544465887c8
https://github.com/davidecesarano/Embryo-Http/blob/5ff81c07fbff3abed051d710f0837544465887c8/Embryo/Http/Message/Traits/ResponseTrait.php#L171-L185
train
flipboxfactory/craft-ember
src/elements/ExplicitElementTrait.php
ExplicitElementTrait.getOne
public static function getOne($criteria) { if (null === ($element = static::findOne($criteria))) { throw new ElementNotFoundException( sprintf( "Organization not found with the following criteria: %s", Json::encode($criteria) ) ); } return $element; }
php
public static function getOne($criteria) { if (null === ($element = static::findOne($criteria))) { throw new ElementNotFoundException( sprintf( "Organization not found with the following criteria: %s", Json::encode($criteria) ) ); } return $element; }
[ "public", "static", "function", "getOne", "(", "$", "criteria", ")", "{", "if", "(", "null", "===", "(", "$", "element", "=", "static", "::", "findOne", "(", "$", "criteria", ")", ")", ")", "{", "throw", "new", "ElementNotFoundException", "(", "sprintf",...
Returns a single element instance by a primary key or a set of element criteria parameters. The method accepts: - an int: query by a single ID value and return the corresponding element (or null if not found). - an array of name-value pairs: query by a set of parameter values and return the first element matching all of them (or null if not found). Note that this method will automatically call the `one()` method and return an [[ElementInterface|\craft\base\Element]] instance. For example, ```php // find a single entry whose ID is 10 $entry = Entry::findOne(10); // the above code is equivalent to: $entry = Entry::find->id(10)->one(); // find the first user whose email ends in "example.com" $user = User::findOne(['email' => '*example.com']); // the above code is equivalent to: $user = User::find()->email('*example.com')->one(); ``` @param mixed $criteria The element ID or a set of element criteria parameters @return static Element instance matching the condition, or null if nothing matches. @throws ElementNotFoundException
[ "Returns", "a", "single", "element", "instance", "by", "a", "primary", "key", "or", "a", "set", "of", "element", "criteria", "parameters", "." ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/elements/ExplicitElementTrait.php#L112-L124
train
Vectorface/cache
src/TieredCache.php
TieredCache.get
public function get($entry) { $value = false; foreach ($this->caches as $cache) { $value = $cache->get($entry); if ($value !== false) { return $value; } } return $value; }
php
public function get($entry) { $value = false; foreach ($this->caches as $cache) { $value = $cache->get($entry); if ($value !== false) { return $value; } } return $value; }
[ "public", "function", "get", "(", "$", "entry", ")", "{", "$", "value", "=", "false", ";", "foreach", "(", "$", "this", "->", "caches", "as", "$", "cache", ")", "{", "$", "value", "=", "$", "cache", "->", "get", "(", "$", "entry", ")", ";", "if...
Get an entry from the first cache that can provide a value. @param string $entry The cache key. @return mixed The cached value, or FALSE if not found.
[ "Get", "an", "entry", "from", "the", "first", "cache", "that", "can", "provide", "a", "value", "." ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/TieredCache.php#L63-L74
train
Vectorface/cache
src/TieredCache.php
TieredCache.set
public function set($entry, $value, $ttl = false) { $setCallback = function ($setSuccess, $cache) use ($entry, $value, $ttl) { return $setSuccess || $cache->set($entry, $value, $ttl); }; return array_reduce($this->caches, $setCallback, false); }
php
public function set($entry, $value, $ttl = false) { $setCallback = function ($setSuccess, $cache) use ($entry, $value, $ttl) { return $setSuccess || $cache->set($entry, $value, $ttl); }; return array_reduce($this->caches, $setCallback, false); }
[ "public", "function", "set", "(", "$", "entry", ",", "$", "value", ",", "$", "ttl", "=", "false", ")", "{", "$", "setCallback", "=", "function", "(", "$", "setSuccess", ",", "$", "cache", ")", "use", "(", "$", "entry", ",", "$", "value", ",", "$"...
Set an entry in all caches in the stack. @param string $entry The cache key. @param mixed $value The value to be stored. @param int $ttl The time-to-live for the cache entry. @return bool Returns true if saving succeeded to any cache in the stack.
[ "Set", "an", "entry", "in", "all", "caches", "in", "the", "stack", "." ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/TieredCache.php#L84-L90
train
Vectorface/cache
src/TieredCache.php
TieredCache.clean
public function clean() { $cleanCallback = function ($allCleaned, $cache) { return $allCleaned && $cache->clean(); }; return array_reduce($this->caches, $cleanCallback, true); }
php
public function clean() { $cleanCallback = function ($allCleaned, $cache) { return $allCleaned && $cache->clean(); }; return array_reduce($this->caches, $cleanCallback, true); }
[ "public", "function", "clean", "(", ")", "{", "$", "cleanCallback", "=", "function", "(", "$", "allCleaned", ",", "$", "cache", ")", "{", "return", "$", "allCleaned", "&&", "$", "cache", "->", "clean", "(", ")", ";", "}", ";", "return", "array_reduce",...
Perform a clean operation on all caches. @return bool Returns true if clean succeeded on all caches in the stack.
[ "Perform", "a", "clean", "operation", "on", "all", "caches", "." ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/TieredCache.php#L111-L117
train
Vectorface/cache
src/TieredCache.php
TieredCache.flush
public function flush() { $flushCallback = function ($allFlushed, $cache) { return $allFlushed && $cache->flush(); }; return array_reduce($this->caches, $flushCallback, true); }
php
public function flush() { $flushCallback = function ($allFlushed, $cache) { return $allFlushed && $cache->flush(); }; return array_reduce($this->caches, $flushCallback, true); }
[ "public", "function", "flush", "(", ")", "{", "$", "flushCallback", "=", "function", "(", "$", "allFlushed", ",", "$", "cache", ")", "{", "return", "$", "allFlushed", "&&", "$", "cache", "->", "flush", "(", ")", ";", "}", ";", "return", "array_reduce",...
Perform a flush operation on all caches. @return bool Returns true if flush succeeded on all caches in the stack.
[ "Perform", "a", "flush", "operation", "on", "all", "caches", "." ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/TieredCache.php#L124-L130
train
flipboxfactory/craft-ember
src/objects/ElementMutatorTrait.php
ElementMutatorTrait.setElement
public function setElement($element = null) { $this->element = null; if (!$element = $this->internalResolveElement($element)) { $this->element = $this->elementId = null; } else { /** @var Element $element */ $this->elementId = $element->id; $this->element = $element; } return $this; }
php
public function setElement($element = null) { $this->element = null; if (!$element = $this->internalResolveElement($element)) { $this->element = $this->elementId = null; } else { /** @var Element $element */ $this->elementId = $element->id; $this->element = $element; } return $this; }
[ "public", "function", "setElement", "(", "$", "element", "=", "null", ")", "{", "$", "this", "->", "element", "=", "null", ";", "if", "(", "!", "$", "element", "=", "$", "this", "->", "internalResolveElement", "(", "$", "element", ")", ")", "{", "$",...
Associate a element @param mixed $element @return $this
[ "Associate", "a", "element" ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/objects/ElementMutatorTrait.php#L61-L74
train
arillo/silverstripe-elements
src/ElementsExtension.php
ElementsExtension.move_elements_manager
public static function move_elements_manager( FieldList $fields, string $relationName, string $newTabName = 'Root.Main', string $insertBefore = null ): FieldList { $itemsGf = $fields->dataFieldByName($relationName); $fields ->removeByName($relationName) ->addFieldToTab($newTabName, $itemsGf, $insertBefore) ; return $fields; }
php
public static function move_elements_manager( FieldList $fields, string $relationName, string $newTabName = 'Root.Main', string $insertBefore = null ): FieldList { $itemsGf = $fields->dataFieldByName($relationName); $fields ->removeByName($relationName) ->addFieldToTab($newTabName, $itemsGf, $insertBefore) ; return $fields; }
[ "public", "static", "function", "move_elements_manager", "(", "FieldList", "$", "fields", ",", "string", "$", "relationName", ",", "string", "$", "newTabName", "=", "'Root.Main'", ",", "string", "$", "insertBefore", "=", "null", ")", ":", "FieldList", "{", "$"...
Move an elements gridfield to an other tab. @param FieldList $fields @param string $relationName @param string $newTabName @param string $insertBefore optional: insert before an other field @return FieldList the altered fields
[ "Move", "an", "elements", "gridfield", "to", "an", "other", "tab", "." ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementsExtension.php#L86-L100
train
arillo/silverstripe-elements
src/ElementsExtension.php
ElementsExtension.create_default_elements
public static function create_default_elements(SiteTree $record): int { $count = 0; if (!$record || !$record->ID) { throw new SS_HTTPResponse_Exception("Bad record ID #" . (int)$data['ID'], 404); } if ($relationNames = ElementsExtension::page_element_relation_names($record)) { $defaultElements = $record->getDefaultElements(); if (count($relationNames) > 0) { foreach ($relationNames as $relationName => $elementsClasses) { if (isset($defaultElements[$relationName])) { $elementClasses = $defaultElements[$relationName]; foreach ($elementClasses as $className) { $definedElements = $record->ElementsByRelation($relationName)->map('ClassName', 'ClassName'); if (!isset($definedElements[$className])) { $element = new $className; $element->populate('PageID', $record->ID, $relationName); $element->write(); $count++; } } } } } } return $count; }
php
public static function create_default_elements(SiteTree $record): int { $count = 0; if (!$record || !$record->ID) { throw new SS_HTTPResponse_Exception("Bad record ID #" . (int)$data['ID'], 404); } if ($relationNames = ElementsExtension::page_element_relation_names($record)) { $defaultElements = $record->getDefaultElements(); if (count($relationNames) > 0) { foreach ($relationNames as $relationName => $elementsClasses) { if (isset($defaultElements[$relationName])) { $elementClasses = $defaultElements[$relationName]; foreach ($elementClasses as $className) { $definedElements = $record->ElementsByRelation($relationName)->map('ClassName', 'ClassName'); if (!isset($definedElements[$className])) { $element = new $className; $element->populate('PageID', $record->ID, $relationName); $element->write(); $count++; } } } } } } return $count; }
[ "public", "static", "function", "create_default_elements", "(", "SiteTree", "$", "record", ")", ":", "int", "{", "$", "count", "=", "0", ";", "if", "(", "!", "$", "record", "||", "!", "$", "record", "->", "ID", ")", "{", "throw", "new", "SS_HTTPRespons...
Create_default elements , if setup via config @see self::getDefaultElements(). @param SiteTree $record @return int
[ "Create_default", "elements", "if", "setup", "via", "config" ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementsExtension.php#L107-L141
train
arillo/silverstripe-elements
src/ElementsExtension.php
ElementsExtension.validate_class_inheritance
public static function validate_class_inheritance(array $relation): array { return array_filter($relation, function($className) { if ( ClassInfo::exists($className) && (is_a(singleton($className), ElementBase::class)) ) { return $className; } user_error('Your element needs to extend from ' . ElementBase::class, E_USER_WARNING); }); }
php
public static function validate_class_inheritance(array $relation): array { return array_filter($relation, function($className) { if ( ClassInfo::exists($className) && (is_a(singleton($className), ElementBase::class)) ) { return $className; } user_error('Your element needs to extend from ' . ElementBase::class, E_USER_WARNING); }); }
[ "public", "static", "function", "validate_class_inheritance", "(", "array", "$", "relation", ")", ":", "array", "{", "return", "array_filter", "(", "$", "relation", ",", "function", "(", "$", "className", ")", "{", "if", "(", "ClassInfo", "::", "exists", "("...
Check if all provied classes derive from ElementBase. @param array $relation @return array
[ "Check", "if", "all", "provied", "classes", "derive", "from", "ElementBase", "." ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementsExtension.php#L148-L160
train
arillo/silverstripe-elements
src/ElementsExtension.php
ElementsExtension.onAfterDelete
public function onAfterDelete() { $staged = Versioned::get_by_stage($this->owner->ClassName, Versioned::DRAFT) ->byID($this->owner->ID) ; $live = Versioned::get_by_stage($this->owner->ClassName, Versioned::LIVE) ->byID($this->owner->ID) ; if (!$staged && !$live) { foreach($this->owner->Elements() as $element) { $element->deleteFromStage(Versioned::LIVE); $element->deleteFromStage(Versioned::DRAFT); $element->delete(); } } parent::onAfterDelete(); }
php
public function onAfterDelete() { $staged = Versioned::get_by_stage($this->owner->ClassName, Versioned::DRAFT) ->byID($this->owner->ID) ; $live = Versioned::get_by_stage($this->owner->ClassName, Versioned::LIVE) ->byID($this->owner->ID) ; if (!$staged && !$live) { foreach($this->owner->Elements() as $element) { $element->deleteFromStage(Versioned::LIVE); $element->deleteFromStage(Versioned::DRAFT); $element->delete(); } } parent::onAfterDelete(); }
[ "public", "function", "onAfterDelete", "(", ")", "{", "$", "staged", "=", "Versioned", "::", "get_by_stage", "(", "$", "this", "->", "owner", "->", "ClassName", ",", "Versioned", "::", "DRAFT", ")", "->", "byID", "(", "$", "this", "->", "owner", "->", ...
Remove all related elements
[ "Remove", "all", "related", "elements" ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementsExtension.php#L273-L293
train
arillo/silverstripe-elements
src/ElementsExtension.php
ElementsExtension.ElementsByRelation
public function ElementsByRelation(string $relationName) { $filter = [ 'RelationName' => $relationName ]; if ( $this->owner->hasExtension(ElementBase::FLUENT_CLASS) && !is_a(Controller::curr(), LeftAndMain::class) ) { $filter['Visible'] = true; } return $this->owner ->Elements() ->filter($filter) ; }
php
public function ElementsByRelation(string $relationName) { $filter = [ 'RelationName' => $relationName ]; if ( $this->owner->hasExtension(ElementBase::FLUENT_CLASS) && !is_a(Controller::curr(), LeftAndMain::class) ) { $filter['Visible'] = true; } return $this->owner ->Elements() ->filter($filter) ; }
[ "public", "function", "ElementsByRelation", "(", "string", "$", "relationName", ")", "{", "$", "filter", "=", "[", "'RelationName'", "=>", "$", "relationName", "]", ";", "if", "(", "$", "this", "->", "owner", "->", "hasExtension", "(", "ElementBase", "::", ...
Getter for items by relation name @param string $relationName @return DataList
[ "Getter", "for", "items", "by", "relation", "name" ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementsExtension.php#L324-L338
train
arillo/silverstripe-elements
src/ElementsExtension.php
ElementsExtension.gridFieldForElementRelation
public function gridFieldForElementRelation( FieldList $fields, $relationName, $relation ) { // sort relations asort($relation); $config = GridFieldConfig_RelationEditor::create() ->removeComponentsByType(GridFieldDeleteAction::class) ->removeComponentsByType(GridFieldAddExistingAutocompleter::class) ->addComponent(new GridFieldOrderableRows('Sort')) ->addComponent(new GridFieldDeleteAction()) ; // attach default elements action if ( $this->owner->canEdit() && !$this->defaultsCreated() && $this->owner->getDefaultElements() && isset($this->owner->getDefaultElements()[$relationName]) ) { $config->addComponent(new GridFieldDefaultElementsButton()); } if (count($relation) > 1) { $config ->removeComponentsByType(GridFieldAddNewButton::class) ->addComponent($multiClass = new GridFieldAddNewMultiClass()) ; $multiClass->setClasses(ElementsExtension::map_classnames($relation)); } $config ->getComponentByType(GridFieldPaginator::class) ->setItemsPerPage(150) ; $columns = [ 'CMSTypeInfo' => _t(__CLASS__ . '.CMSTypeInfo', 'Type'), 'CMSSummary' => _t(__CLASS__ . '.CMSSummary', 'Summary'), ]; if ($this->owner->hasExtension(ElementBase::FLUENT_CLASS)) { $columns['Languages'] = _t(__CLASS__ . '.Languages', 'Lang'); } if (count($relation) == 1 && $summaryFields = singleton($relation[0])->summaryFields() ) { $columns = array_merge($columns, $summaryFields); } $config ->getComponentByType(GridFieldDataColumns::class) ->setDisplayFields($columns) ; $tabName = "Root.{$relationName}"; // if only one relation is set, add gridfield to main tab if (count($this->elementRelations) == 1) $tabName = "Root.Main"; $label = _t("Element_Relations.{$relationName}", $relationName); $config ->getComponentByType(GridFieldDetailForm::class) ->setItemRequestClass(VersionedElement_ItemRequest::class) ; $fields->addFieldToTab( $tabName, $gridField = GridField::create( $relationName, $label, $this->owner->ElementsByRelation($relationName), $config ) ); $gridField->addExtraClass('elements-gridfield'); if (count($relation) == 1) $gridField->setModelClass($relation[0]); if (count($this->elementRelations) > 1) { $fields ->findOrMakeTab($tabName) ->setTitle($label) ; } return $this->owner; }
php
public function gridFieldForElementRelation( FieldList $fields, $relationName, $relation ) { // sort relations asort($relation); $config = GridFieldConfig_RelationEditor::create() ->removeComponentsByType(GridFieldDeleteAction::class) ->removeComponentsByType(GridFieldAddExistingAutocompleter::class) ->addComponent(new GridFieldOrderableRows('Sort')) ->addComponent(new GridFieldDeleteAction()) ; // attach default elements action if ( $this->owner->canEdit() && !$this->defaultsCreated() && $this->owner->getDefaultElements() && isset($this->owner->getDefaultElements()[$relationName]) ) { $config->addComponent(new GridFieldDefaultElementsButton()); } if (count($relation) > 1) { $config ->removeComponentsByType(GridFieldAddNewButton::class) ->addComponent($multiClass = new GridFieldAddNewMultiClass()) ; $multiClass->setClasses(ElementsExtension::map_classnames($relation)); } $config ->getComponentByType(GridFieldPaginator::class) ->setItemsPerPage(150) ; $columns = [ 'CMSTypeInfo' => _t(__CLASS__ . '.CMSTypeInfo', 'Type'), 'CMSSummary' => _t(__CLASS__ . '.CMSSummary', 'Summary'), ]; if ($this->owner->hasExtension(ElementBase::FLUENT_CLASS)) { $columns['Languages'] = _t(__CLASS__ . '.Languages', 'Lang'); } if (count($relation) == 1 && $summaryFields = singleton($relation[0])->summaryFields() ) { $columns = array_merge($columns, $summaryFields); } $config ->getComponentByType(GridFieldDataColumns::class) ->setDisplayFields($columns) ; $tabName = "Root.{$relationName}"; // if only one relation is set, add gridfield to main tab if (count($this->elementRelations) == 1) $tabName = "Root.Main"; $label = _t("Element_Relations.{$relationName}", $relationName); $config ->getComponentByType(GridFieldDetailForm::class) ->setItemRequestClass(VersionedElement_ItemRequest::class) ; $fields->addFieldToTab( $tabName, $gridField = GridField::create( $relationName, $label, $this->owner->ElementsByRelation($relationName), $config ) ); $gridField->addExtraClass('elements-gridfield'); if (count($relation) == 1) $gridField->setModelClass($relation[0]); if (count($this->elementRelations) > 1) { $fields ->findOrMakeTab($tabName) ->setTitle($label) ; } return $this->owner; }
[ "public", "function", "gridFieldForElementRelation", "(", "FieldList", "$", "fields", ",", "$", "relationName", ",", "$", "relation", ")", "{", "// sort relations", "asort", "(", "$", "relation", ")", ";", "$", "config", "=", "GridFieldConfig_RelationEditor", "::"...
Adds a GridField for a elements relation @param FieldList $fields @param string $relationName @return DataObject
[ "Adds", "a", "GridField", "for", "a", "elements", "relation" ]
faa95a6487efe6e28101db5319529aa7e575fa90
https://github.com/arillo/silverstripe-elements/blob/faa95a6487efe6e28101db5319529aa7e575fa90/src/ElementsExtension.php#L347-L443
train
jmikola/WildcardEventDispatcher
src/Jmikola/WildcardEventDispatcher/LazyListenerPattern.php
LazyListenerPattern.getListener
public function getListener() { if (!isset($this->listener) && isset($this->listenerProvider)) { $this->listener = call_user_func($this->listenerProvider); unset($this->listenerProvider); } return $this->listener; }
php
public function getListener() { if (!isset($this->listener) && isset($this->listenerProvider)) { $this->listener = call_user_func($this->listenerProvider); unset($this->listenerProvider); } return $this->listener; }
[ "public", "function", "getListener", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "listener", ")", "&&", "isset", "(", "$", "this", "->", "listenerProvider", ")", ")", "{", "$", "this", "->", "listener", "=", "call_user_func", "(", ...
Get the pattern listener, initializing it lazily from its provider. @return callback
[ "Get", "the", "pattern", "listener", "initializing", "it", "lazily", "from", "its", "provider", "." ]
cc3257181cfc25a025b049348c5f9053e83ec627
https://github.com/jmikola/WildcardEventDispatcher/blob/cc3257181cfc25a025b049348c5f9053e83ec627/src/Jmikola/WildcardEventDispatcher/LazyListenerPattern.php#L36-L44
train
JanDC/css-from-html-extractor
src/Css/Processor.php
Processor.getCssFromStyleTags
public function getCssFromStyleTags($html) { $css = ''; $matches = array(); preg_match_all('|<style(?:\s.*)?>(.*)</style>|isU', $html, $matches); if (!empty($matches[1])) { foreach ($matches[1] as $match) { $css .= trim($match) . "\n"; } } return $css; }
php
public function getCssFromStyleTags($html) { $css = ''; $matches = array(); preg_match_all('|<style(?:\s.*)?>(.*)</style>|isU', $html, $matches); if (!empty($matches[1])) { foreach ($matches[1] as $match) { $css .= trim($match) . "\n"; } } return $css; }
[ "public", "function", "getCssFromStyleTags", "(", "$", "html", ")", "{", "$", "css", "=", "''", ";", "$", "matches", "=", "array", "(", ")", ";", "preg_match_all", "(", "'|<style(?:\\s.*)?>(.*)</style>|isU'", ",", "$", "html", ",", "$", "matches", ")", ";"...
Get the CSS from the style-tags in the given HTML-string @param string $html @return string
[ "Get", "the", "CSS", "from", "the", "style", "-", "tags", "in", "the", "given", "HTML", "-", "string" ]
e471a1e9ea00f800cb20e014079050cb2d9ad57c
https://github.com/JanDC/css-from-html-extractor/blob/e471a1e9ea00f800cb20e014079050cb2d9ad57c/src/Css/Processor.php#L43-L56
train
Vectorface/cache
src/PHPCache.php
PHPCache.get
public function get($key) { if (isset($this->cache[$key])) { list($expires, $value) = $this->cache[$key]; if (!$expires || ($expires >= microtime(true))) { return $value; } unset($this->cache[$key]); } return false; }
php
public function get($key) { if (isset($this->cache[$key])) { list($expires, $value) = $this->cache[$key]; if (!$expires || ($expires >= microtime(true))) { return $value; } unset($this->cache[$key]); } return false; }
[ "public", "function", "get", "(", "$", "key", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "cache", "[", "$", "key", "]", ")", ")", "{", "list", "(", "$", "expires", ",", "$", "value", ")", "=", "$", "this", "->", "cache", "[", "$", ...
Fetch a cache entry by key. @param String $key The key for the entry to fetch @return mixed The value stored in the cache for $key
[ "Fetch", "a", "cache", "entry", "by", "key", "." ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/PHPCache.php#L30-L40
train
czim/laravel-processor
src/AbstractProcessor.php
AbstractProcessor.process
public function process(DataObjectInterface $data = null) { if ( ! is_null($data)) { $this->data = $data; } $this->before(); $this->doProcessing(); $this->after(); return $this->getResult(); }
php
public function process(DataObjectInterface $data = null) { if ( ! is_null($data)) { $this->data = $data; } $this->before(); $this->doProcessing(); $this->after(); return $this->getResult(); }
[ "public", "function", "process", "(", "DataObjectInterface", "$", "data", "=", "null", ")", "{", "if", "(", "!", "is_null", "(", "$", "data", ")", ")", "{", "$", "this", "->", "data", "=", "$", "data", ";", "}", "$", "this", "->", "before", "(", ...
Process the data sent @param DataObjectInterface $data @return ProcessorResult
[ "Process", "the", "data", "sent" ]
3d0025cd463653b7a8981ff52cebdafbe978f000
https://github.com/czim/laravel-processor/blob/3d0025cd463653b7a8981ff52cebdafbe978f000/src/AbstractProcessor.php#L62-L75
train
czim/laravel-processor
src/AbstractProcessor.php
AbstractProcessor.setExtraData
public function setExtraData($data) { if (is_a($data, Arrayable::class)) { $data = $data->toArray(); } if ( ! is_array($data)) { $data = [ $data ]; } $this->extraData = $data; return $this; }
php
public function setExtraData($data) { if (is_a($data, Arrayable::class)) { $data = $data->toArray(); } if ( ! is_array($data)) { $data = [ $data ]; } $this->extraData = $data; return $this; }
[ "public", "function", "setExtraData", "(", "$", "data", ")", "{", "if", "(", "is_a", "(", "$", "data", ",", "Arrayable", "::", "class", ")", ")", "{", "$", "data", "=", "$", "data", "->", "toArray", "(", ")", ";", "}", "if", "(", "!", "is_array",...
Set extra data that the processor should use during the import @param array|Arrayable $data @return $this
[ "Set", "extra", "data", "that", "the", "processor", "should", "use", "during", "the", "import" ]
3d0025cd463653b7a8981ff52cebdafbe978f000
https://github.com/czim/laravel-processor/blob/3d0025cd463653b7a8981ff52cebdafbe978f000/src/AbstractProcessor.php#L84-L97
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Textpattern/Validate.php
Validate.isValidConfig
public function isValidConfig() { $missing = []; foreach ($this->required as $required) { if (!array_key_exists($required, $this->txpcfg)) { $missing[] = $required; } } if ($missing) { throw new \InvalidArgumentException( 'Textpattern installation missing config values: '.implode(', ', $missing) ); } }
php
public function isValidConfig() { $missing = []; foreach ($this->required as $required) { if (!array_key_exists($required, $this->txpcfg)) { $missing[] = $required; } } if ($missing) { throw new \InvalidArgumentException( 'Textpattern installation missing config values: '.implode(', ', $missing) ); } }
[ "public", "function", "isValidConfig", "(", ")", "{", "$", "missing", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "required", "as", "$", "required", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "required", ",", "$", "this", "->"...
Checks that the config contains all needed options. @throws \InvalidArgumentException
[ "Checks", "that", "the", "config", "contains", "all", "needed", "options", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Textpattern/Validate.php#L72-L87
train
gocom/textpattern-installer
src/Textpattern/Composer/Installer/Textpattern/Validate.php
Validate.hasDatabase
public function hasDatabase() { try { $pdo = new \PDO( 'mysql:host='.$this->txpcfg['host'].';dbname='.$this->txpcfg['db'], $this->txpcfg['user'], $this->txpcfg['pass'] ); } catch (\PDOException $e) { $pdo = false; } if ($pdo === false) { throw new \InvalidArgumentException( 'Unable connect to Textpattern database: '.$this->txpcfg['db'].'@'.$this->txpcfg['host'] ); } if (!$pdo->prepare('SHOW TABLES LIKE ?')->execute(array($this->txpcfg['table_prefix'] . 'textpattern'))) { throw new \InvalidArgumentException('Textpattern is not installed'); } }
php
public function hasDatabase() { try { $pdo = new \PDO( 'mysql:host='.$this->txpcfg['host'].';dbname='.$this->txpcfg['db'], $this->txpcfg['user'], $this->txpcfg['pass'] ); } catch (\PDOException $e) { $pdo = false; } if ($pdo === false) { throw new \InvalidArgumentException( 'Unable connect to Textpattern database: '.$this->txpcfg['db'].'@'.$this->txpcfg['host'] ); } if (!$pdo->prepare('SHOW TABLES LIKE ?')->execute(array($this->txpcfg['table_prefix'] . 'textpattern'))) { throw new \InvalidArgumentException('Textpattern is not installed'); } }
[ "public", "function", "hasDatabase", "(", ")", "{", "try", "{", "$", "pdo", "=", "new", "\\", "PDO", "(", "'mysql:host='", ".", "$", "this", "->", "txpcfg", "[", "'host'", "]", ".", "';dbname='", ".", "$", "this", "->", "txpcfg", "[", "'db'", "]", ...
Checks if the database exists. @throws \InvalidArgumentException
[ "Checks", "if", "the", "database", "exists", "." ]
804271de54177ebd294a4a19d409ae7fc2317935
https://github.com/gocom/textpattern-installer/blob/804271de54177ebd294a4a19d409ae7fc2317935/src/Textpattern/Composer/Installer/Textpattern/Validate.php#L94-L115
train
Vectorface/cache
src/MCCache.php
MCCache.set
public function set($key, $value, $ttl = false) { return $this->mc->set($key, $value, null, (int)$ttl); }
php
public function set($key, $value, $ttl = false) { return $this->mc->set($key, $value, null, (int)$ttl); }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", ",", "$", "ttl", "=", "false", ")", "{", "return", "$", "this", "->", "mc", "->", "set", "(", "$", "key", ",", "$", "value", ",", "null", ",", "(", "int", ")", "$", "ttl", ")", ...
Place an item into the cache @param string $key The cache key. @param mixed $value The value to be stored. (Warning: Caches cannot store items of type resource.) @param int $ttl The time to live, in seconds. The time before the object should expire. @return bool True if successful, false otherwise.
[ "Place", "an", "item", "into", "the", "cache" ]
159f4aeaf639da7a1f7e1d4e5e719a279442658b
https://github.com/Vectorface/cache/blob/159f4aeaf639da7a1f7e1d4e5e719a279442658b/src/MCCache.php#L64-L67
train
flipboxfactory/craft-ember
src/queries/ActiveQuery.php
ActiveQuery.requireAll
public function requireAll($db = null) { $records = $this->all($db); if (empty($records)) { throw new RecordNotFoundException( sprintf( "Records not found." ) ); } return $records; }
php
public function requireAll($db = null) { $records = $this->all($db); if (empty($records)) { throw new RecordNotFoundException( sprintf( "Records not found." ) ); } return $records; }
[ "public", "function", "requireAll", "(", "$", "db", "=", "null", ")", "{", "$", "records", "=", "$", "this", "->", "all", "(", "$", "db", ")", ";", "if", "(", "empty", "(", "$", "records", ")", ")", "{", "throw", "new", "RecordNotFoundException", "...
Executes query and returns all results as an array. If results are not found, an exception is thrown as we explicitly expect results. @param Connection $db the DB connection used to create the DB command. If null, the DB connection returned by [[modelClass]] will be used. @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned. @throws RecordNotFoundException
[ "Executes", "query", "and", "returns", "all", "results", "as", "an", "array", ".", "If", "results", "are", "not", "found", "an", "exception", "is", "thrown", "as", "we", "explicitly", "expect", "results", "." ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/queries/ActiveQuery.php#L57-L70
train
flipboxfactory/craft-ember
src/queries/ActiveQuery.php
ActiveQuery.requireOne
public function requireOne($db = null) { if (null === ($record = $this->one($db))) { throw new RecordNotFoundException( sprintf( "Record not found." ) ); } return $record; }
php
public function requireOne($db = null) { if (null === ($record = $this->one($db))) { throw new RecordNotFoundException( sprintf( "Record not found." ) ); } return $record; }
[ "public", "function", "requireOne", "(", "$", "db", "=", "null", ")", "{", "if", "(", "null", "===", "(", "$", "record", "=", "$", "this", "->", "one", "(", "$", "db", ")", ")", ")", "{", "throw", "new", "RecordNotFoundException", "(", "sprintf", "...
Executes query and returns a single result. If a result is not found, an exception is thrown as we explicitly expect a result. @param Connection|null $db the DB connection used to create the DB command. If `null`, the DB connection returned by [[modelClass]] will be used. @return ActiveRecord|array a single row of query result. Depending on the setting of [[asArray]], the query result may be either an array or an ActiveRecord object. `null` will be returned if the query results in nothing. @throws RecordNotFoundException
[ "Executes", "query", "and", "returns", "a", "single", "result", ".", "If", "a", "result", "is", "not", "found", "an", "exception", "is", "thrown", "as", "we", "explicitly", "expect", "a", "result", "." ]
9185b885b404b1cb272a0983023eb7c6c0df61c8
https://github.com/flipboxfactory/craft-ember/blob/9185b885b404b1cb272a0983023eb7c6c0df61c8/src/queries/ActiveQuery.php#L83-L94
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.getOne
public function getOne($hail_object) { $uri = $hail_object::$object_endpoint . '/' . $hail_object->HailID; return $this->get($uri); }
php
public function getOne($hail_object) { $uri = $hail_object::$object_endpoint . '/' . $hail_object->HailID; return $this->get($uri); }
[ "public", "function", "getOne", "(", "$", "hail_object", ")", "{", "$", "uri", "=", "$", "hail_object", "::", "$", "object_endpoint", ".", "'/'", ".", "$", "hail_object", "->", "HailID", ";", "return", "$", "this", "->", "get", "(", "$", "uri", ")", ...
Get one Hail object from the API @param mixed $hail_object Object to retrieve @return array Reply from Hail @throws
[ "Get", "one", "Hail", "object", "from", "the", "API" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L110-L115
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.fetchAccessToken
public function fetchAccessToken($redirect_code) { $http = $this->getHTTPClient(); $post_data = [ 'client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'grant_type' => 'authorization_code', 'code' => $redirect_code, 'redirect_uri' => $this->getRedirectURL(), ]; // Request access token try { $response = $http->request('POST', 'oauth/access_token', [ 'form_params' => $post_data ]); $responseBody = $response->getBody(); $responseArr = json_decode($responseBody, true); //Set new data into the config and update the current instance $this->setAccessToken($responseArr['access_token']); $this->setAccessTokenExpire($responseArr['expires_in']); $this->setRefreshToken($responseArr['refresh_token']); } catch (\Exception $exception) { $this->handleException($exception); } }
php
public function fetchAccessToken($redirect_code) { $http = $this->getHTTPClient(); $post_data = [ 'client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'grant_type' => 'authorization_code', 'code' => $redirect_code, 'redirect_uri' => $this->getRedirectURL(), ]; // Request access token try { $response = $http->request('POST', 'oauth/access_token', [ 'form_params' => $post_data ]); $responseBody = $response->getBody(); $responseArr = json_decode($responseBody, true); //Set new data into the config and update the current instance $this->setAccessToken($responseArr['access_token']); $this->setAccessTokenExpire($responseArr['expires_in']); $this->setRefreshToken($responseArr['refresh_token']); } catch (\Exception $exception) { $this->handleException($exception); } }
[ "public", "function", "fetchAccessToken", "(", "$", "redirect_code", ")", "{", "$", "http", "=", "$", "this", "->", "getHTTPClient", "(", ")", ";", "$", "post_data", "=", "[", "'client_id'", "=>", "$", "this", "->", "client_id", ",", "'client_secret'", "=>...
Fetch OAuth Access token from the HAil API @param string $redirect_code @throws
[ "Fetch", "OAuth", "Access", "token", "from", "the", "HAil", "API" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L124-L150
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.setAccessTokenExpire
public function setAccessTokenExpire($access_token_expire) { //Store expiry date as unix timestamp (now + expires in) $access_token_expire = time() + $access_token_expire; $this->access_token_expire = $access_token_expire; $config = SiteConfig::current_site_config(); $config->HailAccessTokenExpire = $access_token_expire; $config->write(); }
php
public function setAccessTokenExpire($access_token_expire) { //Store expiry date as unix timestamp (now + expires in) $access_token_expire = time() + $access_token_expire; $this->access_token_expire = $access_token_expire; $config = SiteConfig::current_site_config(); $config->HailAccessTokenExpire = $access_token_expire; $config->write(); }
[ "public", "function", "setAccessTokenExpire", "(", "$", "access_token_expire", ")", "{", "//Store expiry date as unix timestamp (now + expires in)\r", "$", "access_token_expire", "=", "time", "(", ")", "+", "$", "access_token_expire", ";", "$", "this", "->", "access_token...
Set Hail API OAuth access token expiry time in current SiteConfig @param string $access_token_expire @throws
[ "Set", "Hail", "API", "OAuth", "access", "token", "expiry", "time", "in", "current", "SiteConfig" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L188-L196
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.setRefreshToken
public function setRefreshToken($refresh_token) { $config = SiteConfig::current_site_config(); $config->HailRefreshToken = $refresh_token; $this->refresh_token = $refresh_token; $config->write(); }
php
public function setRefreshToken($refresh_token) { $config = SiteConfig::current_site_config(); $config->HailRefreshToken = $refresh_token; $this->refresh_token = $refresh_token; $config->write(); }
[ "public", "function", "setRefreshToken", "(", "$", "refresh_token", ")", "{", "$", "config", "=", "SiteConfig", "::", "current_site_config", "(", ")", ";", "$", "config", "->", "HailRefreshToken", "=", "$", "refresh_token", ";", "$", "this", "->", "refresh_tok...
Set Hail API OAuth refresh token in current SiteConfig @param string $refresh_token @throws
[ "Set", "Hail", "API", "OAuth", "refresh", "token", "in", "current", "SiteConfig" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L203-L209
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.handleException
public function handleException($exception) { //Log the error Injector::inst()->get(LoggerInterface::class)->debug($exception->getMessage()); $request = Injector::inst()->get(HTTPRequest::class); $request->getSession()->set('notice', true); $request->getSession()->set('noticeType', 'bad'); $message = $exception->getMessage(); if ($exception->hasResponse()) { $response = json_decode($exception->getResponse()->getBody(), true); if (isset($response['error']) && isset($response['error']['message'])) { $message = $response['error']['message']; } } $request->getSession()->set('noticeText', $message); }
php
public function handleException($exception) { //Log the error Injector::inst()->get(LoggerInterface::class)->debug($exception->getMessage()); $request = Injector::inst()->get(HTTPRequest::class); $request->getSession()->set('notice', true); $request->getSession()->set('noticeType', 'bad'); $message = $exception->getMessage(); if ($exception->hasResponse()) { $response = json_decode($exception->getResponse()->getBody(), true); if (isset($response['error']) && isset($response['error']['message'])) { $message = $response['error']['message']; } } $request->getSession()->set('noticeText', $message); }
[ "public", "function", "handleException", "(", "$", "exception", ")", "{", "//Log the error\r", "Injector", "::", "inst", "(", ")", "->", "get", "(", "LoggerInterface", "::", "class", ")", "->", "debug", "(", "$", "exception", "->", "getMessage", "(", ")", ...
Silently handle Hail API HTTP Exception to avoid CMS crashes Stores error message in a session variable for CMS display @param \Exception $exception
[ "Silently", "handle", "Hail", "API", "HTTP", "Exception", "to", "avoid", "CMS", "crashes", "Stores", "error", "message", "in", "a", "session", "variable", "for", "CMS", "display" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L217-L232
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.getAuthorizationURL
public function getAuthorizationURL() { $url = Config::inst()->get(self::class, 'AuthorizationUrl'); $params = [ 'client_id' => $this->client_id, 'redirect_uri' => $this->getRedirectURL(), 'response_type' => "code", 'scope' => $this->scopes, ]; return $url . "?" . http_build_query($params); }
php
public function getAuthorizationURL() { $url = Config::inst()->get(self::class, 'AuthorizationUrl'); $params = [ 'client_id' => $this->client_id, 'redirect_uri' => $this->getRedirectURL(), 'response_type' => "code", 'scope' => $this->scopes, ]; return $url . "?" . http_build_query($params); }
[ "public", "function", "getAuthorizationURL", "(", ")", "{", "$", "url", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "self", "::", "class", ",", "'AuthorizationUrl'", ")", ";", "$", "params", "=", "[", "'client_id'", "=>", "$", "this", "->"...
Build Hail API Authorization URL @return string
[ "Build", "Hail", "API", "Authorization", "URL" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L239-L250
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.setUserID
public function setUserID() { $response = $this->get("me"); $config = SiteConfig::current_site_config(); $config->HailUserID = $response['id']; $this->user_id = $response['id']; $config->write(); }
php
public function setUserID() { $response = $this->get("me"); $config = SiteConfig::current_site_config(); $config->HailUserID = $response['id']; $this->user_id = $response['id']; $config->write(); }
[ "public", "function", "setUserID", "(", ")", "{", "$", "response", "=", "$", "this", "->", "get", "(", "\"me\"", ")", ";", "$", "config", "=", "SiteConfig", "::", "current_site_config", "(", ")", ";", "$", "config", "->", "HailUserID", "=", "$", "respo...
Get Hail User ID from the API and set it in the current SiteConfig @throws
[ "Get", "Hail", "User", "ID", "from", "the", "API", "and", "set", "it", "in", "the", "current", "SiteConfig" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L257-L264
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.getAccessToken
public function getAccessToken() { //Check if AccessToken needs to be refreshed $now = time(); $time = time(); $difference = $this->access_token_expire - $time; if ($difference < strtotime('15 minutes', 0)) { $this->refreshAccessToken(); } return $this->access_token; }
php
public function getAccessToken() { //Check if AccessToken needs to be refreshed $now = time(); $time = time(); $difference = $this->access_token_expire - $time; if ($difference < strtotime('15 minutes', 0)) { $this->refreshAccessToken(); } return $this->access_token; }
[ "public", "function", "getAccessToken", "(", ")", "{", "//Check if AccessToken needs to be refreshed\r", "$", "now", "=", "time", "(", ")", ";", "$", "time", "=", "time", "(", ")", ";", "$", "difference", "=", "$", "this", "->", "access_token_expire", "-", "...
Get current Hail API OAuth Access token Will refresh the token from the API if it has expired @return string
[ "Get", "current", "Hail", "API", "OAuth", "Access", "token", "Will", "refresh", "the", "token", "from", "the", "API", "if", "it", "has", "expired" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L272-L283
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.setAccessToken
public function setAccessToken($access_token) { $this->access_token = $access_token; $config = SiteConfig::current_site_config(); $config->HailAccessToken = $access_token; $config->write(); }
php
public function setAccessToken($access_token) { $this->access_token = $access_token; $config = SiteConfig::current_site_config(); $config->HailAccessToken = $access_token; $config->write(); }
[ "public", "function", "setAccessToken", "(", "$", "access_token", ")", "{", "$", "this", "->", "access_token", "=", "$", "access_token", ";", "$", "config", "=", "SiteConfig", "::", "current_site_config", "(", ")", ";", "$", "config", "->", "HailAccessToken", ...
Set Hail API OAuth token in the current SiteConfig @throws
[ "Set", "Hail", "API", "OAuth", "token", "in", "the", "current", "SiteConfig" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L290-L296
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.refreshAccessToken
public function refreshAccessToken() { $http = $this->getHTTPClient(); $post_data = [ 'client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'grant_type' => 'refresh_token', 'refresh_token' => $this->refresh_token, ]; // Refresh access token try { $response = $http->request('POST', 'oauth/access_token', [ 'form_params' => $post_data ]); $responseBody = $response->getBody(); $responseArr = json_decode($responseBody, true); //Set new data into the config and update the current instance $this->setAccessToken($responseArr['access_token']); $this->setAccessTokenExpire($responseArr['expires_in']); $this->setRefreshToken($responseArr['refresh_token']); } catch (\Exception $exception) { $this->handleException($exception); } }
php
public function refreshAccessToken() { $http = $this->getHTTPClient(); $post_data = [ 'client_id' => $this->client_id, 'client_secret' => $this->client_secret, 'grant_type' => 'refresh_token', 'refresh_token' => $this->refresh_token, ]; // Refresh access token try { $response = $http->request('POST', 'oauth/access_token', [ 'form_params' => $post_data ]); $responseBody = $response->getBody(); $responseArr = json_decode($responseBody, true); //Set new data into the config and update the current instance $this->setAccessToken($responseArr['access_token']); $this->setAccessTokenExpire($responseArr['expires_in']); $this->setRefreshToken($responseArr['refresh_token']); } catch (\Exception $exception) { $this->handleException($exception); } }
[ "public", "function", "refreshAccessToken", "(", ")", "{", "$", "http", "=", "$", "this", "->", "getHTTPClient", "(", ")", ";", "$", "post_data", "=", "[", "'client_id'", "=>", "$", "this", "->", "client_id", ",", "'client_secret'", "=>", "$", "this", "-...
Refresh Hail API OAuth Access token from the API @throws
[ "Refresh", "Hail", "API", "OAuth", "Access", "token", "from", "the", "API" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L303-L329
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.getAvailableOrganisations
public function getAvailableOrganisations($as_simple_array = false) { $organisations = $this->get('users/' . $this->user_id . '/organisations'); //If simple array is true, we send back an array with [id] => [name] instead of the full list if ($as_simple_array) { $temp = []; foreach ($organisations as $org) { $temp[$org['id']] = $org['name']; } $organisations = $temp; } asort($organisations); return $organisations; }
php
public function getAvailableOrganisations($as_simple_array = false) { $organisations = $this->get('users/' . $this->user_id . '/organisations'); //If simple array is true, we send back an array with [id] => [name] instead of the full list if ($as_simple_array) { $temp = []; foreach ($organisations as $org) { $temp[$org['id']] = $org['name']; } $organisations = $temp; } asort($organisations); return $organisations; }
[ "public", "function", "getAvailableOrganisations", "(", "$", "as_simple_array", "=", "false", ")", "{", "$", "organisations", "=", "$", "this", "->", "get", "(", "'users/'", ".", "$", "this", "->", "user_id", ".", "'/organisations'", ")", ";", "//If simple arr...
Get all available Hail Organisation the configured client has access to @param boolean $as_simple_array Return a simple associative array (ID => Tile )instead of the full objects @return array @throws
[ "Get", "all", "available", "Hail", "Organisation", "the", "configured", "client", "has", "access", "to" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L359-L373
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.getAvailablePrivateTags
public function getAvailablePrivateTags($organisations = null, $as_simple_array = false) { $orgs_ids = $organisations ? array_keys($organisations) : json_decode($this->orgs_ids); if (!$orgs_ids) { //No organisations configured $this->handleException(new \Exception("You need at least 1 Hail Organisation configured to be able to fetch private tags")); return false; } $tag_list = []; foreach ($orgs_ids as $org_id) { //Get Org Name if ($organisations) { $org_name = isset($organisations[$org_id]) ? $organisations[$org_id] : ''; } else { $org = DataObject::get_one(Organisation::class, ['HailID' => $org_id]); $org_name = $org ? $org->Title : ""; } $results = $this->get('organisations/' . $org_id . '/private-tags'); //If simple array is true, we send back an array with [id] => [name] instead of the full list if ($as_simple_array) { foreach ($results as $result) { $tag_title = $result['name']; //Add organisation name on tag title if more than 1 org if (count($orgs_ids) > 1) { $tag_title = $org_name . " - " . $tag_title; } $tag_list[$result['id']] = $tag_title; } } else { $tag_list = array_merge($results, $tag_list); } } asort($tag_list); return $tag_list; }
php
public function getAvailablePrivateTags($organisations = null, $as_simple_array = false) { $orgs_ids = $organisations ? array_keys($organisations) : json_decode($this->orgs_ids); if (!$orgs_ids) { //No organisations configured $this->handleException(new \Exception("You need at least 1 Hail Organisation configured to be able to fetch private tags")); return false; } $tag_list = []; foreach ($orgs_ids as $org_id) { //Get Org Name if ($organisations) { $org_name = isset($organisations[$org_id]) ? $organisations[$org_id] : ''; } else { $org = DataObject::get_one(Organisation::class, ['HailID' => $org_id]); $org_name = $org ? $org->Title : ""; } $results = $this->get('organisations/' . $org_id . '/private-tags'); //If simple array is true, we send back an array with [id] => [name] instead of the full list if ($as_simple_array) { foreach ($results as $result) { $tag_title = $result['name']; //Add organisation name on tag title if more than 1 org if (count($orgs_ids) > 1) { $tag_title = $org_name . " - " . $tag_title; } $tag_list[$result['id']] = $tag_title; } } else { $tag_list = array_merge($results, $tag_list); } } asort($tag_list); return $tag_list; }
[ "public", "function", "getAvailablePrivateTags", "(", "$", "organisations", "=", "null", ",", "$", "as_simple_array", "=", "false", ")", "{", "$", "orgs_ids", "=", "$", "organisations", "?", "array_keys", "(", "$", "organisations", ")", ":", "json_decode", "("...
Get all available Private Tags from the Hail API Will get all tags from all configured organisations unless specified otherwise @param array|null $organisations Pass an array of organisations (HailID => Organisation Name) to get the tag for, if null will get all configured organisation @param boolean $as_simple_array Return a simple associative array (ID => Tile )instead of the full objects @return array|boolean @throws
[ "Get", "all", "available", "Private", "Tags", "from", "the", "Hail", "API", "Will", "get", "all", "tags", "from", "all", "configured", "organisations", "unless", "specified", "otherwise" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L385-L421
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.getImagesByArticles
public function getImagesByArticles($id) { $uri = Article::$object_endpoint . '/' . $id . '/' . Image::$object_endpoint; return $this->get($uri); }
php
public function getImagesByArticles($id) { $uri = Article::$object_endpoint . '/' . $id . '/' . Image::$object_endpoint; return $this->get($uri); }
[ "public", "function", "getImagesByArticles", "(", "$", "id", ")", "{", "$", "uri", "=", "Article", "::", "$", "object_endpoint", ".", "'/'", ".", "$", "id", ".", "'/'", ".", "Image", "::", "$", "object_endpoint", ";", "return", "$", "this", "->", "get"...
Retrieve a list of images for a given article. @param string $id ID of the article in Hail @return array @throws
[ "Retrieve", "a", "list", "of", "images", "for", "a", "given", "article", "." ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L491-L495
train
firebrandhq/silverstripe-hail
src/Api/Client.php
Client.getVideosByArticles
public function getVideosByArticles($id) { $uri = Article::$object_endpoint . '/' . $id . '/' . Video::$object_endpoint; return $this->get($uri); }
php
public function getVideosByArticles($id) { $uri = Article::$object_endpoint . '/' . $id . '/' . Video::$object_endpoint; return $this->get($uri); }
[ "public", "function", "getVideosByArticles", "(", "$", "id", ")", "{", "$", "uri", "=", "Article", "::", "$", "object_endpoint", ".", "'/'", ".", "$", "id", ".", "'/'", ".", "Video", "::", "$", "object_endpoint", ";", "return", "$", "this", "->", "get"...
Retrieve a list of videos for a given article. @param string $id ID of the article in Hail @return array @throws
[ "Retrieve", "a", "list", "of", "videos", "for", "a", "given", "article", "." ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Api/Client.php#L505-L509
train
CradlePHP/cradle-system
src/Schema/Validator.php
Validator.getCreateErrors
public static function getCreateErrors(array $data, array $errors = []) { if (!isset($data['singular']) || empty($data['singular'])) { $errors['singular'] = 'Singular is required'; } if (!isset($data['plural']) || empty($data['plural'])) { $errors['plural'] = 'Plural is required'; } if (!isset($data['name']) || empty($data['name'])) { $errors['name'] = 'Keyword is required'; } if (!isset($data['fields']) || empty($data['fields'])) { $errors['fields'] = 'Fields is required'; } if (isset($data['name'])) { $exists = false; try { $exists = Schema::i($data['name'])->getAll(); } catch (Exception $e) { } if ($exists) { $errors['name'] = 'Schema already exists'; } } return self::getOptionalErrors($data, $errors); }
php
public static function getCreateErrors(array $data, array $errors = []) { if (!isset($data['singular']) || empty($data['singular'])) { $errors['singular'] = 'Singular is required'; } if (!isset($data['plural']) || empty($data['plural'])) { $errors['plural'] = 'Plural is required'; } if (!isset($data['name']) || empty($data['name'])) { $errors['name'] = 'Keyword is required'; } if (!isset($data['fields']) || empty($data['fields'])) { $errors['fields'] = 'Fields is required'; } if (isset($data['name'])) { $exists = false; try { $exists = Schema::i($data['name'])->getAll(); } catch (Exception $e) { } if ($exists) { $errors['name'] = 'Schema already exists'; } } return self::getOptionalErrors($data, $errors); }
[ "public", "static", "function", "getCreateErrors", "(", "array", "$", "data", ",", "array", "$", "errors", "=", "[", "]", ")", "{", "if", "(", "!", "isset", "(", "$", "data", "[", "'singular'", "]", ")", "||", "empty", "(", "$", "data", "[", "'sing...
Returns Table Create Errors @param *array $data @param array $errors @return array
[ "Returns", "Table", "Create", "Errors" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema/Validator.php#L31-L62
train
CradlePHP/cradle-system
src/Schema/Validator.php
Validator.getOptionalErrors
public static function getOptionalErrors(array $data, array $errors = []) { //validations if (isset($data['singular']) && strlen($data['singular']) <= 2) { $errors['singular'] = 'Singular should be longer than 2 characters'; } if (isset($data['singular']) && strlen($data['singular']) >= 255) { $errors['singular'] = 'Singular should be less than 255 characters'; } if (isset($data['plural']) && strlen($data['plural']) <= 2) { $errors['plural'] = 'Plural should be longer than 2 characters'; } if (isset($data['plural']) && strlen($data['plural']) >= 255) { $errors['plural'] = 'Plural should be less than 255 characters'; } if (isset($data['name']) && !preg_match('#^[a-zA-Z0-9\-_]+$#', $data['name'])) { $errors['name'] = 'Keyword must only have letters, numbers, dashes'; } if (isset($data['relations'])) { $relations = []; foreach ($data['relations'] as $i => $relation) { if (in_array($relation['name'], $relations)) { $errors['relations'] = 'Duplicate Relations'; break; } if (!trim($relation['name'])) { $errors['relations'] = 'Empty relation name'; break; } $relations[] = $relation['name']; } } return $errors; }
php
public static function getOptionalErrors(array $data, array $errors = []) { //validations if (isset($data['singular']) && strlen($data['singular']) <= 2) { $errors['singular'] = 'Singular should be longer than 2 characters'; } if (isset($data['singular']) && strlen($data['singular']) >= 255) { $errors['singular'] = 'Singular should be less than 255 characters'; } if (isset($data['plural']) && strlen($data['plural']) <= 2) { $errors['plural'] = 'Plural should be longer than 2 characters'; } if (isset($data['plural']) && strlen($data['plural']) >= 255) { $errors['plural'] = 'Plural should be less than 255 characters'; } if (isset($data['name']) && !preg_match('#^[a-zA-Z0-9\-_]+$#', $data['name'])) { $errors['name'] = 'Keyword must only have letters, numbers, dashes'; } if (isset($data['relations'])) { $relations = []; foreach ($data['relations'] as $i => $relation) { if (in_array($relation['name'], $relations)) { $errors['relations'] = 'Duplicate Relations'; break; } if (!trim($relation['name'])) { $errors['relations'] = 'Empty relation name'; break; } $relations[] = $relation['name']; } } return $errors; }
[ "public", "static", "function", "getOptionalErrors", "(", "array", "$", "data", ",", "array", "$", "errors", "=", "[", "]", ")", "{", "//validations", "if", "(", "isset", "(", "$", "data", "[", "'singular'", "]", ")", "&&", "strlen", "(", "$", "data", ...
Returns Table Optional Errors @param *array $data @param array $errors @return array
[ "Returns", "Table", "Optional", "Errors" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema/Validator.php#L101-L143
train
CradlePHP/cradle-system
src/Schema.php
Schema.getRelations
public function getRelations($many = -1) { $results = []; if (!isset($this->data['relations']) || empty($this->data['relations']) ) { return $results; } $table = $this->getName(); $primary = $this->getPrimaryFieldName(); foreach ($this->data['relations'] as $relation) { if (is_numeric($many) && $many != -1 && $many != $relation['many']) { continue; } //case for getting a specific relation if (!is_numeric($many) && $relation['name'] !== $many) { continue; } $name = $table . '_' . $relation['name']; $results[$name] = []; try { $results[$name] = Schema::i($relation['name'])->getAll(false); } catch (Exception $e) { //this is not a registered schema //lets make a best guess $results[$name]['name'] = $relation['name']; $results[$name]['singular'] = ucfirst($relation['name']); $results[$name]['plural'] = $results[$name]['singular'] . 's'; $results[$name]['primary'] = $relation['name'] . '_id'; } $results[$name]['table'] = $name; $results[$name]['primary1'] = $primary; $results[$name]['primary2'] = $results[$name]['primary']; $results[$name]['many'] = $relation['many']; $results[$name]['source'] = $this->getAll(false); //case for relating to itself ie. post_post if ($table === $relation['name']) { $results[$name]['primary1'] .= '_1'; $results[$name]['primary2'] .= '_2'; } //case for getting a specific relation if (!is_numeric($many) && $relation['name'] === $many) { return $results[$name]; } } return $results; }
php
public function getRelations($many = -1) { $results = []; if (!isset($this->data['relations']) || empty($this->data['relations']) ) { return $results; } $table = $this->getName(); $primary = $this->getPrimaryFieldName(); foreach ($this->data['relations'] as $relation) { if (is_numeric($many) && $many != -1 && $many != $relation['many']) { continue; } //case for getting a specific relation if (!is_numeric($many) && $relation['name'] !== $many) { continue; } $name = $table . '_' . $relation['name']; $results[$name] = []; try { $results[$name] = Schema::i($relation['name'])->getAll(false); } catch (Exception $e) { //this is not a registered schema //lets make a best guess $results[$name]['name'] = $relation['name']; $results[$name]['singular'] = ucfirst($relation['name']); $results[$name]['plural'] = $results[$name]['singular'] . 's'; $results[$name]['primary'] = $relation['name'] . '_id'; } $results[$name]['table'] = $name; $results[$name]['primary1'] = $primary; $results[$name]['primary2'] = $results[$name]['primary']; $results[$name]['many'] = $relation['many']; $results[$name]['source'] = $this->getAll(false); //case for relating to itself ie. post_post if ($table === $relation['name']) { $results[$name]['primary1'] .= '_1'; $results[$name]['primary2'] .= '_2'; } //case for getting a specific relation if (!is_numeric($many) && $relation['name'] === $many) { return $results[$name]; } } return $results; }
[ "public", "function", "getRelations", "(", "$", "many", "=", "-", "1", ")", "{", "$", "results", "=", "[", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "data", "[", "'relations'", "]", ")", "||", "empty", "(", "$", "this", "->", "...
Returns relational data @param int $many @return array
[ "Returns", "relational", "data" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema.php#L190-L246
train
CradlePHP/cradle-system
src/Schema.php
Schema.getReverseRelations
public function getReverseRelations($many = -1) { $results = []; $name = $this->getName(); $payload = cradle()->makePayload(); cradle()->trigger( 'system-schema-search', $payload['request'], $payload['response'] ); $rows = $payload['response']->getResults('rows'); if (empty($rows)) { return $results; } foreach ($rows as $row) { $schema = Schema::i($row['name']); $table = $row['name'] . '_' . $name; $relations = $schema->getRelations(); if (!isset($relations[$table]['many']) || ( $many != -1 && $many != $relations[$table]['many'] ) ) { continue; } $results[$table] = $relations[$table]; $results[$table]['source'] = $schema->getAll(false); } return $results; }
php
public function getReverseRelations($many = -1) { $results = []; $name = $this->getName(); $payload = cradle()->makePayload(); cradle()->trigger( 'system-schema-search', $payload['request'], $payload['response'] ); $rows = $payload['response']->getResults('rows'); if (empty($rows)) { return $results; } foreach ($rows as $row) { $schema = Schema::i($row['name']); $table = $row['name'] . '_' . $name; $relations = $schema->getRelations(); if (!isset($relations[$table]['many']) || ( $many != -1 && $many != $relations[$table]['many'] ) ) { continue; } $results[$table] = $relations[$table]; $results[$table]['source'] = $schema->getAll(false); } return $results; }
[ "public", "function", "getReverseRelations", "(", "$", "many", "=", "-", "1", ")", "{", "$", "results", "=", "[", "]", ";", "$", "name", "=", "$", "this", "->", "getName", "(", ")", ";", "$", "payload", "=", "cradle", "(", ")", "->", "makePayload",...
Returns reverse relational data @param int $many @return array
[ "Returns", "reverse", "relational", "data" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema.php#L255-L293
train
CradlePHP/cradle-system
src/Schema.php
Schema.getSuggestionFormat
public function getSuggestionFormat(array $data) { //if no suggestion format if (!isset($this->data['suggestion']) || !trim($this->data['suggestion'])) { //use best guess $suggestion = null; foreach ($data as $key => $value) { if (is_numeric($value) || ( isset($value[0]) && is_numeric($value[0]) ) ) { continue; } $suggestion = $value; break; } //if still no suggestion if (is_null($suggestion)) { //just get the first one, i guess. foreach ($data as $key => $value) { $suggestion = $value; break; } } return $suggestion; } $template = cradle('global')->handlebars()->compile($this->data['suggestion']); return $template($data); }
php
public function getSuggestionFormat(array $data) { //if no suggestion format if (!isset($this->data['suggestion']) || !trim($this->data['suggestion'])) { //use best guess $suggestion = null; foreach ($data as $key => $value) { if (is_numeric($value) || ( isset($value[0]) && is_numeric($value[0]) ) ) { continue; } $suggestion = $value; break; } //if still no suggestion if (is_null($suggestion)) { //just get the first one, i guess. foreach ($data as $key => $value) { $suggestion = $value; break; } } return $suggestion; } $template = cradle('global')->handlebars()->compile($this->data['suggestion']); return $template($data); }
[ "public", "function", "getSuggestionFormat", "(", "array", "$", "data", ")", "{", "//if no suggestion format", "if", "(", "!", "isset", "(", "$", "this", "->", "data", "[", "'suggestion'", "]", ")", "||", "!", "trim", "(", "$", "this", "->", "data", "[",...
Based on the data will generate a suggestion format @param array @return string
[ "Based", "on", "the", "data", "will", "generate", "a", "suggestion", "format" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema.php#L325-L360
train
CradlePHP/cradle-system
src/Schema.php
Schema.getUpdatedFieldName
public function getUpdatedFieldName() { if (!isset($this->data['fields']) || empty($this->data['fields'])) { return false; } $table = $this->data['name']; foreach ($this->data['fields'] as $field) { if ($field['name'] === 'updated') { return $table . '_' . $field['name']; } } return false; }
php
public function getUpdatedFieldName() { if (!isset($this->data['fields']) || empty($this->data['fields'])) { return false; } $table = $this->data['name']; foreach ($this->data['fields'] as $field) { if ($field['name'] === 'updated') { return $table . '_' . $field['name']; } } return false; }
[ "public", "function", "getUpdatedFieldName", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "data", "[", "'fields'", "]", ")", "||", "empty", "(", "$", "this", "->", "data", "[", "'fields'", "]", ")", ")", "{", "return", "false", "...
Returns updated field @return string|false
[ "Returns", "updated", "field" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Schema.php#L390-L404
train
CradlePHP/cradle-system
src/Model/Service/SqlService.php
SqlService.create
public function create(array $data) { if (is_null($this->schema)) { throw SystemException::forNoSchema(); } $table = $this->schema->getName(); $created = $this->schema->getCreatedFieldName(); $updated = $this->schema->getUpdatedFieldName(); $ipaddress = $this->schema->getIPAddressFieldName(); if ($created) { $data[$created] = date('Y-m-d H:i:s'); } if ($updated) { $data[$updated] = date('Y-m-d H:i:s'); } if ($ipaddress && isset($_SERVER['REMOTE_ADDR'])) { $data[$ipaddress] = $_SERVER['REMOTE_ADDR']; } $uuids = $this->schema->getUuidFieldNames(); foreach($uuids as $uuid) { $data[$uuid] = sha1(uniqid()); } return $this ->resource ->model($data) ->save($table) ->get(); }
php
public function create(array $data) { if (is_null($this->schema)) { throw SystemException::forNoSchema(); } $table = $this->schema->getName(); $created = $this->schema->getCreatedFieldName(); $updated = $this->schema->getUpdatedFieldName(); $ipaddress = $this->schema->getIPAddressFieldName(); if ($created) { $data[$created] = date('Y-m-d H:i:s'); } if ($updated) { $data[$updated] = date('Y-m-d H:i:s'); } if ($ipaddress && isset($_SERVER['REMOTE_ADDR'])) { $data[$ipaddress] = $_SERVER['REMOTE_ADDR']; } $uuids = $this->schema->getUuidFieldNames(); foreach($uuids as $uuid) { $data[$uuid] = sha1(uniqid()); } return $this ->resource ->model($data) ->save($table) ->get(); }
[ "public", "function", "create", "(", "array", "$", "data", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "schema", ")", ")", "{", "throw", "SystemException", "::", "forNoSchema", "(", ")", ";", "}", "$", "table", "=", "$", "this", "->", "...
Create in database @param *array $object @param *array $data @return array
[ "Create", "in", "database" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Model/Service/SqlService.php#L58-L92
train
CradlePHP/cradle-system
src/Model/Service/SqlService.php
SqlService.exists
public function exists($key, $value) { if (is_null($this->schema)) { throw SystemException::forNoSchema(); } $search = $this ->resource ->search($this->schema->getName()) ->addFilter($key . ' = %s', $value); return !!$search->getRow(); }
php
public function exists($key, $value) { if (is_null($this->schema)) { throw SystemException::forNoSchema(); } $search = $this ->resource ->search($this->schema->getName()) ->addFilter($key . ' = %s', $value); return !!$search->getRow(); }
[ "public", "function", "exists", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "schema", ")", ")", "{", "throw", "SystemException", "::", "forNoSchema", "(", ")", ";", "}", "$", "search", "=", "$", "this...
Checks to see if unique.0 already exists @param *string $objectKey @return bool
[ "Checks", "to", "see", "if", "unique", ".", "0", "already", "exists" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Model/Service/SqlService.php#L101-L113
train
CradlePHP/cradle-system
src/Model/Service/SqlService.php
SqlService.remove
public function remove($id) { if (is_null($this->schema)) { throw SystemException::forNoSchema(); } $table = $this->schema->getName(); $primary = $this->schema->getPrimaryFieldName(); //please rely on SQL CASCADING ON DELETE $model = $this->resource->model(); $model[$primary] = $id; return $model->remove($table); }
php
public function remove($id) { if (is_null($this->schema)) { throw SystemException::forNoSchema(); } $table = $this->schema->getName(); $primary = $this->schema->getPrimaryFieldName(); //please rely on SQL CASCADING ON DELETE $model = $this->resource->model(); $model[$primary] = $id; return $model->remove($table); }
[ "public", "function", "remove", "(", "$", "id", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "schema", ")", ")", "{", "throw", "SystemException", "::", "forNoSchema", "(", ")", ";", "}", "$", "table", "=", "$", "this", "->", "schema", "-...
Remove from database PLEASE BECAREFUL USING THIS !!! It's here for clean up scripts @param *array $object @param *int $id
[ "Remove", "from", "database", "PLEASE", "BECAREFUL", "USING", "THIS", "!!!", "It", "s", "here", "for", "clean", "up", "scripts" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Model/Service/SqlService.php#L371-L383
train
CradlePHP/cradle-system
src/Model/Service/SqlService.php
SqlService.unlink
public function unlink($relation, $primary1, $primary2) { if (is_null($this->schema)) { throw SystemException::forNoSchema(); } $name = $this->schema->getName(); $relations = $this->schema->getRelations(); $table = $name . '_' . $relation; if (!isset($relations[$table])) { throw SystemException::forNoRelation($name, $relation); } $relation = $relations[$table]; $model = $this->resource->model(); $model[$relation['primary1']] = $primary1; $model[$relation['primary2']] = $primary2; return $model->remove($table); }
php
public function unlink($relation, $primary1, $primary2) { if (is_null($this->schema)) { throw SystemException::forNoSchema(); } $name = $this->schema->getName(); $relations = $this->schema->getRelations(); $table = $name . '_' . $relation; if (!isset($relations[$table])) { throw SystemException::forNoRelation($name, $relation); } $relation = $relations[$table]; $model = $this->resource->model(); $model[$relation['primary1']] = $primary1; $model[$relation['primary2']] = $primary2; return $model->remove($table); }
[ "public", "function", "unlink", "(", "$", "relation", ",", "$", "primary1", ",", "$", "primary2", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "schema", ")", ")", "{", "throw", "SystemException", "::", "forNoSchema", "(", ")", ";", "}", "$...
Unlinks table to another table @param *string $relation @param *int $primary1 @param *int $primary2 @return array
[ "Unlinks", "table", "to", "another", "table" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Model/Service/SqlService.php#L822-L843
train
CradlePHP/cradle-system
src/Model/Service/SqlService.php
SqlService.unlinkAll
public function unlinkAll($relation, $primary) { if (is_null($this->schema)) { throw SystemException::forNoSchema(); } $name = $this->schema->getName(); $relations = $this->schema->getRelations(); $table = $name . '_' . $relation; if (!isset($relations[$table])) { throw SystemException::forNoRelation($name, $relation); } $relation = $relations[$table]; $filter = sprintf('%s = %%s', $relation['primary1']); return $this ->resource ->search($table) ->addFilter($filter, $primary) ->getCollection() ->each(function ($i, $model) use (&$table) { $model->remove($table); }) ->get(); }
php
public function unlinkAll($relation, $primary) { if (is_null($this->schema)) { throw SystemException::forNoSchema(); } $name = $this->schema->getName(); $relations = $this->schema->getRelations(); $table = $name . '_' . $relation; if (!isset($relations[$table])) { throw SystemException::forNoRelation($name, $relation); } $relation = $relations[$table]; $filter = sprintf('%s = %%s', $relation['primary1']); return $this ->resource ->search($table) ->addFilter($filter, $primary) ->getCollection() ->each(function ($i, $model) use (&$table) { $model->remove($table); }) ->get(); }
[ "public", "function", "unlinkAll", "(", "$", "relation", ",", "$", "primary", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "schema", ")", ")", "{", "throw", "SystemException", "::", "forNoSchema", "(", ")", ";", "}", "$", "name", "=", "$",...
Unlinks all references in a table from another table @param *string $relation @param *int $primary @return array
[ "Unlinks", "all", "references", "in", "a", "table", "from", "another", "table" ]
3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c
https://github.com/CradlePHP/cradle-system/blob/3dda31fbc7e4523fdcc87e18a7ab852116cbdc6c/src/Model/Service/SqlService.php#L853-L880
train
firebrandhq/silverstripe-hail
src/Lists/HailList.php
HailList.getOrganisations
public function getOrganisations() { $config = SiteConfig::current_site_config(); //Filter out Organisation that are not setup in the config $organisations = Organisation::get()->filter(['HailID' => json_decode($config->HailOrgsIDs)]); return $organisations->sort('Title')->map('HailID', 'Title')->toArray(); }
php
public function getOrganisations() { $config = SiteConfig::current_site_config(); //Filter out Organisation that are not setup in the config $organisations = Organisation::get()->filter(['HailID' => json_decode($config->HailOrgsIDs)]); return $organisations->sort('Title')->map('HailID', 'Title')->toArray(); }
[ "public", "function", "getOrganisations", "(", ")", "{", "$", "config", "=", "SiteConfig", "::", "current_site_config", "(", ")", ";", "//Filter out Organisation that are not setup in the config\r", "$", "organisations", "=", "Organisation", "::", "get", "(", ")", "->...
Get currently configured Hail Organisations @return array
[ "Get", "currently", "configured", "Hail", "Organisations" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Lists/HailList.php#L107-L114
train
firebrandhq/silverstripe-hail
src/Lists/HailList.php
HailList.getPrivateTagsList
public function getPrivateTagsList() { $config = SiteConfig::current_site_config(); //Filter out global excluded tags and non configured Organisations $pri_tags = PrivateTag::get()->filter(['HailID:not' => json_decode($config->HailExcludePrivateTagsIDs), 'HailOrgID' => json_decode($config->HailOrgsIDs)]); return $pri_tags->sort(['HailOrgName ASC', 'Name ASC'])->map('HailID', 'FullName')->toArray(); }
php
public function getPrivateTagsList() { $config = SiteConfig::current_site_config(); //Filter out global excluded tags and non configured Organisations $pri_tags = PrivateTag::get()->filter(['HailID:not' => json_decode($config->HailExcludePrivateTagsIDs), 'HailOrgID' => json_decode($config->HailOrgsIDs)]); return $pri_tags->sort(['HailOrgName ASC', 'Name ASC'])->map('HailID', 'FullName')->toArray(); }
[ "public", "function", "getPrivateTagsList", "(", ")", "{", "$", "config", "=", "SiteConfig", "::", "current_site_config", "(", ")", ";", "//Filter out global excluded tags and non configured Organisations\r", "$", "pri_tags", "=", "PrivateTag", "::", "get", "(", ")", ...
Get currently available Hail Private Tags @return array
[ "Get", "currently", "available", "Hail", "Private", "Tags" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Lists/HailList.php#L121-L128
train
firebrandhq/silverstripe-hail
src/Lists/HailList.php
HailList.getPublicTagsList
public function getPublicTagsList() { $config = SiteConfig::current_site_config(); //Filter out global excluded tags and non configured Organisations $pub_tags = PublicTag::get()->filter(['HailID:not' => json_decode($config->HailExcludePublicTagsIDs), 'HailOrgID' => json_decode($config->HailOrgsIDs)]); return $pub_tags->sort(['HailOrgName ASC', 'Name ASC'])->map('HailID', 'FullName')->toArray(); }
php
public function getPublicTagsList() { $config = SiteConfig::current_site_config(); //Filter out global excluded tags and non configured Organisations $pub_tags = PublicTag::get()->filter(['HailID:not' => json_decode($config->HailExcludePublicTagsIDs), 'HailOrgID' => json_decode($config->HailOrgsIDs)]); return $pub_tags->sort(['HailOrgName ASC', 'Name ASC'])->map('HailID', 'FullName')->toArray(); }
[ "public", "function", "getPublicTagsList", "(", ")", "{", "$", "config", "=", "SiteConfig", "::", "current_site_config", "(", ")", ";", "//Filter out global excluded tags and non configured Organisations\r", "$", "pub_tags", "=", "PublicTag", "::", "get", "(", ")", "-...
Get currently available Hail Public Tags @return array
[ "Get", "currently", "available", "Hail", "Public", "Tags" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Lists/HailList.php#L135-L142
train
firebrandhq/silverstripe-hail
src/Pages/HailPage.php
HailPage.getCurrentArticle
public function getCurrentArticle() { if ($this->current_article instanceof Article || $this->current_article === null) { return $this->current_article; } $params = Controller::curr()->getRequest()->params(); if(empty($params['ID'])){ $this->current_article = null; } else { $this->current_article = Article::get()->filter(['HailID' => $params['ID']])->first(); } return $this->current_article; }
php
public function getCurrentArticle() { if ($this->current_article instanceof Article || $this->current_article === null) { return $this->current_article; } $params = Controller::curr()->getRequest()->params(); if(empty($params['ID'])){ $this->current_article = null; } else { $this->current_article = Article::get()->filter(['HailID' => $params['ID']])->first(); } return $this->current_article; }
[ "public", "function", "getCurrentArticle", "(", ")", "{", "if", "(", "$", "this", "->", "current_article", "instanceof", "Article", "||", "$", "this", "->", "current_article", "===", "null", ")", "{", "return", "$", "this", "->", "current_article", ";", "}",...
Get article accessed in current request @return Article|null
[ "Get", "article", "accessed", "in", "current", "request" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Pages/HailPage.php#L132-L146
train
firebrandhq/silverstripe-hail
src/Pages/HailPage.php
HailPage.MetaTags
public function MetaTags($includeTitle = true) { $tags = parent::MetaTags($includeTitle); $params = Controller::curr()->getRequest()->params(); if ($article = $this->getCurrentArticle()) { $tags .= "<link rel=\"canonical\" href=\"{$article->AbsoluteLink()}\" />\n"; if ($article->Lead || $article->Content) { $tags = explode("\n", $tags); //Replace description meta tag with article lead foreach ($tags as $index => $tag) { if (strpos($tag, "name=\"description\"")) { $description = $article->Lead ? $article->Lead : $article->Content; $description = mb_strimwidth($description, 0, 300, '...'); $tags[$index] = "<meta name=\"description\" content=\"$article->Lead\">\n"; } } $tags = implode("\n", $tags); } } return $tags; }
php
public function MetaTags($includeTitle = true) { $tags = parent::MetaTags($includeTitle); $params = Controller::curr()->getRequest()->params(); if ($article = $this->getCurrentArticle()) { $tags .= "<link rel=\"canonical\" href=\"{$article->AbsoluteLink()}\" />\n"; if ($article->Lead || $article->Content) { $tags = explode("\n", $tags); //Replace description meta tag with article lead foreach ($tags as $index => $tag) { if (strpos($tag, "name=\"description\"")) { $description = $article->Lead ? $article->Lead : $article->Content; $description = mb_strimwidth($description, 0, 300, '...'); $tags[$index] = "<meta name=\"description\" content=\"$article->Lead\">\n"; } } $tags = implode("\n", $tags); } } return $tags; }
[ "public", "function", "MetaTags", "(", "$", "includeTitle", "=", "true", ")", "{", "$", "tags", "=", "parent", "::", "MetaTags", "(", "$", "includeTitle", ")", ";", "$", "params", "=", "Controller", "::", "curr", "(", ")", "->", "getRequest", "(", ")",...
Add a canonical link meta tag Replace description meta tag with Article description when necessary @param boolean $includeTitle Show default <title>-tag, set to false for custom templating @return string The XHTML metatags
[ "Add", "a", "canonical", "link", "meta", "tag", "Replace", "description", "meta", "tag", "with", "Article", "description", "when", "necessary" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Pages/HailPage.php#L155-L176
train
firebrandhq/silverstripe-hail
src/Pages/HailPage.php
HailPage.getTitle
public function getTitle() { $article = $this->getCurrentArticle(); if ($article instanceof Article) { return $article->Title; } return parent::getTitle(); }
php
public function getTitle() { $article = $this->getCurrentArticle(); if ($article instanceof Article) { return $article->Title; } return parent::getTitle(); }
[ "public", "function", "getTitle", "(", ")", "{", "$", "article", "=", "$", "this", "->", "getCurrentArticle", "(", ")", ";", "if", "(", "$", "article", "instanceof", "Article", ")", "{", "return", "$", "article", "->", "Title", ";", "}", "return", "par...
Get page or article title @return string
[ "Get", "page", "or", "article", "title" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Pages/HailPage.php#L183-L191
train
firebrandhq/silverstripe-hail
src/Controllers/HailController.php
HailController.progress
public function progress(HTTPRequest $request) { if (!Security::getCurrentUser()) { return $this->makeJsonReponse(401, [ 'message' => 'Unauthorized.' ])->setStatusDescription('Unauthorized.'); } $latest_job = FetchJob::get()->filter('ErrorShown', 0)->sort('Created DESC')->first(); if ($latest_job) { $map = $latest_job->toMap(); if ($latest_job->Status === "Error") { $latest_job->ErrorShown = 1; $latest_job->write(); } return $this->makeJsonReponse(200, $map); } return $this->makeJsonReponse(200, [ 'message' => 'No hail job found.', 'Status' => 'Done' ]); }
php
public function progress(HTTPRequest $request) { if (!Security::getCurrentUser()) { return $this->makeJsonReponse(401, [ 'message' => 'Unauthorized.' ])->setStatusDescription('Unauthorized.'); } $latest_job = FetchJob::get()->filter('ErrorShown', 0)->sort('Created DESC')->first(); if ($latest_job) { $map = $latest_job->toMap(); if ($latest_job->Status === "Error") { $latest_job->ErrorShown = 1; $latest_job->write(); } return $this->makeJsonReponse(200, $map); } return $this->makeJsonReponse(200, [ 'message' => 'No hail job found.', 'Status' => 'Done' ]); }
[ "public", "function", "progress", "(", "HTTPRequest", "$", "request", ")", "{", "if", "(", "!", "Security", "::", "getCurrentUser", "(", ")", ")", "{", "return", "$", "this", "->", "makeJsonReponse", "(", "401", ",", "[", "'message'", "=>", "'Unauthorized....
Get the progress on the current fetch job running @param HTTPRequest $request Current request @return HTTPResponse JSON response @throws
[ "Get", "the", "progress", "on", "the", "current", "fetch", "job", "running" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Controllers/HailController.php#L120-L145
train
firebrandhq/silverstripe-hail
src/Controllers/HailController.php
HailController.fetchOneSync
public function fetchOneSync(HTTPRequest $request) { if (!Security::getCurrentUser()) { return $this->makeJsonReponse(401, [ 'message' => 'Unauthorized.' ])->setStatusDescription('Unauthorized.'); } $params = $request->params(); if (empty($params['Class']) || empty($params['HailID'])) { return $this->makeJsonReponse(400, [ 'message' => 'Invalid request.' ]); } $class_name = str_replace("-", "\\", $params['Class']); if (!class_exists($class_name)) { return $this->makeJsonReponse(400, [ 'message' => 'Invalid request.' ]); } $object = DataObject::get($class_name)->filter(['HailID' => $params['HailID']])->first(); if (!$object) { return $this->makeJsonReponse(404, [ 'message' => 'Object does not exist.' ]); } //Refresh from Hail API $object->refresh(); return $this->makeJsonReponse(200, [ 'message' => 'Success' ]); }
php
public function fetchOneSync(HTTPRequest $request) { if (!Security::getCurrentUser()) { return $this->makeJsonReponse(401, [ 'message' => 'Unauthorized.' ])->setStatusDescription('Unauthorized.'); } $params = $request->params(); if (empty($params['Class']) || empty($params['HailID'])) { return $this->makeJsonReponse(400, [ 'message' => 'Invalid request.' ]); } $class_name = str_replace("-", "\\", $params['Class']); if (!class_exists($class_name)) { return $this->makeJsonReponse(400, [ 'message' => 'Invalid request.' ]); } $object = DataObject::get($class_name)->filter(['HailID' => $params['HailID']])->first(); if (!$object) { return $this->makeJsonReponse(404, [ 'message' => 'Object does not exist.' ]); } //Refresh from Hail API $object->refresh(); return $this->makeJsonReponse(200, [ 'message' => 'Success' ]); }
[ "public", "function", "fetchOneSync", "(", "HTTPRequest", "$", "request", ")", "{", "if", "(", "!", "Security", "::", "getCurrentUser", "(", ")", ")", "{", "return", "$", "this", "->", "makeJsonReponse", "(", "401", ",", "[", "'message'", "=>", "'Unauthori...
Fetch one specific Hail object synchronously and update its database record The object to fetch is specified in the URL e.g.: /hail/fetchOne/[CLASS]/[HAILID] Example: /hail/fetchOne/Firebrand-Hail-Models-Article/l1KjRUP will fetch and update the article with HailID=l1KjRUP @param HTTPRequest $request Current request @return HTTPResponse JSON response @throws
[ "Fetch", "one", "specific", "Hail", "object", "synchronously", "and", "update", "its", "database", "record" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Controllers/HailController.php#L159-L193
train
firebrandhq/silverstripe-hail
src/Controllers/HailController.php
HailController.articles
public function articles(HTTPRequest $request) { if (!Security::getCurrentUser()) { return $this->makeJsonReponse(401, [ 'message' => 'Unauthorized.' ])->setStatusDescription('Unauthorized.'); } $pages = HailPage::get(); $articles = [['text' => 'Select an article']]; foreach ($pages as $page) { $list = $page->getFullHailList(); foreach ($list as $item) { $link = $item->getLinkForPage($page); if ($item->getType() === 'article') { $link = Director::absoluteURL($link); } $create_at = isset($item->Date) ? $item->Date : $item->DueDate; $date = new \DateTime($create_at); $name = $date->format('d/m/Y') . ' - ' . $page->Title . ' - ' . $item->Title; $articles[] = [ 'text' => $name, 'value' => $link ]; } } return $this->makeJsonReponse(200, $articles); }
php
public function articles(HTTPRequest $request) { if (!Security::getCurrentUser()) { return $this->makeJsonReponse(401, [ 'message' => 'Unauthorized.' ])->setStatusDescription('Unauthorized.'); } $pages = HailPage::get(); $articles = [['text' => 'Select an article']]; foreach ($pages as $page) { $list = $page->getFullHailList(); foreach ($list as $item) { $link = $item->getLinkForPage($page); if ($item->getType() === 'article') { $link = Director::absoluteURL($link); } $create_at = isset($item->Date) ? $item->Date : $item->DueDate; $date = new \DateTime($create_at); $name = $date->format('d/m/Y') . ' - ' . $page->Title . ' - ' . $item->Title; $articles[] = [ 'text' => $name, 'value' => $link ]; } } return $this->makeJsonReponse(200, $articles); }
[ "public", "function", "articles", "(", "HTTPRequest", "$", "request", ")", "{", "if", "(", "!", "Security", "::", "getCurrentUser", "(", ")", ")", "{", "return", "$", "this", "->", "makeJsonReponse", "(", "401", ",", "[", "'message'", "=>", "'Unauthorized....
Retrieve a list of articles from the database Only used by the Hail TinyMCE plugin to add article links to any HTML content @param HTTPRequest $request Current request @return HTTPResponse JSON response @throws
[ "Retrieve", "a", "list", "of", "articles", "from", "the", "database" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Controllers/HailController.php#L205-L233
train
firebrandhq/silverstripe-hail
src/Controllers/HailController.php
HailController.makeJsonReponse
public function makeJsonReponse($status_code, $body) { $this->getResponse()->setBody(json_encode($body, JSON_UNESCAPED_SLASHES)); $this->getResponse()->setStatusCode($status_code); $this->getResponse()->addHeader("Content-type", "application/json"); return $this->getResponse(); }
php
public function makeJsonReponse($status_code, $body) { $this->getResponse()->setBody(json_encode($body, JSON_UNESCAPED_SLASHES)); $this->getResponse()->setStatusCode($status_code); $this->getResponse()->addHeader("Content-type", "application/json"); return $this->getResponse(); }
[ "public", "function", "makeJsonReponse", "(", "$", "status_code", ",", "$", "body", ")", "{", "$", "this", "->", "getResponse", "(", ")", "->", "setBody", "(", "json_encode", "(", "$", "body", ",", "JSON_UNESCAPED_SLASHES", ")", ")", ";", "$", "this", "-...
Make the JSON response @param int $status_code HTTP status code to return @param array|null $body JSON body of the request @return HTTPResponse JSON response
[ "Make", "the", "JSON", "response" ]
fd655b7a568f8d5f6a8f888f39368618596f794e
https://github.com/firebrandhq/silverstripe-hail/blob/fd655b7a568f8d5f6a8f888f39368618596f794e/src/Controllers/HailController.php#L243-L250
train