id
int32
0
241k
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
232,800
laravel-notification-channels/hipchat
src/Card.php
Card.toArray
public function toArray() { $card = str_array_filter([ 'id' => $this->id, 'style' => $this->style, 'format' => $this->cardFormat, 'title' => $this->title, 'url' => $this->url, ]); if (! str_empty($this->content)) { $card['description'] = [ 'value' => $this->content, 'format' => $this->format, ]; } if (! str_empty($this->thumbnail)) { $card['thumbnail'] = str_array_filter([ 'url' => $this->thumbnail, 'url@2x' => $this->thumbnail2, 'width' => $this->thumbnailWidth, 'height' => $this->thumbnailHeight, ]); } if (! str_empty($this->activity)) { $card['activity'] = str_array_filter([ 'html' => $this->activity, 'icon' => str_array_filter([ 'url' => $this->activityIcon, 'url@2x' => $this->activityIcon2, ]), ]); } if (! str_empty($this->icon)) { $card['icon'] = str_array_filter([ 'url' => $this->icon, 'url@2x' => $this->icon2, ]); } if (! empty($this->attributes)) { $card['attributes'] = array_map(function (CardAttribute $attribute) { return $attribute->toArray(); }, $this->attributes); } return $card; }
php
public function toArray() { $card = str_array_filter([ 'id' => $this->id, 'style' => $this->style, 'format' => $this->cardFormat, 'title' => $this->title, 'url' => $this->url, ]); if (! str_empty($this->content)) { $card['description'] = [ 'value' => $this->content, 'format' => $this->format, ]; } if (! str_empty($this->thumbnail)) { $card['thumbnail'] = str_array_filter([ 'url' => $this->thumbnail, 'url@2x' => $this->thumbnail2, 'width' => $this->thumbnailWidth, 'height' => $this->thumbnailHeight, ]); } if (! str_empty($this->activity)) { $card['activity'] = str_array_filter([ 'html' => $this->activity, 'icon' => str_array_filter([ 'url' => $this->activityIcon, 'url@2x' => $this->activityIcon2, ]), ]); } if (! str_empty($this->icon)) { $card['icon'] = str_array_filter([ 'url' => $this->icon, 'url@2x' => $this->icon2, ]); } if (! empty($this->attributes)) { $card['attributes'] = array_map(function (CardAttribute $attribute) { return $attribute->toArray(); }, $this->attributes); } return $card; }
[ "public", "function", "toArray", "(", ")", "{", "$", "card", "=", "str_array_filter", "(", "[", "'id'", "=>", "$", "this", "->", "id", ",", "'style'", "=>", "$", "this", "->", "style", ",", "'format'", "=>", "$", "this", "->", "cardFormat", ",", "'title'", "=>", "$", "this", "->", "title", ",", "'url'", "=>", "$", "this", "->", "url", ",", "]", ")", ";", "if", "(", "!", "str_empty", "(", "$", "this", "->", "content", ")", ")", "{", "$", "card", "[", "'description'", "]", "=", "[", "'value'", "=>", "$", "this", "->", "content", ",", "'format'", "=>", "$", "this", "->", "format", ",", "]", ";", "}", "if", "(", "!", "str_empty", "(", "$", "this", "->", "thumbnail", ")", ")", "{", "$", "card", "[", "'thumbnail'", "]", "=", "str_array_filter", "(", "[", "'url'", "=>", "$", "this", "->", "thumbnail", ",", "'url@2x'", "=>", "$", "this", "->", "thumbnail2", ",", "'width'", "=>", "$", "this", "->", "thumbnailWidth", ",", "'height'", "=>", "$", "this", "->", "thumbnailHeight", ",", "]", ")", ";", "}", "if", "(", "!", "str_empty", "(", "$", "this", "->", "activity", ")", ")", "{", "$", "card", "[", "'activity'", "]", "=", "str_array_filter", "(", "[", "'html'", "=>", "$", "this", "->", "activity", ",", "'icon'", "=>", "str_array_filter", "(", "[", "'url'", "=>", "$", "this", "->", "activityIcon", ",", "'url@2x'", "=>", "$", "this", "->", "activityIcon2", ",", "]", ")", ",", "]", ")", ";", "}", "if", "(", "!", "str_empty", "(", "$", "this", "->", "icon", ")", ")", "{", "$", "card", "[", "'icon'", "]", "=", "str_array_filter", "(", "[", "'url'", "=>", "$", "this", "->", "icon", ",", "'url@2x'", "=>", "$", "this", "->", "icon2", ",", "]", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "attributes", ")", ")", "{", "$", "card", "[", "'attributes'", "]", "=", "array_map", "(", "function", "(", "CardAttribute", "$", "attribute", ")", "{", "return", "$", "attribute", "->", "toArray", "(", ")", ";", "}", ",", "$", "this", "->", "attributes", ")", ";", "}", "return", "$", "card", ";", "}" ]
Get an array representation of the Card. @return array
[ "Get", "an", "array", "representation", "of", "the", "Card", "." ]
c24bca85f7cf9f6804635aa206c961783e22e888
https://github.com/laravel-notification-channels/hipchat/blob/c24bca85f7cf9f6804635aa206c961783e22e888/src/Card.php#L368-L418
232,801
laraplug/product-module
Http/Controllers/Api/CategoryController.php
CategoryController.update
public function update(Request $request) { $this->cache->tags('categories')->flush(); $this->categoryOrdener->handle($request->get('categories')); }
php
public function update(Request $request) { $this->cache->tags('categories')->flush(); $this->categoryOrdener->handle($request->get('categories')); }
[ "public", "function", "update", "(", "Request", "$", "request", ")", "{", "$", "this", "->", "cache", "->", "tags", "(", "'categories'", ")", "->", "flush", "(", ")", ";", "$", "this", "->", "categoryOrdener", "->", "handle", "(", "$", "request", "->", "get", "(", "'categories'", ")", ")", ";", "}" ]
Update all categories @param Request $request
[ "Update", "all", "categories" ]
0a835482d2888a05bfe145e1b453926832185ae0
https://github.com/laraplug/product-module/blob/0a835482d2888a05bfe145e1b453926832185ae0/Http/Controllers/Api/CategoryController.php#L52-L57
232,802
laraplug/product-module
Http/Controllers/Api/CategoryController.php
CategoryController.delete
public function delete(Request $request) { $category = $this->category->find($request->get('category')); if (!$category) { return Response::json(['errors' => true]); } $this->category->destroy($category); return Response::json(['errors' => false]); }
php
public function delete(Request $request) { $category = $this->category->find($request->get('category')); if (!$category) { return Response::json(['errors' => true]); } $this->category->destroy($category); return Response::json(['errors' => false]); }
[ "public", "function", "delete", "(", "Request", "$", "request", ")", "{", "$", "category", "=", "$", "this", "->", "category", "->", "find", "(", "$", "request", "->", "get", "(", "'category'", ")", ")", ";", "if", "(", "!", "$", "category", ")", "{", "return", "Response", "::", "json", "(", "[", "'errors'", "=>", "true", "]", ")", ";", "}", "$", "this", "->", "category", "->", "destroy", "(", "$", "category", ")", ";", "return", "Response", "::", "json", "(", "[", "'errors'", "=>", "false", "]", ")", ";", "}" ]
Delete a category @param Request $request @return mixed
[ "Delete", "a", "category" ]
0a835482d2888a05bfe145e1b453926832185ae0
https://github.com/laraplug/product-module/blob/0a835482d2888a05bfe145e1b453926832185ae0/Http/Controllers/Api/CategoryController.php#L64-L75
232,803
bav-php/bav
classes/dataBackend/file/download/Downloader.php
Downloader.download
private function download($uri) { curl_setopt($this->handle, CURLOPT_URL, $uri); $result = curl_exec($this->handle); $curl_info = curl_getinfo($this->handle); if ($curl_info['http_code'] >= 400) { throw new DownloaderException( sprintf( "Failed to download '%s'. HTTP Code: %d", $uri, $curl_info['http_code'] ) ); } return $result; }
php
private function download($uri) { curl_setopt($this->handle, CURLOPT_URL, $uri); $result = curl_exec($this->handle); $curl_info = curl_getinfo($this->handle); if ($curl_info['http_code'] >= 400) { throw new DownloaderException( sprintf( "Failed to download '%s'. HTTP Code: %d", $uri, $curl_info['http_code'] ) ); } return $result; }
[ "private", "function", "download", "(", "$", "uri", ")", "{", "curl_setopt", "(", "$", "this", "->", "handle", ",", "CURLOPT_URL", ",", "$", "uri", ")", ";", "$", "result", "=", "curl_exec", "(", "$", "this", "->", "handle", ")", ";", "$", "curl_info", "=", "curl_getinfo", "(", "$", "this", "->", "handle", ")", ";", "if", "(", "$", "curl_info", "[", "'http_code'", "]", ">=", "400", ")", "{", "throw", "new", "DownloaderException", "(", "sprintf", "(", "\"Failed to download '%s'. HTTP Code: %d\"", ",", "$", "uri", ",", "$", "curl_info", "[", "'http_code'", "]", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Execute the curl call. @throws DownloaderException @return mixed
[ "Execute", "the", "curl", "call", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/file/download/Downloader.php#L41-L57
232,804
bav-php/bav
classes/dataBackend/file/download/Downloader.php
Downloader.downloadContent
public function downloadContent($uri) { curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, true); $content = $this->download($uri); if (! $content) { throw new DataBackendIOException("Failed to download '$uri'."); } return $content; }
php
public function downloadContent($uri) { curl_setopt($this->handle, CURLOPT_RETURNTRANSFER, true); $content = $this->download($uri); if (! $content) { throw new DataBackendIOException("Failed to download '$uri'."); } return $content; }
[ "public", "function", "downloadContent", "(", "$", "uri", ")", "{", "curl_setopt", "(", "$", "this", "->", "handle", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "$", "content", "=", "$", "this", "->", "download", "(", "$", "uri", ")", ";", "if", "(", "!", "$", "content", ")", "{", "throw", "new", "DataBackendIOException", "(", "\"Failed to download '$uri'.\"", ")", ";", "}", "return", "$", "content", ";", "}" ]
Downloads the content of an URI @param string $uri URI @return string Content of the page @throws DownloaderException
[ "Downloads", "the", "content", "of", "an", "URI" ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/file/download/Downloader.php#L66-L76
232,805
silverstripe-archive/deploynaut
code/model/steps/TriggerDeployStep.php
TriggerDeployStep.deploy
public function deploy() { // Check permission if(!$this->canTriggerDeploy()) { return Security::permissionFailure( null, _t("TriggerDeployStep.DENYTRIGGERDEPLOY", "You do not have permission to deploy this pipeline") ); } if ($this->Status == 'Queued') { $this->start(); } // Trigger deployment $this->Deployed = SS_Datetime::now()->Rfc2822(); $this->log(_t('TriggerDeployStep.BEINGDEPLOYED', "{$this->Title} is being deployed")); $this->ResponderID = Member::currentUserID(); $this->finish(); return true; }
php
public function deploy() { // Check permission if(!$this->canTriggerDeploy()) { return Security::permissionFailure( null, _t("TriggerDeployStep.DENYTRIGGERDEPLOY", "You do not have permission to deploy this pipeline") ); } if ($this->Status == 'Queued') { $this->start(); } // Trigger deployment $this->Deployed = SS_Datetime::now()->Rfc2822(); $this->log(_t('TriggerDeployStep.BEINGDEPLOYED', "{$this->Title} is being deployed")); $this->ResponderID = Member::currentUserID(); $this->finish(); return true; }
[ "public", "function", "deploy", "(", ")", "{", "// Check permission", "if", "(", "!", "$", "this", "->", "canTriggerDeploy", "(", ")", ")", "{", "return", "Security", "::", "permissionFailure", "(", "null", ",", "_t", "(", "\"TriggerDeployStep.DENYTRIGGERDEPLOY\"", ",", "\"You do not have permission to deploy this pipeline\"", ")", ")", ";", "}", "if", "(", "$", "this", "->", "Status", "==", "'Queued'", ")", "{", "$", "this", "->", "start", "(", ")", ";", "}", "// Trigger deployment", "$", "this", "->", "Deployed", "=", "SS_Datetime", "::", "now", "(", ")", "->", "Rfc2822", "(", ")", ";", "$", "this", "->", "log", "(", "_t", "(", "'TriggerDeployStep.BEINGDEPLOYED'", ",", "\"{$this->Title} is being deployed\"", ")", ")", ";", "$", "this", "->", "ResponderID", "=", "Member", "::", "currentUserID", "(", ")", ";", "$", "this", "->", "finish", "(", ")", ";", "return", "true", ";", "}" ]
When a member wishes to deploy this pipeline @return boolean True if successful
[ "When", "a", "member", "wishes", "to", "deploy", "this", "pipeline" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/TriggerDeployStep.php#L79-L99
232,806
silverstripe-archive/deploynaut
code/model/steps/TriggerDeployStep.php
TriggerDeployStep.StartDeployment
public function StartDeployment() { $this->Status = 'Started'; if (!$this->Started) $this->Started = SS_Datetime::now()->Rfc2822(); $this->log("Starting {$this->Title}..."); $this->write(); return true; }
php
public function StartDeployment() { $this->Status = 'Started'; if (!$this->Started) $this->Started = SS_Datetime::now()->Rfc2822(); $this->log("Starting {$this->Title}..."); $this->write(); return true; }
[ "public", "function", "StartDeployment", "(", ")", "{", "$", "this", "->", "Status", "=", "'Started'", ";", "if", "(", "!", "$", "this", "->", "Started", ")", "$", "this", "->", "Started", "=", "SS_Datetime", "::", "now", "(", ")", "->", "Rfc2822", "(", ")", ";", "$", "this", "->", "log", "(", "\"Starting {$this->Title}...\"", ")", ";", "$", "this", "->", "write", "(", ")", ";", "return", "true", ";", "}" ]
Initiate the deployment process
[ "Initiate", "the", "deployment", "process" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/TriggerDeployStep.php#L104-L110
232,807
luwes/craft3-parsedown
src/twigextensions/ParsedownTwigExtension.php
ParsedownTwigExtension.parsedown
public function parsedown($text = null, $parseAs = 'text') { if ($parseAs == 'line') { $parsed = Parsedown::$plugin->parsedown->parseLine($text); } else { $parsed = Parsedown::$plugin->parsedown->parseText($text); } return Template::raw($parsed); }
php
public function parsedown($text = null, $parseAs = 'text') { if ($parseAs == 'line') { $parsed = Parsedown::$plugin->parsedown->parseLine($text); } else { $parsed = Parsedown::$plugin->parsedown->parseText($text); } return Template::raw($parsed); }
[ "public", "function", "parsedown", "(", "$", "text", "=", "null", ",", "$", "parseAs", "=", "'text'", ")", "{", "if", "(", "$", "parseAs", "==", "'line'", ")", "{", "$", "parsed", "=", "Parsedown", "::", "$", "plugin", "->", "parsedown", "->", "parseLine", "(", "$", "text", ")", ";", "}", "else", "{", "$", "parsed", "=", "Parsedown", "::", "$", "plugin", "->", "parsedown", "->", "parseText", "(", "$", "text", ")", ";", "}", "return", "Template", "::", "raw", "(", "$", "parsed", ")", ";", "}" ]
Our function called via Twig; it can do anything you want @param null $text @return string
[ "Our", "function", "called", "via", "Twig", ";", "it", "can", "do", "anything", "you", "want" ]
64da4bb8a32072c83070f4c8683a34369075f63a
https://github.com/luwes/craft3-parsedown/blob/64da4bb8a32072c83070f4c8683a34369075f63a/src/twigextensions/ParsedownTwigExtension.php#L81-L93
232,808
silverstripe-archive/deploynaut
code/model/steps/UserConfirmationStep.php
UserConfirmationStep.approve
public function approve() { // Check permission if(!$this->canApprove()) { return Security::permissionFailure( null, _t("UserConfirmationStep.DENYAPPROVE", "You do not have permission to approve this deployment") ); } // Skip subsequent approvals if already approved / rejected if($this->hasResponse()) return; // Approve $this->Approval = 'Approved'; $this->log("{$this->Title} has been approved"); $this->ResponderID = Member::currentUserID(); $this->finish(); $this->sendMessage(self::ALERT_APPROVE); return true; }
php
public function approve() { // Check permission if(!$this->canApprove()) { return Security::permissionFailure( null, _t("UserConfirmationStep.DENYAPPROVE", "You do not have permission to approve this deployment") ); } // Skip subsequent approvals if already approved / rejected if($this->hasResponse()) return; // Approve $this->Approval = 'Approved'; $this->log("{$this->Title} has been approved"); $this->ResponderID = Member::currentUserID(); $this->finish(); $this->sendMessage(self::ALERT_APPROVE); return true; }
[ "public", "function", "approve", "(", ")", "{", "// Check permission", "if", "(", "!", "$", "this", "->", "canApprove", "(", ")", ")", "{", "return", "Security", "::", "permissionFailure", "(", "null", ",", "_t", "(", "\"UserConfirmationStep.DENYAPPROVE\"", ",", "\"You do not have permission to approve this deployment\"", ")", ")", ";", "}", "// Skip subsequent approvals if already approved / rejected", "if", "(", "$", "this", "->", "hasResponse", "(", ")", ")", "return", ";", "// Approve", "$", "this", "->", "Approval", "=", "'Approved'", ";", "$", "this", "->", "log", "(", "\"{$this->Title} has been approved\"", ")", ";", "$", "this", "->", "ResponderID", "=", "Member", "::", "currentUserID", "(", ")", ";", "$", "this", "->", "finish", "(", ")", ";", "$", "this", "->", "sendMessage", "(", "self", "::", "ALERT_APPROVE", ")", ";", "return", "true", ";", "}" ]
When the recipient wishes to approve this request @return boolean True if successful
[ "When", "the", "recipient", "wishes", "to", "approve", "this", "request" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/UserConfirmationStep.php#L172-L191
232,809
silverstripe-archive/deploynaut
code/model/steps/UserConfirmationStep.php
UserConfirmationStep.reject
public function reject() { // Check permission if(!$this->canApprove()) { return Security::permissionFailure( null, _t("UserConfirmationStep.DENYREJECT", "You do not have permission to reject this deployment") ); } // Skip subsequent approvals if already approved / rejected if($this->hasResponse()) return; // Reject $this->Approval = 'Rejected'; $this->log("{$this->Title} has been rejected"); $this->ResponderID = Member::currentUserID(); $this->markFailed(false); $this->sendMessage(self::ALERT_REJECT); return true; }
php
public function reject() { // Check permission if(!$this->canApprove()) { return Security::permissionFailure( null, _t("UserConfirmationStep.DENYREJECT", "You do not have permission to reject this deployment") ); } // Skip subsequent approvals if already approved / rejected if($this->hasResponse()) return; // Reject $this->Approval = 'Rejected'; $this->log("{$this->Title} has been rejected"); $this->ResponderID = Member::currentUserID(); $this->markFailed(false); $this->sendMessage(self::ALERT_REJECT); return true; }
[ "public", "function", "reject", "(", ")", "{", "// Check permission", "if", "(", "!", "$", "this", "->", "canApprove", "(", ")", ")", "{", "return", "Security", "::", "permissionFailure", "(", "null", ",", "_t", "(", "\"UserConfirmationStep.DENYREJECT\"", ",", "\"You do not have permission to reject this deployment\"", ")", ")", ";", "}", "// Skip subsequent approvals if already approved / rejected", "if", "(", "$", "this", "->", "hasResponse", "(", ")", ")", "return", ";", "// Reject", "$", "this", "->", "Approval", "=", "'Rejected'", ";", "$", "this", "->", "log", "(", "\"{$this->Title} has been rejected\"", ")", ";", "$", "this", "->", "ResponderID", "=", "Member", "::", "currentUserID", "(", ")", ";", "$", "this", "->", "markFailed", "(", "false", ")", ";", "$", "this", "->", "sendMessage", "(", "self", "::", "ALERT_REJECT", ")", ";", "return", "true", ";", "}" ]
When the recipient wishes to reject this request @return boolean True if successful
[ "When", "the", "recipient", "wishes", "to", "reject", "this", "request" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/UserConfirmationStep.php#L198-L217
232,810
silverstripe-archive/deploynaut
code/model/steps/UserConfirmationStep.php
UserConfirmationStep.checkStatus
protected function checkStatus() { // For running or queued tasks ensure that we have not exceeded // a reasonable time-elapsed to consider this job inactive if($this->isTimedOut()) { $days = round($this->MaxDuration / (24.0 * 3600.0), 1); $this->log("{$this->Title} took longer than {$this->MaxDuration} seconds ($days days) to be approved and has timed out"); $this->markFailed(); $this->sendMessage(self::ALERT_TIMEOUT); return false; } // If operating on a delayed notification schedule, determine if there are further groups who should be notified if($delay = $this->getConfigSetting('RecipientsDelay')) { // Check group that should have been notified by now $age = $this->getAge(); $escallateGroup = intval($age / $delay); $recipients = $this->getConfigSetting('Recipients'); $lastGroup = count($recipients) - 1; // If we can notify the next group, do so // We only escallate one group at a time to ensure correct order is followed if($this->NotifiedGroup < $lastGroup && $this->NotifiedGroup < $escallateGroup) { $this->NotifiedGroup++; $groupDescription = is_array($recipients[$this->NotifiedGroup]) ? implode(',', $recipients[$this->NotifiedGroup]) : $recipients[$this->NotifiedGroup]; $this->log("Escalating approval request to group {$this->NotifiedGroup}: '$groupDescription'"); // Send to selected group $this->sendMessage(self::ALERT_REQUEST, $this->NotifiedGroup); $this->write(); return true; } } // While still running report no error, waiting for resque job to eventually finish. // Since this could potentially fill the log with hundreds of thousands of messages, // if it takes a few days to get a response, don't write anything. return true; }
php
protected function checkStatus() { // For running or queued tasks ensure that we have not exceeded // a reasonable time-elapsed to consider this job inactive if($this->isTimedOut()) { $days = round($this->MaxDuration / (24.0 * 3600.0), 1); $this->log("{$this->Title} took longer than {$this->MaxDuration} seconds ($days days) to be approved and has timed out"); $this->markFailed(); $this->sendMessage(self::ALERT_TIMEOUT); return false; } // If operating on a delayed notification schedule, determine if there are further groups who should be notified if($delay = $this->getConfigSetting('RecipientsDelay')) { // Check group that should have been notified by now $age = $this->getAge(); $escallateGroup = intval($age / $delay); $recipients = $this->getConfigSetting('Recipients'); $lastGroup = count($recipients) - 1; // If we can notify the next group, do so // We only escallate one group at a time to ensure correct order is followed if($this->NotifiedGroup < $lastGroup && $this->NotifiedGroup < $escallateGroup) { $this->NotifiedGroup++; $groupDescription = is_array($recipients[$this->NotifiedGroup]) ? implode(',', $recipients[$this->NotifiedGroup]) : $recipients[$this->NotifiedGroup]; $this->log("Escalating approval request to group {$this->NotifiedGroup}: '$groupDescription'"); // Send to selected group $this->sendMessage(self::ALERT_REQUEST, $this->NotifiedGroup); $this->write(); return true; } } // While still running report no error, waiting for resque job to eventually finish. // Since this could potentially fill the log with hundreds of thousands of messages, // if it takes a few days to get a response, don't write anything. return true; }
[ "protected", "function", "checkStatus", "(", ")", "{", "// For running or queued tasks ensure that we have not exceeded", "// a reasonable time-elapsed to consider this job inactive", "if", "(", "$", "this", "->", "isTimedOut", "(", ")", ")", "{", "$", "days", "=", "round", "(", "$", "this", "->", "MaxDuration", "/", "(", "24.0", "*", "3600.0", ")", ",", "1", ")", ";", "$", "this", "->", "log", "(", "\"{$this->Title} took longer than {$this->MaxDuration} seconds ($days days) to be approved and has timed out\"", ")", ";", "$", "this", "->", "markFailed", "(", ")", ";", "$", "this", "->", "sendMessage", "(", "self", "::", "ALERT_TIMEOUT", ")", ";", "return", "false", ";", "}", "// If operating on a delayed notification schedule, determine if there are further groups who should be notified", "if", "(", "$", "delay", "=", "$", "this", "->", "getConfigSetting", "(", "'RecipientsDelay'", ")", ")", "{", "// Check group that should have been notified by now", "$", "age", "=", "$", "this", "->", "getAge", "(", ")", ";", "$", "escallateGroup", "=", "intval", "(", "$", "age", "/", "$", "delay", ")", ";", "$", "recipients", "=", "$", "this", "->", "getConfigSetting", "(", "'Recipients'", ")", ";", "$", "lastGroup", "=", "count", "(", "$", "recipients", ")", "-", "1", ";", "// If we can notify the next group, do so", "// We only escallate one group at a time to ensure correct order is followed", "if", "(", "$", "this", "->", "NotifiedGroup", "<", "$", "lastGroup", "&&", "$", "this", "->", "NotifiedGroup", "<", "$", "escallateGroup", ")", "{", "$", "this", "->", "NotifiedGroup", "++", ";", "$", "groupDescription", "=", "is_array", "(", "$", "recipients", "[", "$", "this", "->", "NotifiedGroup", "]", ")", "?", "implode", "(", "','", ",", "$", "recipients", "[", "$", "this", "->", "NotifiedGroup", "]", ")", ":", "$", "recipients", "[", "$", "this", "->", "NotifiedGroup", "]", ";", "$", "this", "->", "log", "(", "\"Escalating approval request to group {$this->NotifiedGroup}: '$groupDescription'\"", ")", ";", "// Send to selected group", "$", "this", "->", "sendMessage", "(", "self", "::", "ALERT_REQUEST", ",", "$", "this", "->", "NotifiedGroup", ")", ";", "$", "this", "->", "write", "(", ")", ";", "return", "true", ";", "}", "}", "// While still running report no error, waiting for resque job to eventually finish.", "// Since this could potentially fill the log with hundreds of thousands of messages,", "// if it takes a few days to get a response, don't write anything.", "return", "true", ";", "}" ]
Report the status of the current request queue and makes sure it hasn't overrun it's time allowed @return boolean True if not failed
[ "Report", "the", "status", "of", "the", "current", "request", "queue", "and", "makes", "sure", "it", "hasn", "t", "overrun", "it", "s", "time", "allowed" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/UserConfirmationStep.php#L224-L262
232,811
silverstripe-archive/deploynaut
code/model/steps/UserConfirmationStep.php
UserConfirmationStep.startApproval
public function startApproval() { $this->Status = 'Started'; $this->log("Starting {$this->Title}..."); // Determine if we should use delayed notification $recipientGroup = 'all'; if($this->getConfigSetting('RecipientsDelay')) { $this->NotifiedGroup = $recipientGroup = 0; } // Send to selected group $this->sendMessage(self::ALERT_REQUEST, $recipientGroup); $this->write(); return true; }
php
public function startApproval() { $this->Status = 'Started'; $this->log("Starting {$this->Title}..."); // Determine if we should use delayed notification $recipientGroup = 'all'; if($this->getConfigSetting('RecipientsDelay')) { $this->NotifiedGroup = $recipientGroup = 0; } // Send to selected group $this->sendMessage(self::ALERT_REQUEST, $recipientGroup); $this->write(); return true; }
[ "public", "function", "startApproval", "(", ")", "{", "$", "this", "->", "Status", "=", "'Started'", ";", "$", "this", "->", "log", "(", "\"Starting {$this->Title}...\"", ")", ";", "// Determine if we should use delayed notification", "$", "recipientGroup", "=", "'all'", ";", "if", "(", "$", "this", "->", "getConfigSetting", "(", "'RecipientsDelay'", ")", ")", "{", "$", "this", "->", "NotifiedGroup", "=", "$", "recipientGroup", "=", "0", ";", "}", "// Send to selected group", "$", "this", "->", "sendMessage", "(", "self", "::", "ALERT_REQUEST", ",", "$", "recipientGroup", ")", ";", "$", "this", "->", "write", "(", ")", ";", "return", "true", ";", "}" ]
Initiate the approval process
[ "Initiate", "the", "approval", "process" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/UserConfirmationStep.php#L267-L279
232,812
silverstripe-archive/deploynaut
code/model/steps/UserConfirmationStep.php
UserConfirmationStep.getReplacements
public function getReplacements() { // Get member who began this request return array_merge( $this->Pipeline()->getReplacements(), array( // Note that this actually displays the link to the interface to approve, // not the direct link to the approve action '<approvelink>' => Director::absoluteURL($this->Pipeline()->Environment()->Link()) ) ); }
php
public function getReplacements() { // Get member who began this request return array_merge( $this->Pipeline()->getReplacements(), array( // Note that this actually displays the link to the interface to approve, // not the direct link to the approve action '<approvelink>' => Director::absoluteURL($this->Pipeline()->Environment()->Link()) ) ); }
[ "public", "function", "getReplacements", "(", ")", "{", "// Get member who began this request", "return", "array_merge", "(", "$", "this", "->", "Pipeline", "(", ")", "->", "getReplacements", "(", ")", ",", "array", "(", "// Note that this actually displays the link to the interface to approve,", "// not the direct link to the approve action", "'<approvelink>'", "=>", "Director", "::", "absoluteURL", "(", "$", "this", "->", "Pipeline", "(", ")", "->", "Environment", "(", ")", "->", "Link", "(", ")", ")", ")", ")", ";", "}" ]
Retrieve message replacements @return array
[ "Retrieve", "message", "replacements" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/UserConfirmationStep.php#L304-L314
232,813
asinfotrack/yii2-toolbox
behaviors/ArchiveBehavior.php
ArchiveBehavior.onBeforeInsert
public function onBeforeInsert() { if ($this->defaultArchiveValue === null || !empty($this->owner->{$this->archiveAttribute})) return; $this->owner->{$this->archiveAttribute} = $this->defaultArchiveValue; }
php
public function onBeforeInsert() { if ($this->defaultArchiveValue === null || !empty($this->owner->{$this->archiveAttribute})) return; $this->owner->{$this->archiveAttribute} = $this->defaultArchiveValue; }
[ "public", "function", "onBeforeInsert", "(", ")", "{", "if", "(", "$", "this", "->", "defaultArchiveValue", "===", "null", "||", "!", "empty", "(", "$", "this", "->", "owner", "->", "{", "$", "this", "->", "archiveAttribute", "}", ")", ")", "return", ";", "$", "this", "->", "owner", "->", "{", "$", "this", "->", "archiveAttribute", "}", "=", "$", "this", "->", "defaultArchiveValue", ";", "}" ]
This method is called before a record is inserted. It sets the column to the default value if there is one specified
[ "This", "method", "is", "called", "before", "a", "record", "is", "inserted", ".", "It", "sets", "the", "column", "to", "the", "default", "value", "if", "there", "is", "one", "specified" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/ArchiveBehavior.php#L74-L78
232,814
juanmf/PdfManager
Fpdi/Traits/FpdiPdfManagerExplodeTrait.php
FpdiPdfManagerExplodeTrait.explode
public function explode($pdf, array $pageRangesLength = array()) { $pdf = $this->getPdfInstance($pdf); if (empty($pageRangesLength)) { $pageRangesLength = array_fill(0, $pdf->getPageCount(), 1); } $pdfs = array(); $offset = 1; foreach ($pageRangesLength as $length) { $pdfs[] = $this->getRange($pdf, $offset, $length); $offset += $length; } return $pdfs; }
php
public function explode($pdf, array $pageRangesLength = array()) { $pdf = $this->getPdfInstance($pdf); if (empty($pageRangesLength)) { $pageRangesLength = array_fill(0, $pdf->getPageCount(), 1); } $pdfs = array(); $offset = 1; foreach ($pageRangesLength as $length) { $pdfs[] = $this->getRange($pdf, $offset, $length); $offset += $length; } return $pdfs; }
[ "public", "function", "explode", "(", "$", "pdf", ",", "array", "$", "pageRangesLength", "=", "array", "(", ")", ")", "{", "$", "pdf", "=", "$", "this", "->", "getPdfInstance", "(", "$", "pdf", ")", ";", "if", "(", "empty", "(", "$", "pageRangesLength", ")", ")", "{", "$", "pageRangesLength", "=", "array_fill", "(", "0", ",", "$", "pdf", "->", "getPageCount", "(", ")", ",", "1", ")", ";", "}", "$", "pdfs", "=", "array", "(", ")", ";", "$", "offset", "=", "1", ";", "foreach", "(", "$", "pageRangesLength", "as", "$", "length", ")", "{", "$", "pdfs", "[", "]", "=", "$", "this", "->", "getRange", "(", "$", "pdf", ",", "$", "offset", ",", "$", "length", ")", ";", "$", "offset", "+=", "$", "length", ";", "}", "return", "$", "pdfs", ";", "}" ]
Divide a pdf into multiple Pdfs, each containing its corresponding number of pages. @param string|Pdf $pdf Could be PDF path or Pdf Object. @param int[] $pageRanges The number of pages each resulting PDF must have. Optional, if not given generates one pdf per page. @return Pdf[] The PDFs
[ "Divide", "a", "pdf", "into", "multiple", "Pdfs", "each", "containing", "its", "corresponding", "number", "of", "pages", "." ]
0b2a199981486a08206d015e7f1e5e26397301f0
https://github.com/juanmf/PdfManager/blob/0b2a199981486a08206d015e7f1e5e26397301f0/Fpdi/Traits/FpdiPdfManagerExplodeTrait.php#L22-L35
232,815
affilinet/productdata-php-sdk
src/Affilinet/ProductData/Requests/ProductsRequest.php
ProductsRequest.findOne
public function findOne($productId) { $this->useAlternateEndpoint = true; $this->queryParams['ProductIds'] = $productId; $this->addAllProductImages(); $this->addAllShopLogos(); $response = $this->send(); $products = $response->getProducts(); if (isset($products[0])) { return $products[0]; } return null; }
php
public function findOne($productId) { $this->useAlternateEndpoint = true; $this->queryParams['ProductIds'] = $productId; $this->addAllProductImages(); $this->addAllShopLogos(); $response = $this->send(); $products = $response->getProducts(); if (isset($products[0])) { return $products[0]; } return null; }
[ "public", "function", "findOne", "(", "$", "productId", ")", "{", "$", "this", "->", "useAlternateEndpoint", "=", "true", ";", "$", "this", "->", "queryParams", "[", "'ProductIds'", "]", "=", "$", "productId", ";", "$", "this", "->", "addAllProductImages", "(", ")", ";", "$", "this", "->", "addAllShopLogos", "(", ")", ";", "$", "response", "=", "$", "this", "->", "send", "(", ")", ";", "$", "products", "=", "$", "response", "->", "getProducts", "(", ")", ";", "if", "(", "isset", "(", "$", "products", "[", "0", "]", ")", ")", "{", "return", "$", "products", "[", "0", "]", ";", "}", "return", "null", ";", "}" ]
Find one Product by Id @param integer $productId @return Product|null
[ "Find", "one", "Product", "by", "Id" ]
fd3979a5b4531ea2140b4202651eca56bab98229
https://github.com/affilinet/productdata-php-sdk/blob/fd3979a5b4531ea2140b4202651eca56bab98229/src/Affilinet/ProductData/Requests/ProductsRequest.php#L57-L70
232,816
affilinet/productdata-php-sdk
src/Affilinet/ProductData/Requests/ProductsRequest.php
ProductsRequest.excludeShopIds
public function excludeShopIds(array $shopIDs) { if (isset($this->queryParams['ShopIdMode']) && $this->queryParams['ShopIdMode'] === 'Include') { throw new AffilinetProductWebserviceException('excludeShopIds() can not be combined with onlyFromShopIds() in one ProductsRequest'); } $this->queryParams['ShopIds'] = $this->getShopIdCSV($shopIDs); $this->queryParams['ShopIdMode'] = 'Exclude'; return $this; }
php
public function excludeShopIds(array $shopIDs) { if (isset($this->queryParams['ShopIdMode']) && $this->queryParams['ShopIdMode'] === 'Include') { throw new AffilinetProductWebserviceException('excludeShopIds() can not be combined with onlyFromShopIds() in one ProductsRequest'); } $this->queryParams['ShopIds'] = $this->getShopIdCSV($shopIDs); $this->queryParams['ShopIdMode'] = 'Exclude'; return $this; }
[ "public", "function", "excludeShopIds", "(", "array", "$", "shopIDs", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "queryParams", "[", "'ShopIdMode'", "]", ")", "&&", "$", "this", "->", "queryParams", "[", "'ShopIdMode'", "]", "===", "'Include'", ")", "{", "throw", "new", "AffilinetProductWebserviceException", "(", "'excludeShopIds() can not be combined with onlyFromShopIds() in one ProductsRequest'", ")", ";", "}", "$", "this", "->", "queryParams", "[", "'ShopIds'", "]", "=", "$", "this", "->", "getShopIdCSV", "(", "$", "shopIDs", ")", ";", "$", "this", "->", "queryParams", "[", "'ShopIdMode'", "]", "=", "'Exclude'", ";", "return", "$", "this", ";", "}" ]
Exclude ShopIDs from result Please note the difference between ShopId and ProgramId: each program (= advertiser) has one ProgramId, but might have more than one ShopId, e.g. if the program supplies its electronics products separately from its clothing products. If one of the specified ShopIds is ‘0’, then the search is performed across all shops with which the requesting publisher has an accepted partners @param array $shopIDs @return ProductsRequest @throws AffilinetProductWebserviceException
[ "Exclude", "ShopIDs", "from", "result" ]
fd3979a5b4531ea2140b4202651eca56bab98229
https://github.com/affilinet/productdata-php-sdk/blob/fd3979a5b4531ea2140b4202651eca56bab98229/src/Affilinet/ProductData/Requests/ProductsRequest.php#L145-L155
232,817
silverstripe-archive/deploynaut
code/model/steps/RollbackStep.php
RollbackStep.doRestoreDB
protected function doRestoreDB() { if ($this->Pipeline()->SkipSnapshot) return false; return $this->getConfigSetting('RestoreDB') && $this->Pipeline()->PreviousSnapshot(); }
php
protected function doRestoreDB() { if ($this->Pipeline()->SkipSnapshot) return false; return $this->getConfigSetting('RestoreDB') && $this->Pipeline()->PreviousSnapshot(); }
[ "protected", "function", "doRestoreDB", "(", ")", "{", "if", "(", "$", "this", "->", "Pipeline", "(", ")", "->", "SkipSnapshot", ")", "return", "false", ";", "return", "$", "this", "->", "getConfigSetting", "(", "'RestoreDB'", ")", "&&", "$", "this", "->", "Pipeline", "(", ")", "->", "PreviousSnapshot", "(", ")", ";", "}" ]
Check if we are intending to restore the DB after this deployment @return boolean
[ "Check", "if", "we", "are", "intending", "to", "restore", "the", "DB", "after", "this", "deployment" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/RollbackStep.php#L221-L225
232,818
silverstripe-archive/deploynaut
code/model/steps/RollbackStep.php
RollbackStep.checkResqueStatus
protected function checkResqueStatus($status) { switch($status) { case "Complete": return true; case "Failed": case "Invalid": $this->log("{$this->Title} failed with task status $status"); $this->markFailed(); return false; case "Queued": case "Running": default: // For running or queued tasks ensure that we have not exceeded // a reasonable time-elapsed to consider this job inactive if($this->isTimedOut()) { $this->log("{$this->Title} took longer than {$this->MaxDuration} seconds to run and has timed out"); $this->markFailed(); return false; } else { // While still running report no error, waiting for resque job to eventually finish // some time in the future $this->log("{$this->Title} is still in progress"); return false; } } }
php
protected function checkResqueStatus($status) { switch($status) { case "Complete": return true; case "Failed": case "Invalid": $this->log("{$this->Title} failed with task status $status"); $this->markFailed(); return false; case "Queued": case "Running": default: // For running or queued tasks ensure that we have not exceeded // a reasonable time-elapsed to consider this job inactive if($this->isTimedOut()) { $this->log("{$this->Title} took longer than {$this->MaxDuration} seconds to run and has timed out"); $this->markFailed(); return false; } else { // While still running report no error, waiting for resque job to eventually finish // some time in the future $this->log("{$this->Title} is still in progress"); return false; } } }
[ "protected", "function", "checkResqueStatus", "(", "$", "status", ")", "{", "switch", "(", "$", "status", ")", "{", "case", "\"Complete\"", ":", "return", "true", ";", "case", "\"Failed\"", ":", "case", "\"Invalid\"", ":", "$", "this", "->", "log", "(", "\"{$this->Title} failed with task status $status\"", ")", ";", "$", "this", "->", "markFailed", "(", ")", ";", "return", "false", ";", "case", "\"Queued\"", ":", "case", "\"Running\"", ":", "default", ":", "// For running or queued tasks ensure that we have not exceeded", "// a reasonable time-elapsed to consider this job inactive", "if", "(", "$", "this", "->", "isTimedOut", "(", ")", ")", "{", "$", "this", "->", "log", "(", "\"{$this->Title} took longer than {$this->MaxDuration} seconds to run and has timed out\"", ")", ";", "$", "this", "->", "markFailed", "(", ")", ";", "return", "false", ";", "}", "else", "{", "// While still running report no error, waiting for resque job to eventually finish", "// some time in the future", "$", "this", "->", "log", "(", "\"{$this->Title} is still in progress\"", ")", ";", "return", "false", ";", "}", "}", "}" ]
Check the status of a resque sub-task @param string $status Resque task status @return boolean True if the task is finished successfully
[ "Check", "the", "status", "of", "a", "resque", "sub", "-", "task" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/steps/RollbackStep.php#L233-L258
232,819
silverstripe-archive/deploynaut
code/model/DNData.php
DNData.setEnvironmentDir
public function setEnvironmentDir($environmentDir) { if($environmentDir[0] != "/") $environmentDir = BASE_PATH . '/' . $environmentDir; $this->environmentDir = realpath($environmentDir) ?: $environmentDir; }
php
public function setEnvironmentDir($environmentDir) { if($environmentDir[0] != "/") $environmentDir = BASE_PATH . '/' . $environmentDir; $this->environmentDir = realpath($environmentDir) ?: $environmentDir; }
[ "public", "function", "setEnvironmentDir", "(", "$", "environmentDir", ")", "{", "if", "(", "$", "environmentDir", "[", "0", "]", "!=", "\"/\"", ")", "$", "environmentDir", "=", "BASE_PATH", ".", "'/'", ".", "$", "environmentDir", ";", "$", "this", "->", "environmentDir", "=", "realpath", "(", "$", "environmentDir", ")", "?", ":", "$", "environmentDir", ";", "}" ]
Set the directory environment code is saved @param string $environmentDir
[ "Set", "the", "directory", "environment", "code", "is", "saved" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNData.php#L80-L83
232,820
silverstripe-archive/deploynaut
code/model/DNData.php
DNData.setKeyDir
public function setKeyDir($keyDir) { if($keyDir[0] != "/") $keyDir = BASE_PATH . '/' . $keyDir; $this->keyDir = realpath($keyDir) ?: $keyDir; }
php
public function setKeyDir($keyDir) { if($keyDir[0] != "/") $keyDir = BASE_PATH . '/' . $keyDir; $this->keyDir = realpath($keyDir) ?: $keyDir; }
[ "public", "function", "setKeyDir", "(", "$", "keyDir", ")", "{", "if", "(", "$", "keyDir", "[", "0", "]", "!=", "\"/\"", ")", "$", "keyDir", "=", "BASE_PATH", ".", "'/'", ".", "$", "keyDir", ";", "$", "this", "->", "keyDir", "=", "realpath", "(", "$", "keyDir", ")", "?", ":", "$", "keyDir", ";", "}" ]
Set the directory where ssh are stored @param string $keyDir
[ "Set", "the", "directory", "where", "ssh", "are", "stored" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNData.php#L99-L102
232,821
silverstripe-archive/deploynaut
code/model/DNData.php
DNData.setDataTransferDir
public function setDataTransferDir($transferDir) { if($transferDir[0] != "/") $transferDir = BASE_PATH . '/' . $transferDir; if(strpos($transferDir, ASSETS_PATH) === false) { throw new LogicException(sprintf( 'DNData::dataTransferDir needs to be located within <webroot>assets/ (location: %s)', $transferDir )); } $this->dataTransferDir = realpath($transferDir) ?: $transferDir; }
php
public function setDataTransferDir($transferDir) { if($transferDir[0] != "/") $transferDir = BASE_PATH . '/' . $transferDir; if(strpos($transferDir, ASSETS_PATH) === false) { throw new LogicException(sprintf( 'DNData::dataTransferDir needs to be located within <webroot>assets/ (location: %s)', $transferDir )); } $this->dataTransferDir = realpath($transferDir) ?: $transferDir; }
[ "public", "function", "setDataTransferDir", "(", "$", "transferDir", ")", "{", "if", "(", "$", "transferDir", "[", "0", "]", "!=", "\"/\"", ")", "$", "transferDir", "=", "BASE_PATH", ".", "'/'", ".", "$", "transferDir", ";", "if", "(", "strpos", "(", "$", "transferDir", ",", "ASSETS_PATH", ")", "===", "false", ")", "{", "throw", "new", "LogicException", "(", "sprintf", "(", "'DNData::dataTransferDir needs to be located within <webroot>assets/ (location: %s)'", ",", "$", "transferDir", ")", ")", ";", "}", "$", "this", "->", "dataTransferDir", "=", "realpath", "(", "$", "transferDir", ")", "?", ":", "$", "transferDir", ";", "}" ]
Set the directory where data transfers should be saved This should either be an absolute path (beginning with /) or a path that can be appended to the web root safely @param string $transferDir
[ "Set", "the", "directory", "where", "data", "transfers", "should", "be", "saved" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNData.php#L139-L148
232,822
silverstripe-archive/deploynaut
code/model/DNData.php
DNData.getProjectPaths
public function getProjectPaths() { $paths = array(); if(!file_exists($this->getEnvironmentDir())) { throw new Exception('The environment directory '.$this->getEnvironmentDir().' doesn\'t exist. Create it first and add some projects to it.'); } foreach(scandir($this->getEnvironmentDir()) as $project) { // Exlcude dot-prefixed directories (.git was getting in the way) if(preg_match('/^[^\.]/', $project)) { $path = $this->getEnvironmentDir().'/'.$project; if(is_dir($path) && $project!='.' && $project!='..') { $paths[] = $project; } } } sort($paths); return array_values($paths); }
php
public function getProjectPaths() { $paths = array(); if(!file_exists($this->getEnvironmentDir())) { throw new Exception('The environment directory '.$this->getEnvironmentDir().' doesn\'t exist. Create it first and add some projects to it.'); } foreach(scandir($this->getEnvironmentDir()) as $project) { // Exlcude dot-prefixed directories (.git was getting in the way) if(preg_match('/^[^\.]/', $project)) { $path = $this->getEnvironmentDir().'/'.$project; if(is_dir($path) && $project!='.' && $project!='..') { $paths[] = $project; } } } sort($paths); return array_values($paths); }
[ "public", "function", "getProjectPaths", "(", ")", "{", "$", "paths", "=", "array", "(", ")", ";", "if", "(", "!", "file_exists", "(", "$", "this", "->", "getEnvironmentDir", "(", ")", ")", ")", "{", "throw", "new", "Exception", "(", "'The environment directory '", ".", "$", "this", "->", "getEnvironmentDir", "(", ")", ".", "' doesn\\'t exist. Create it first and add some projects to it.'", ")", ";", "}", "foreach", "(", "scandir", "(", "$", "this", "->", "getEnvironmentDir", "(", ")", ")", "as", "$", "project", ")", "{", "// Exlcude dot-prefixed directories (.git was getting in the way)", "if", "(", "preg_match", "(", "'/^[^\\.]/'", ",", "$", "project", ")", ")", "{", "$", "path", "=", "$", "this", "->", "getEnvironmentDir", "(", ")", ".", "'/'", ".", "$", "project", ";", "if", "(", "is_dir", "(", "$", "path", ")", "&&", "$", "project", "!=", "'.'", "&&", "$", "project", "!=", "'..'", ")", "{", "$", "paths", "[", "]", "=", "$", "project", ";", "}", "}", "}", "sort", "(", "$", "paths", ")", ";", "return", "array_values", "(", "$", "paths", ")", ";", "}" ]
Grabs a list of projects from the env directory. The projects in the builds directory alone will not be picked up. Returns an array of paths @return array
[ "Grabs", "a", "list", "of", "projects", "from", "the", "env", "directory", ".", "The", "projects", "in", "the", "builds", "directory", "alone", "will", "not", "be", "picked", "up", ".", "Returns", "an", "array", "of", "paths" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNData.php#L165-L181
232,823
silverstripe-archive/deploynaut
code/model/DNData.php
DNData.getEnvironmentPaths
public function getEnvironmentPaths($project) { $baseDir = $this->getEnvironmentDir() . '/' . $project; $paths = array(); if(!file_exists($baseDir)) { throw new Exception('Environment directory '.$baseDir.' doesn\'t exist. Create it first.'); } // Search the directory for config files. foreach(scandir($baseDir) as $environmentFile) { if(preg_match('/\.rb$/', $environmentFile)) { // Config found, wrap it into an object. $paths[] = "$baseDir/$environmentFile"; } } sort($paths); return array_values($paths); }
php
public function getEnvironmentPaths($project) { $baseDir = $this->getEnvironmentDir() . '/' . $project; $paths = array(); if(!file_exists($baseDir)) { throw new Exception('Environment directory '.$baseDir.' doesn\'t exist. Create it first.'); } // Search the directory for config files. foreach(scandir($baseDir) as $environmentFile) { if(preg_match('/\.rb$/', $environmentFile)) { // Config found, wrap it into an object. $paths[] = "$baseDir/$environmentFile"; } } sort($paths); return array_values($paths); }
[ "public", "function", "getEnvironmentPaths", "(", "$", "project", ")", "{", "$", "baseDir", "=", "$", "this", "->", "getEnvironmentDir", "(", ")", ".", "'/'", ".", "$", "project", ";", "$", "paths", "=", "array", "(", ")", ";", "if", "(", "!", "file_exists", "(", "$", "baseDir", ")", ")", "{", "throw", "new", "Exception", "(", "'Environment directory '", ".", "$", "baseDir", ".", "' doesn\\'t exist. Create it first.'", ")", ";", "}", "// Search the directory for config files.", "foreach", "(", "scandir", "(", "$", "baseDir", ")", "as", "$", "environmentFile", ")", "{", "if", "(", "preg_match", "(", "'/\\.rb$/'", ",", "$", "environmentFile", ")", ")", "{", "// Config found, wrap it into an object.", "$", "paths", "[", "]", "=", "\"$baseDir/$environmentFile\"", ";", "}", "}", "sort", "(", "$", "paths", ")", ";", "return", "array_values", "(", "$", "paths", ")", ";", "}" ]
Scan the directory and enumerate all envs founds within. Returns an array of paths
[ "Scan", "the", "directory", "and", "enumerate", "all", "envs", "founds", "within", ".", "Returns", "an", "array", "of", "paths" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNData.php#L187-L203
232,824
asinfotrack/yii2-toolbox
helpers/ComponentConfig.php
ComponentConfig.hasBehavior
public static function hasBehavior($subject, $behavior, $throwException=false) { //only components allowed if (!$subject instanceof \yii\base\Component) { throw new InvalidParamException(Yii::t('app', 'Subject must extend Component')); } //prepare vars $behavior = $behavior instanceof \yii\base\Behavior ? $behavior::className() : $behavior; //check if behavior is attached $found = false; foreach ($subject->behaviors() as $name=>$config) { $className = is_array($config) ? $config['class'] : $config; if (strcmp($className, $behavior) === 0) { $found = true; break; } } if ($throwException && !$found) { $msg = Yii::t('app', '{subject} needs to have behavior {behavior} attached', [ 'subject'=>$subject->className(), 'behavior'=>$behavior, ]); throw new InvalidConfigException($msg); } return $found; }
php
public static function hasBehavior($subject, $behavior, $throwException=false) { //only components allowed if (!$subject instanceof \yii\base\Component) { throw new InvalidParamException(Yii::t('app', 'Subject must extend Component')); } //prepare vars $behavior = $behavior instanceof \yii\base\Behavior ? $behavior::className() : $behavior; //check if behavior is attached $found = false; foreach ($subject->behaviors() as $name=>$config) { $className = is_array($config) ? $config['class'] : $config; if (strcmp($className, $behavior) === 0) { $found = true; break; } } if ($throwException && !$found) { $msg = Yii::t('app', '{subject} needs to have behavior {behavior} attached', [ 'subject'=>$subject->className(), 'behavior'=>$behavior, ]); throw new InvalidConfigException($msg); } return $found; }
[ "public", "static", "function", "hasBehavior", "(", "$", "subject", ",", "$", "behavior", ",", "$", "throwException", "=", "false", ")", "{", "//only components allowed", "if", "(", "!", "$", "subject", "instanceof", "\\", "yii", "\\", "base", "\\", "Component", ")", "{", "throw", "new", "InvalidParamException", "(", "Yii", "::", "t", "(", "'app'", ",", "'Subject must extend Component'", ")", ")", ";", "}", "//prepare vars", "$", "behavior", "=", "$", "behavior", "instanceof", "\\", "yii", "\\", "base", "\\", "Behavior", "?", "$", "behavior", "::", "className", "(", ")", ":", "$", "behavior", ";", "//check if behavior is attached", "$", "found", "=", "false", ";", "foreach", "(", "$", "subject", "->", "behaviors", "(", ")", "as", "$", "name", "=>", "$", "config", ")", "{", "$", "className", "=", "is_array", "(", "$", "config", ")", "?", "$", "config", "[", "'class'", "]", ":", "$", "config", ";", "if", "(", "strcmp", "(", "$", "className", ",", "$", "behavior", ")", "===", "0", ")", "{", "$", "found", "=", "true", ";", "break", ";", "}", "}", "if", "(", "$", "throwException", "&&", "!", "$", "found", ")", "{", "$", "msg", "=", "Yii", "::", "t", "(", "'app'", ",", "'{subject} needs to have behavior {behavior} attached'", ",", "[", "'subject'", "=>", "$", "subject", "->", "className", "(", ")", ",", "'behavior'", "=>", "$", "behavior", ",", "]", ")", ";", "throw", "new", "InvalidConfigException", "(", "$", "msg", ")", ";", "}", "return", "$", "found", ";", "}" ]
Checks whether or not a subject has a behavior of a certain type attached. @param \yii\base\Component $subject the subject to check @param string|\yii\base\Behavior $behavior either the class name or an instance of the behavior @param bool $throwException if set to true, an exception will be thrown if the subject doesn't have the behavior attached @return bool true if attached @throws \yii\base\InvalidParamException when subject is of wrong type @throws \yii\base\InvalidConfigException if desired and behavior missing
[ "Checks", "whether", "or", "not", "a", "subject", "has", "a", "behavior", "of", "a", "certain", "type", "attached", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ComponentConfig.php#L29-L58
232,825
asinfotrack/yii2-toolbox
helpers/ComponentConfig.php
ComponentConfig.isActiveRecord
public static function isActiveRecord($object, $throwException=false) { if ($object instanceof \yii\db\ActiveRecord) return true; if ($throwException) { $msg = Yii::t('app', 'Object {obj} does not extend ActiveRecord', ['obj'=>get_class($object)]); throw new InvalidConfigException($msg); } return false; }
php
public static function isActiveRecord($object, $throwException=false) { if ($object instanceof \yii\db\ActiveRecord) return true; if ($throwException) { $msg = Yii::t('app', 'Object {obj} does not extend ActiveRecord', ['obj'=>get_class($object)]); throw new InvalidConfigException($msg); } return false; }
[ "public", "static", "function", "isActiveRecord", "(", "$", "object", ",", "$", "throwException", "=", "false", ")", "{", "if", "(", "$", "object", "instanceof", "\\", "yii", "\\", "db", "\\", "ActiveRecord", ")", "return", "true", ";", "if", "(", "$", "throwException", ")", "{", "$", "msg", "=", "Yii", "::", "t", "(", "'app'", ",", "'Object {obj} does not extend ActiveRecord'", ",", "[", "'obj'", "=>", "get_class", "(", "$", "object", ")", "]", ")", ";", "throw", "new", "InvalidConfigException", "(", "$", "msg", ")", ";", "}", "return", "false", ";", "}" ]
Checks whether or not an object is of type active record @param mixed $object the object to check @param bool $throwException whether or not to throw an exception @return bool true if of type active record @throws \yii\base\InvalidConfigException
[ "Checks", "whether", "or", "not", "an", "object", "is", "of", "type", "active", "record" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ComponentConfig.php#L68-L77
232,826
stephanecoinon/papertrail
src/Laravel.php
Laravel.getLogger
public function getLogger() { $logger = app('log'); // Laravel < 5.6 if ($logger instanceof \Illuminate\Log\Writer) { return $logger->getMonolog(); } // Laravel >= 5.6 return $logger->getLogger(); }
php
public function getLogger() { $logger = app('log'); // Laravel < 5.6 if ($logger instanceof \Illuminate\Log\Writer) { return $logger->getMonolog(); } // Laravel >= 5.6 return $logger->getLogger(); }
[ "public", "function", "getLogger", "(", ")", "{", "$", "logger", "=", "app", "(", "'log'", ")", ";", "// Laravel < 5.6", "if", "(", "$", "logger", "instanceof", "\\", "Illuminate", "\\", "Log", "\\", "Writer", ")", "{", "return", "$", "logger", "->", "getMonolog", "(", ")", ";", "}", "// Laravel >= 5.6", "return", "$", "logger", "->", "getLogger", "(", ")", ";", "}" ]
Get the logger instance. @return \Psr\Log\LoggerInterface
[ "Get", "the", "logger", "instance", "." ]
b1d1771b21f65427701e6d5eb8515c7cd17a8e56
https://github.com/stephanecoinon/papertrail/blob/b1d1771b21f65427701e6d5eb8515c7cd17a8e56/src/Laravel.php#L38-L49
232,827
ibmjstart/wp-bluemix-objectstorage
classes/swift.php
Swift.swift_get_attachment_folder_time
function swift_get_attachment_folder_time( $post_id ) { $time = current_time( 'timestamp' ); if ( !( $attach = get_post( $post_id ) ) ) { return $time; } if ( !$attach->post_parent ) { return $time; } if ( !( $post = get_post( $attach->post_parent ) ) ) { return $time; } if ( substr( $post->post_date_gmt, 0, 4 ) > 0 ) { return strtotime( $post->post_date_gmt . ' +0000' ); } return $time; }
php
function swift_get_attachment_folder_time( $post_id ) { $time = current_time( 'timestamp' ); if ( !( $attach = get_post( $post_id ) ) ) { return $time; } if ( !$attach->post_parent ) { return $time; } if ( !( $post = get_post( $attach->post_parent ) ) ) { return $time; } if ( substr( $post->post_date_gmt, 0, 4 ) > 0 ) { return strtotime( $post->post_date_gmt . ' +0000' ); } return $time; }
[ "function", "swift_get_attachment_folder_time", "(", "$", "post_id", ")", "{", "$", "time", "=", "current_time", "(", "'timestamp'", ")", ";", "if", "(", "!", "(", "$", "attach", "=", "get_post", "(", "$", "post_id", ")", ")", ")", "{", "return", "$", "time", ";", "}", "if", "(", "!", "$", "attach", "->", "post_parent", ")", "{", "return", "$", "time", ";", "}", "if", "(", "!", "(", "$", "post", "=", "get_post", "(", "$", "attach", "->", "post_parent", ")", ")", ")", "{", "return", "$", "time", ";", "}", "if", "(", "substr", "(", "$", "post", "->", "post_date_gmt", ",", "0", ",", "4", ")", ">", "0", ")", "{", "return", "strtotime", "(", "$", "post", "->", "post_date_gmt", ".", "' +0000'", ")", ";", "}", "return", "$", "time", ";", "}" ]
to determine the folder path they are placed in
[ "to", "determine", "the", "folder", "path", "they", "are", "placed", "in" ]
e83a80c783dc3749a91955495998bca942a7bfdc
https://github.com/ibmjstart/wp-bluemix-objectstorage/blob/e83a80c783dc3749a91955495998bca942a7bfdc/classes/swift.php#L316-L336
232,828
ibmjstart/wp-bluemix-objectstorage
classes/swift.php
Swift.swift_get_secure_attachment_url
function swift_get_secure_attachment_url( $post_id, $expires = 900, $size = null ) { return $this->swift_get_attachment_url( $post_id, $expires, $size = null ); }
php
function swift_get_secure_attachment_url( $post_id, $expires = 900, $size = null ) { return $this->swift_get_attachment_url( $post_id, $expires, $size = null ); }
[ "function", "swift_get_secure_attachment_url", "(", "$", "post_id", ",", "$", "expires", "=", "900", ",", "$", "size", "=", "null", ")", "{", "return", "$", "this", "->", "swift_get_attachment_url", "(", "$", "post_id", ",", "$", "expires", ",", "$", "size", "=", "null", ")", ";", "}" ]
Generate a link to download a file from Softlayer Swift using query string authentication. @param mixed $post_id Post ID of the attachment or null to use the loop @param int $expires Seconds for the link to live
[ "Generate", "a", "link", "to", "download", "a", "file", "from", "Softlayer", "Swift", "using", "query", "string", "authentication", "." ]
e83a80c783dc3749a91955495998bca942a7bfdc
https://github.com/ibmjstart/wp-bluemix-objectstorage/blob/e83a80c783dc3749a91955495998bca942a7bfdc/classes/swift.php#L365-L367
232,829
ibmjstart/wp-bluemix-objectstorage
classes/swift.php
Swift.swift_get_base_upload_path
function swift_get_base_upload_path() { if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) { return ABSPATH . UPLOADS; } $upload_path = trim( get_option( 'upload_path' ) ); if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) { return WP_CONTENT_DIR . '/uploads'; } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) { // $dir is absolute, $upload_path is (maybe) relative to ABSPATH return path_join( ABSPATH, $upload_path ); } else { return $upload_path; } }
php
function swift_get_base_upload_path() { if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) { return ABSPATH . UPLOADS; } $upload_path = trim( get_option( 'upload_path' ) ); if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) { return WP_CONTENT_DIR . '/uploads'; } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) { // $dir is absolute, $upload_path is (maybe) relative to ABSPATH return path_join( ABSPATH, $upload_path ); } else { return $upload_path; } }
[ "function", "swift_get_base_upload_path", "(", ")", "{", "if", "(", "defined", "(", "'UPLOADS'", ")", "&&", "!", "(", "is_multisite", "(", ")", "&&", "get_site_option", "(", "'ms_files_rewriting'", ")", ")", ")", "{", "return", "ABSPATH", ".", "UPLOADS", ";", "}", "$", "upload_path", "=", "trim", "(", "get_option", "(", "'upload_path'", ")", ")", ";", "if", "(", "empty", "(", "$", "upload_path", ")", "||", "'wp-content/uploads'", "==", "$", "upload_path", ")", "{", "return", "WP_CONTENT_DIR", ".", "'/uploads'", ";", "}", "elseif", "(", "0", "!==", "strpos", "(", "$", "upload_path", ",", "ABSPATH", ")", ")", "{", "// $dir is absolute, $upload_path is (maybe) relative to ABSPATH", "return", "path_join", "(", "ABSPATH", ",", "$", "upload_path", ")", ";", "}", "else", "{", "return", "$", "upload_path", ";", "}", "}" ]
Without the multisite subdirectory
[ "Without", "the", "multisite", "subdirectory" ]
e83a80c783dc3749a91955495998bca942a7bfdc
https://github.com/ibmjstart/wp-bluemix-objectstorage/blob/e83a80c783dc3749a91955495998bca942a7bfdc/classes/swift.php#L569-L584
232,830
ibmjstart/wp-bluemix-objectstorage
classes/swift.php
Swift.wp_calculate_image_srcset
public function wp_calculate_image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ) { foreach ( $sources as $width => $source ) { $size = $this->find_image_size_from_width( $image_meta['sizes'], $width ); $OS_url = $this->swift_get_attachment_url( $attachment_id, null, $size ); if ( false === $OS_url || is_wp_error( $OS_url ) ) { continue; } $sources[ $width ]['url'] = $OS_url; } return $sources; }
php
public function wp_calculate_image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ) { foreach ( $sources as $width => $source ) { $size = $this->find_image_size_from_width( $image_meta['sizes'], $width ); $OS_url = $this->swift_get_attachment_url( $attachment_id, null, $size ); if ( false === $OS_url || is_wp_error( $OS_url ) ) { continue; } $sources[ $width ]['url'] = $OS_url; } return $sources; }
[ "public", "function", "wp_calculate_image_srcset", "(", "$", "sources", ",", "$", "size_array", ",", "$", "image_src", ",", "$", "image_meta", ",", "$", "attachment_id", ")", "{", "foreach", "(", "$", "sources", "as", "$", "width", "=>", "$", "source", ")", "{", "$", "size", "=", "$", "this", "->", "find_image_size_from_width", "(", "$", "image_meta", "[", "'sizes'", "]", ",", "$", "width", ")", ";", "$", "OS_url", "=", "$", "this", "->", "swift_get_attachment_url", "(", "$", "attachment_id", ",", "null", ",", "$", "size", ")", ";", "if", "(", "false", "===", "$", "OS_url", "||", "is_wp_error", "(", "$", "OS_url", ")", ")", "{", "continue", ";", "}", "$", "sources", "[", "$", "width", "]", "[", "'url'", "]", "=", "$", "OS_url", ";", "}", "return", "$", "sources", ";", "}" ]
Replace local URLs with object storage ones for srcset image sources @param array $sources @param array $size_array @param string $image_src @param array $image_meta @param int $attachment_id @return array
[ "Replace", "local", "URLs", "with", "object", "storage", "ones", "for", "srcset", "image", "sources" ]
e83a80c783dc3749a91955495998bca942a7bfdc
https://github.com/ibmjstart/wp-bluemix-objectstorage/blob/e83a80c783dc3749a91955495998bca942a7bfdc/classes/swift.php#L597-L607
232,831
ibmjstart/wp-bluemix-objectstorage
classes/swift.php
Swift.find_image_size_from_width
protected function find_image_size_from_width( $sizes, $width ) { foreach ( $sizes as $name => $size ) { if ( $width === $size['width'] ) { return $name; } } return null; }
php
protected function find_image_size_from_width( $sizes, $width ) { foreach ( $sizes as $name => $size ) { if ( $width === $size['width'] ) { return $name; } } return null; }
[ "protected", "function", "find_image_size_from_width", "(", "$", "sizes", ",", "$", "width", ")", "{", "foreach", "(", "$", "sizes", "as", "$", "name", "=>", "$", "size", ")", "{", "if", "(", "$", "width", "===", "$", "size", "[", "'width'", "]", ")", "{", "return", "$", "name", ";", "}", "}", "return", "null", ";", "}" ]
Helper function to find size name from width @param array $sizes @param string $width @return null|string
[ "Helper", "function", "to", "find", "size", "name", "from", "width" ]
e83a80c783dc3749a91955495998bca942a7bfdc
https://github.com/ibmjstart/wp-bluemix-objectstorage/blob/e83a80c783dc3749a91955495998bca942a7bfdc/classes/swift.php#L617-L624
232,832
silverstripe-archive/deploynaut
code/model/DNReferenceList.php
DNReferenceList.byName
public function byName($hash) { if($this->loaded == false) { $this->items = $this->getReferences(); $this->loaded = true; } // The item might not be in the list because of the limit, try to find // in an older version and add it to the list. if(!isset($this->items[$hash])) { $repository = new Gitonomy\Git\Repository($this->project->LocalCVSPath); $commit = new Gitonomy\Git\Commit($repository, $hash); $this->items[$hash] = DNCommit::create($commit, $this->project, $this->data); }; return $this->items[$hash]; }
php
public function byName($hash) { if($this->loaded == false) { $this->items = $this->getReferences(); $this->loaded = true; } // The item might not be in the list because of the limit, try to find // in an older version and add it to the list. if(!isset($this->items[$hash])) { $repository = new Gitonomy\Git\Repository($this->project->LocalCVSPath); $commit = new Gitonomy\Git\Commit($repository, $hash); $this->items[$hash] = DNCommit::create($commit, $this->project, $this->data); }; return $this->items[$hash]; }
[ "public", "function", "byName", "(", "$", "hash", ")", "{", "if", "(", "$", "this", "->", "loaded", "==", "false", ")", "{", "$", "this", "->", "items", "=", "$", "this", "->", "getReferences", "(", ")", ";", "$", "this", "->", "loaded", "=", "true", ";", "}", "// The item might not be in the list because of the limit, try to find", "// in an older version and add it to the list.", "if", "(", "!", "isset", "(", "$", "this", "->", "items", "[", "$", "hash", "]", ")", ")", "{", "$", "repository", "=", "new", "Gitonomy", "\\", "Git", "\\", "Repository", "(", "$", "this", "->", "project", "->", "LocalCVSPath", ")", ";", "$", "commit", "=", "new", "Gitonomy", "\\", "Git", "\\", "Commit", "(", "$", "repository", ",", "$", "hash", ")", ";", "$", "this", "->", "items", "[", "$", "hash", "]", "=", "DNCommit", "::", "create", "(", "$", "commit", ",", "$", "this", "->", "project", ",", "$", "this", "->", "data", ")", ";", "}", ";", "return", "$", "this", "->", "items", "[", "$", "hash", "]", ";", "}" ]
Find a build in this set by hash.
[ "Find", "a", "build", "in", "this", "set", "by", "hash", "." ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/model/DNReferenceList.php#L110-L124
232,833
lamoni/netconf
src/NetConfAuth/NetConfAuthAbstract.php
NetConfAuthAbstract.validateAuthParams
public function validateAuthParams(array $authParams, array $acceptableParams) { foreach ($authParams as $paramName=>$paramValue) { if (!isset($acceptableParams[$paramName])) { throw new \Exception(get_class().": Unacceptable authParam: {$paramName}"); } // Try resolving to class method first, then try resolving to global function if (method_exists($this, $acceptableParams[$paramName])) { $validationPassed = $this->$acceptableParams[$paramName]($paramValue); } elseif (function_exists($acceptableParams[$paramName])) { $validationPassed = $acceptableParams[$paramName]($paramValue); } else { throw new \Exception(get_class().": authParam validator not found: {$paramName}"); } if (!$validationPassed) { throw new \Exception(get_class().": Failed authParam validation: {$paramName}"); } } }
php
public function validateAuthParams(array $authParams, array $acceptableParams) { foreach ($authParams as $paramName=>$paramValue) { if (!isset($acceptableParams[$paramName])) { throw new \Exception(get_class().": Unacceptable authParam: {$paramName}"); } // Try resolving to class method first, then try resolving to global function if (method_exists($this, $acceptableParams[$paramName])) { $validationPassed = $this->$acceptableParams[$paramName]($paramValue); } elseif (function_exists($acceptableParams[$paramName])) { $validationPassed = $acceptableParams[$paramName]($paramValue); } else { throw new \Exception(get_class().": authParam validator not found: {$paramName}"); } if (!$validationPassed) { throw new \Exception(get_class().": Failed authParam validation: {$paramName}"); } } }
[ "public", "function", "validateAuthParams", "(", "array", "$", "authParams", ",", "array", "$", "acceptableParams", ")", "{", "foreach", "(", "$", "authParams", "as", "$", "paramName", "=>", "$", "paramValue", ")", "{", "if", "(", "!", "isset", "(", "$", "acceptableParams", "[", "$", "paramName", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "get_class", "(", ")", ".", "\": Unacceptable authParam: {$paramName}\"", ")", ";", "}", "// Try resolving to class method first, then try resolving to global function", "if", "(", "method_exists", "(", "$", "this", ",", "$", "acceptableParams", "[", "$", "paramName", "]", ")", ")", "{", "$", "validationPassed", "=", "$", "this", "->", "$", "acceptableParams", "[", "$", "paramName", "]", "(", "$", "paramValue", ")", ";", "}", "elseif", "(", "function_exists", "(", "$", "acceptableParams", "[", "$", "paramName", "]", ")", ")", "{", "$", "validationPassed", "=", "$", "acceptableParams", "[", "$", "paramName", "]", "(", "$", "paramValue", ")", ";", "}", "else", "{", "throw", "new", "\\", "Exception", "(", "get_class", "(", ")", ".", "\": authParam validator not found: {$paramName}\"", ")", ";", "}", "if", "(", "!", "$", "validationPassed", ")", "{", "throw", "new", "\\", "Exception", "(", "get_class", "(", ")", ".", "\": Failed authParam validation: {$paramName}\"", ")", ";", "}", "}", "}" ]
All children will need this to validate the passed inputs against our defined inputs @param array $authParams @param array $acceptableParams @throws \Exception
[ "All", "children", "will", "need", "this", "to", "validate", "the", "passed", "inputs", "against", "our", "defined", "inputs" ]
e0ee6cd792e75f15163e51e70b293dba2b8ee4b4
https://github.com/lamoni/netconf/blob/e0ee6cd792e75f15163e51e70b293dba2b8ee4b4/src/NetConfAuth/NetConfAuthAbstract.php#L41-L64
232,834
mcustiel/php-simple-request
src/Util/AnnotationToImplementationBuilder.php
AnnotationToImplementationBuilder.build
public function build() { $class = $this->getClassForType($this->type); $validator = new $class; $validator->setSpecification($this->specification); return $validator; }
php
public function build() { $class = $this->getClassForType($this->type); $validator = new $class; $validator->setSpecification($this->specification); return $validator; }
[ "public", "function", "build", "(", ")", "{", "$", "class", "=", "$", "this", "->", "getClassForType", "(", "$", "this", "->", "type", ")", ";", "$", "validator", "=", "new", "$", "class", ";", "$", "validator", "->", "setSpecification", "(", "$", "this", "->", "specification", ")", ";", "return", "$", "validator", ";", "}" ]
Builds the object from the given specification. @return \Mcustiel\SimpleRequest\Interfaces\FilterInterface|\Mcustiel\SimpleRequest\Interfaces\ValidatorInterface
[ "Builds", "the", "object", "from", "the", "given", "specification", "." ]
4d0fc06092ccdff3ea488c67b394225c7243428f
https://github.com/mcustiel/php-simple-request/blob/4d0fc06092ccdff3ea488c67b394225c7243428f/src/Util/AnnotationToImplementationBuilder.php#L78-L85
232,835
pstaender/silverstripe-restful-api
code/model/ApiDataObject.php
ApiDataObject.inheritedApiFields
function inheritedApiFields() { $fields = array(); $currentObj = $this->owner->class; while($currentObj != 'DataObject') { $apiFields = singleton($currentObj)->stat('api_fields'); if ($apiFields === null) { $apiFields = Config::inst()->get($this->owner->class, 'db', Config::INHERITED);//$this->owner->stat('db'); $fields['ID'] = 'ID'; // we have to add manually 'ID' $fields['ClassName'] = 'ClassName'; $fields['Created'] = 'Created'; $fields['LastEdited'] = 'LastEdited'; if (is_array($apiFields)) foreach ($apiFields as $field => $type) { $fields[$field] = $field; } } else if (is_array($apiFields)) { $fields = array_merge($fields, $apiFields); } $currentObj = get_parent_class($currentObj); } return array_unique($fields); }
php
function inheritedApiFields() { $fields = array(); $currentObj = $this->owner->class; while($currentObj != 'DataObject') { $apiFields = singleton($currentObj)->stat('api_fields'); if ($apiFields === null) { $apiFields = Config::inst()->get($this->owner->class, 'db', Config::INHERITED);//$this->owner->stat('db'); $fields['ID'] = 'ID'; // we have to add manually 'ID' $fields['ClassName'] = 'ClassName'; $fields['Created'] = 'Created'; $fields['LastEdited'] = 'LastEdited'; if (is_array($apiFields)) foreach ($apiFields as $field => $type) { $fields[$field] = $field; } } else if (is_array($apiFields)) { $fields = array_merge($fields, $apiFields); } $currentObj = get_parent_class($currentObj); } return array_unique($fields); }
[ "function", "inheritedApiFields", "(", ")", "{", "$", "fields", "=", "array", "(", ")", ";", "$", "currentObj", "=", "$", "this", "->", "owner", "->", "class", ";", "while", "(", "$", "currentObj", "!=", "'DataObject'", ")", "{", "$", "apiFields", "=", "singleton", "(", "$", "currentObj", ")", "->", "stat", "(", "'api_fields'", ")", ";", "if", "(", "$", "apiFields", "===", "null", ")", "{", "$", "apiFields", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "$", "this", "->", "owner", "->", "class", ",", "'db'", ",", "Config", "::", "INHERITED", ")", ";", "//$this->owner->stat('db');", "$", "fields", "[", "'ID'", "]", "=", "'ID'", ";", "// we have to add manually 'ID'", "$", "fields", "[", "'ClassName'", "]", "=", "'ClassName'", ";", "$", "fields", "[", "'Created'", "]", "=", "'Created'", ";", "$", "fields", "[", "'LastEdited'", "]", "=", "'LastEdited'", ";", "if", "(", "is_array", "(", "$", "apiFields", ")", ")", "foreach", "(", "$", "apiFields", "as", "$", "field", "=>", "$", "type", ")", "{", "$", "fields", "[", "$", "field", "]", "=", "$", "field", ";", "}", "}", "else", "if", "(", "is_array", "(", "$", "apiFields", ")", ")", "{", "$", "fields", "=", "array_merge", "(", "$", "fields", ",", "$", "apiFields", ")", ";", "}", "$", "currentObj", "=", "get_parent_class", "(", "$", "currentObj", ")", ";", "}", "return", "array_unique", "(", "$", "fields", ")", ";", "}" ]
Array of inherited static desriptions of `api_fields` Copied from @DataOject->inheritedDatabaseFields() @return array fields
[ "Array", "of", "inherited", "static", "desriptions", "of", "api_fields", "Copied", "from" ]
658c840ae88bf823da1116726081eee82fb6a435
https://github.com/pstaender/silverstripe-restful-api/blob/658c840ae88bf823da1116726081eee82fb6a435/code/model/ApiDataObject.php#L81-L105
232,836
markant-norge/php-bring-api
src/Contract/ApiEntity.php
ApiEntity.addData
protected function addData($key, $value) { if (!isset($this->_data[$key]) || !is_array($this->_data[$key])) { $this->_data[$key] = []; } $this->_data[$key][] = $value; return $this; }
php
protected function addData($key, $value) { if (!isset($this->_data[$key]) || !is_array($this->_data[$key])) { $this->_data[$key] = []; } $this->_data[$key][] = $value; return $this; }
[ "protected", "function", "addData", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_data", "[", "$", "key", "]", ")", "||", "!", "is_array", "(", "$", "this", "->", "_data", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "_data", "[", "$", "key", "]", "=", "[", "]", ";", "}", "$", "this", "->", "_data", "[", "$", "key", "]", "[", "]", "=", "$", "value", ";", "return", "$", "this", ";", "}" ]
Adds data to data array @param $key Identifier. @param $value Value to add @return $this
[ "Adds", "data", "to", "data", "array" ]
d4eecd40f8c2931d2c22f399e02577c74f573f1c
https://github.com/markant-norge/php-bring-api/blob/d4eecd40f8c2931d2c22f399e02577c74f573f1c/src/Contract/ApiEntity.php#L54-L60
232,837
markant-norge/php-bring-api
src/Contract/ApiEntity.php
ApiEntity.dataToArray
protected function dataToArray (array $data) { $result = []; foreach ($data as $key => $value) { if ($value instanceof ApiEntity) { $result[$key] = $value->toArray(); } else if (is_array($value)) { $result[$key] = $this->dataToArray($value); } else { $result[$key] = $value; } } return $result; }
php
protected function dataToArray (array $data) { $result = []; foreach ($data as $key => $value) { if ($value instanceof ApiEntity) { $result[$key] = $value->toArray(); } else if (is_array($value)) { $result[$key] = $this->dataToArray($value); } else { $result[$key] = $value; } } return $result; }
[ "protected", "function", "dataToArray", "(", "array", "$", "data", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "value", "instanceof", "ApiEntity", ")", "{", "$", "result", "[", "$", "key", "]", "=", "$", "value", "->", "toArray", "(", ")", ";", "}", "else", "if", "(", "is_array", "(", "$", "value", ")", ")", "{", "$", "result", "[", "$", "key", "]", "=", "$", "this", "->", "dataToArray", "(", "$", "value", ")", ";", "}", "else", "{", "$", "result", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "result", ";", "}" ]
Recursively serialize data and ApiEntity instances. @param array $data Array of data @return array Serialized array
[ "Recursively", "serialize", "data", "and", "ApiEntity", "instances", "." ]
d4eecd40f8c2931d2c22f399e02577c74f573f1c
https://github.com/markant-norge/php-bring-api/blob/d4eecd40f8c2931d2c22f399e02577c74f573f1c/src/Contract/ApiEntity.php#L111-L123
232,838
silverstripe-archive/deploynaut
code/backends/SizeRestrictedPackageCache.php
SizeRestrictedPackageCache.getPackageFilename
public function getPackageFilename(PackageGenerator $generator, $identifier, $sha, $repositoryDir, DeploynautLogFile $log) { if(!$this->baseDir) throw new \LogicException("Can't use PackageCache without setting BaseDir"); $buildPath = $this->baseDir . '/' . $this->sanitiseDirName($identifier); $filename = "$buildPath/$sha.tar.gz"; if(!file_exists($this->baseDir)) { if(!mkdir($this->baseDir)) throw new \LogicException("Can't create base dir {$this->baseDir}"); } if(!file_exists($buildPath)) { if(!mkdir($buildPath)) throw new \LogicException("Can't create build path $buildPath"); } if(file_exists($filename)) { $log->write("Using previously generated package $filename"); // This will ensure that our cache garbage collection will remove least-recently-accessed, // rather than oldest. touch($filename); return $filename; } else { if($this->cacheSize) $this->reduceDirSizeTo($buildPath, $this->cacheSize-1, $log); if($generator->generatePackage($sha, $repositoryDir, $filename, $log)) { return $filename; } } }
php
public function getPackageFilename(PackageGenerator $generator, $identifier, $sha, $repositoryDir, DeploynautLogFile $log) { if(!$this->baseDir) throw new \LogicException("Can't use PackageCache without setting BaseDir"); $buildPath = $this->baseDir . '/' . $this->sanitiseDirName($identifier); $filename = "$buildPath/$sha.tar.gz"; if(!file_exists($this->baseDir)) { if(!mkdir($this->baseDir)) throw new \LogicException("Can't create base dir {$this->baseDir}"); } if(!file_exists($buildPath)) { if(!mkdir($buildPath)) throw new \LogicException("Can't create build path $buildPath"); } if(file_exists($filename)) { $log->write("Using previously generated package $filename"); // This will ensure that our cache garbage collection will remove least-recently-accessed, // rather than oldest. touch($filename); return $filename; } else { if($this->cacheSize) $this->reduceDirSizeTo($buildPath, $this->cacheSize-1, $log); if($generator->generatePackage($sha, $repositoryDir, $filename, $log)) { return $filename; } } }
[ "public", "function", "getPackageFilename", "(", "PackageGenerator", "$", "generator", ",", "$", "identifier", ",", "$", "sha", ",", "$", "repositoryDir", ",", "DeploynautLogFile", "$", "log", ")", "{", "if", "(", "!", "$", "this", "->", "baseDir", ")", "throw", "new", "\\", "LogicException", "(", "\"Can't use PackageCache without setting BaseDir\"", ")", ";", "$", "buildPath", "=", "$", "this", "->", "baseDir", ".", "'/'", ".", "$", "this", "->", "sanitiseDirName", "(", "$", "identifier", ")", ";", "$", "filename", "=", "\"$buildPath/$sha.tar.gz\"", ";", "if", "(", "!", "file_exists", "(", "$", "this", "->", "baseDir", ")", ")", "{", "if", "(", "!", "mkdir", "(", "$", "this", "->", "baseDir", ")", ")", "throw", "new", "\\", "LogicException", "(", "\"Can't create base dir {$this->baseDir}\"", ")", ";", "}", "if", "(", "!", "file_exists", "(", "$", "buildPath", ")", ")", "{", "if", "(", "!", "mkdir", "(", "$", "buildPath", ")", ")", "throw", "new", "\\", "LogicException", "(", "\"Can't create build path $buildPath\"", ")", ";", "}", "if", "(", "file_exists", "(", "$", "filename", ")", ")", "{", "$", "log", "->", "write", "(", "\"Using previously generated package $filename\"", ")", ";", "// This will ensure that our cache garbage collection will remove least-recently-accessed,", "// rather than oldest.", "touch", "(", "$", "filename", ")", ";", "return", "$", "filename", ";", "}", "else", "{", "if", "(", "$", "this", "->", "cacheSize", ")", "$", "this", "->", "reduceDirSizeTo", "(", "$", "buildPath", ",", "$", "this", "->", "cacheSize", "-", "1", ",", "$", "log", ")", ";", "if", "(", "$", "generator", "->", "generatePackage", "(", "$", "sha", ",", "$", "repositoryDir", ",", "$", "filename", ",", "$", "log", ")", ")", "{", "return", "$", "filename", ";", "}", "}", "}" ]
Return the filename of the generated package, retrieving from cache or generating as necessary @param PackageGenerator $generator The generator to use to create cache entries. @param string $identifier A unique identifier for the generator; used to partition the cache @param string $sha The SHA of the commit to be deployed @param string $repositoryDir The directory where the repository resides @param DeploynautLogFile $log The log to write status output to, including package-generation commands
[ "Return", "the", "filename", "of", "the", "generated", "package", "retrieving", "from", "cache", "or", "generating", "as", "necessary" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/backends/SizeRestrictedPackageCache.php#L43-L70
232,839
phillies2k/ratchet-bundle
WebSocket/Connection/Connection.php
Connection.broadcast
public function broadcast(Payload $payload) { foreach ($this->connectionManager->getConnections() as $connection) { if ($connection->getId() !== $this->getId()) { $connection->emit($payload); } } }
php
public function broadcast(Payload $payload) { foreach ($this->connectionManager->getConnections() as $connection) { if ($connection->getId() !== $this->getId()) { $connection->emit($payload); } } }
[ "public", "function", "broadcast", "(", "Payload", "$", "payload", ")", "{", "foreach", "(", "$", "this", "->", "connectionManager", "->", "getConnections", "(", ")", "as", "$", "connection", ")", "{", "if", "(", "$", "connection", "->", "getId", "(", ")", "!==", "$", "this", "->", "getId", "(", ")", ")", "{", "$", "connection", "->", "emit", "(", "$", "payload", ")", ";", "}", "}", "}" ]
Broadcasts an event to all @param Payload $payload @return mixed
[ "Broadcasts", "an", "event", "to", "all" ]
1ea60f42d04c6e5e2c63c7f8c53262d382b0b5f3
https://github.com/phillies2k/ratchet-bundle/blob/1ea60f42d04c6e5e2c63c7f8c53262d382b0b5f3/WebSocket/Connection/Connection.php#L105-L112
232,840
asinfotrack/yii2-toolbox
helpers/Timestamp.php
Timestamp.makeMidnight
public static function makeMidnight($timestamp, $timezone=null) { $tz = new DateTimeZone($timezone !== null ? $timezone : Yii::$app->timeZone); $dt = new DateTime('now', $tz); $dt->setTimestamp($timestamp); $dt->setTime(0, 0, 0); return $dt->getTimestamp(); }
php
public static function makeMidnight($timestamp, $timezone=null) { $tz = new DateTimeZone($timezone !== null ? $timezone : Yii::$app->timeZone); $dt = new DateTime('now', $tz); $dt->setTimestamp($timestamp); $dt->setTime(0, 0, 0); return $dt->getTimestamp(); }
[ "public", "static", "function", "makeMidnight", "(", "$", "timestamp", ",", "$", "timezone", "=", "null", ")", "{", "$", "tz", "=", "new", "DateTimeZone", "(", "$", "timezone", "!==", "null", "?", "$", "timezone", ":", "Yii", "::", "$", "app", "->", "timeZone", ")", ";", "$", "dt", "=", "new", "DateTime", "(", "'now'", ",", "$", "tz", ")", ";", "$", "dt", "->", "setTimestamp", "(", "$", "timestamp", ")", ";", "$", "dt", "->", "setTime", "(", "0", ",", "0", ",", "0", ")", ";", "return", "$", "dt", "->", "getTimestamp", "(", ")", ";", "}" ]
This method takes a timestamp and sets is time to midnight on the same day in the specified timezone. @param int $timestamp the timestamp to set the time to midnight @param string $timezone the timezone to calculate the day for @return int the midnight timestamp of the same timezone as timezone source
[ "This", "method", "takes", "a", "timestamp", "and", "sets", "is", "time", "to", "midnight", "on", "the", "same", "day", "in", "the", "specified", "timezone", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Timestamp.php#L191-L200
232,841
asinfotrack/yii2-toolbox
helpers/Timestamp.php
Timestamp.hasTime
public static function hasTime($timestamp, $timezone=self::TIMEZONE_UTC) { $tz = new DateTimeZone($timezone); $dt = new DateTime('now', $tz); $dt->setTimestamp($timestamp); $valTime = intval($dt->format('His')); return $valTime !== 0; }
php
public static function hasTime($timestamp, $timezone=self::TIMEZONE_UTC) { $tz = new DateTimeZone($timezone); $dt = new DateTime('now', $tz); $dt->setTimestamp($timestamp); $valTime = intval($dt->format('His')); return $valTime !== 0; }
[ "public", "static", "function", "hasTime", "(", "$", "timestamp", ",", "$", "timezone", "=", "self", "::", "TIMEZONE_UTC", ")", "{", "$", "tz", "=", "new", "DateTimeZone", "(", "$", "timezone", ")", ";", "$", "dt", "=", "new", "DateTime", "(", "'now'", ",", "$", "tz", ")", ";", "$", "dt", "->", "setTimestamp", "(", "$", "timestamp", ")", ";", "$", "valTime", "=", "intval", "(", "$", "dt", "->", "format", "(", "'His'", ")", ")", ";", "return", "$", "valTime", "!==", "0", ";", "}" ]
Checks whether or not a timestamp has a time part. The function returns true, if the time-part of a stamp differs from the values defined in params 2 to 4. Default setting for no time part is 00:00:00. @param integer $timestamp the timestamp to check @param string $timezone the timezone the timestamp is in (defaults to UTC) @return boolean true if a time is set differing from the one defined in params 2 to 4 @throws InvalidParamException if values are illegal
[ "Checks", "whether", "or", "not", "a", "timestamp", "has", "a", "time", "part", ".", "The", "function", "returns", "true", "if", "the", "time", "-", "part", "of", "a", "stamp", "differs", "from", "the", "values", "defined", "in", "params", "2", "to", "4", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Timestamp.php#L213-L222
232,842
asinfotrack/yii2-toolbox
helpers/Timestamp.php
Timestamp.parseFromDate
public static function parseFromDate($value, $format, $locale=null, $timeZone='UTC') { //default values $locale = $locale === null ? Yii::$app->language : $locale; //decide which parser to use if (strncmp($format, 'php:', 4) === 0) { $format = substr($format, 4); } else { if (ServerConfig::extIntlLoaded()) { return static::parseDateValueIntl($value, $format, $locale, $timeZone); } else { $format = FormatConverter::convertDateIcuToPhp($format, 'date'); } } return static::parseDateValuePHP($value, $format, $timeZone); }
php
public static function parseFromDate($value, $format, $locale=null, $timeZone='UTC') { //default values $locale = $locale === null ? Yii::$app->language : $locale; //decide which parser to use if (strncmp($format, 'php:', 4) === 0) { $format = substr($format, 4); } else { if (ServerConfig::extIntlLoaded()) { return static::parseDateValueIntl($value, $format, $locale, $timeZone); } else { $format = FormatConverter::convertDateIcuToPhp($format, 'date'); } } return static::parseDateValuePHP($value, $format, $timeZone); }
[ "public", "static", "function", "parseFromDate", "(", "$", "value", ",", "$", "format", ",", "$", "locale", "=", "null", ",", "$", "timeZone", "=", "'UTC'", ")", "{", "//default values", "$", "locale", "=", "$", "locale", "===", "null", "?", "Yii", "::", "$", "app", "->", "language", ":", "$", "locale", ";", "//decide which parser to use", "if", "(", "strncmp", "(", "$", "format", ",", "'php:'", ",", "4", ")", "===", "0", ")", "{", "$", "format", "=", "substr", "(", "$", "format", ",", "4", ")", ";", "}", "else", "{", "if", "(", "ServerConfig", "::", "extIntlLoaded", "(", ")", ")", "{", "return", "static", "::", "parseDateValueIntl", "(", "$", "value", ",", "$", "format", ",", "$", "locale", ",", "$", "timeZone", ")", ";", "}", "else", "{", "$", "format", "=", "FormatConverter", "::", "convertDateIcuToPhp", "(", "$", "format", ",", "'date'", ")", ";", "}", "}", "return", "static", "::", "parseDateValuePHP", "(", "$", "value", ",", "$", "format", ",", "$", "timeZone", ")", ";", "}" ]
Parses a date value into a UNIX-Timestamp @param string $value string representing date @param string $format the expected date format @param string $locale string the locale ID that is used to localize the date parsing. This is only effective when the [PHP intl extension](http://php.net/manual/en/book.intl.php) is installed. If not set, the locale of the [[\yii\base\Application::formatter|formatter]] will be used. See also [[\yii\i18n\Formatter::locale]]. @param string $timeZone the timezone to use for parsing date and time values. This can be any value that may be passed to [date_default_timezone_set()](http://www.php.net/manual/en/function.date-default-timezone-set.php) e.g. `UTC`, `Europe/Berlin` or `America/Chicago`. Refer to the [php manual](http://www.php.net/manual/en/timezones.php) for available timezones. If this property is not set, [[\yii\base\Application::timeZone]] will be used. @return integer|boolean a UNIX timestamp or `false` on failure.
[ "Parses", "a", "date", "value", "into", "a", "UNIX", "-", "Timestamp" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/Timestamp.php#L240-L256
232,843
contao-community-alliance/event-dispatcher
src/Configuration/ResourceLocator.php
ResourceLocator.getResourcePaths
public function getResourcePaths() { $paths = []; foreach ($this->bundles as $name => $class) { if (null !== ($path = $this->getResourcePathFromBundle($this->appRoot, $name, $class))) { $paths[] = $path; } } if (is_readable($file = $this->appRoot . '/app/Resources/contao/config/' . $this->fileName)) { $paths[] = $file; } if (is_readable($file = $this->appRoot . '/system/config/' . $this->fileName)) { $paths[] = $file; } return $paths; }
php
public function getResourcePaths() { $paths = []; foreach ($this->bundles as $name => $class) { if (null !== ($path = $this->getResourcePathFromBundle($this->appRoot, $name, $class))) { $paths[] = $path; } } if (is_readable($file = $this->appRoot . '/app/Resources/contao/config/' . $this->fileName)) { $paths[] = $file; } if (is_readable($file = $this->appRoot . '/system/config/' . $this->fileName)) { $paths[] = $file; } return $paths; }
[ "public", "function", "getResourcePaths", "(", ")", "{", "$", "paths", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "bundles", "as", "$", "name", "=>", "$", "class", ")", "{", "if", "(", "null", "!==", "(", "$", "path", "=", "$", "this", "->", "getResourcePathFromBundle", "(", "$", "this", "->", "appRoot", ",", "$", "name", ",", "$", "class", ")", ")", ")", "{", "$", "paths", "[", "]", "=", "$", "path", ";", "}", "}", "if", "(", "is_readable", "(", "$", "file", "=", "$", "this", "->", "appRoot", ".", "'/app/Resources/contao/config/'", ".", "$", "this", "->", "fileName", ")", ")", "{", "$", "paths", "[", "]", "=", "$", "file", ";", "}", "if", "(", "is_readable", "(", "$", "file", "=", "$", "this", "->", "appRoot", ".", "'/system/config/'", ".", "$", "this", "->", "fileName", ")", ")", "{", "$", "paths", "[", "]", "=", "$", "file", ";", "}", "return", "$", "paths", ";", "}" ]
Returns the Contao resource paths as array. @return array
[ "Returns", "the", "Contao", "resource", "paths", "as", "array", "." ]
1282b22fdbec4e458fc6204530ed36c3eebbe6c6
https://github.com/contao-community-alliance/event-dispatcher/blob/1282b22fdbec4e458fc6204530ed36c3eebbe6c6/src/Configuration/ResourceLocator.php#L65-L84
232,844
laraplug/product-module
Services/CategoryOrdener.php
CategoryOrdener.order
private function order($position, $item) { $category = $this->categoryRepository->find($item['id']); $this->savePosition($category, $position); $this->makeItemChildOf($category, null); if ($this->hasChildren($item)) { $this->handleChildrenForParent($category, $item['children']); } }
php
private function order($position, $item) { $category = $this->categoryRepository->find($item['id']); $this->savePosition($category, $position); $this->makeItemChildOf($category, null); if ($this->hasChildren($item)) { $this->handleChildrenForParent($category, $item['children']); } }
[ "private", "function", "order", "(", "$", "position", ",", "$", "item", ")", "{", "$", "category", "=", "$", "this", "->", "categoryRepository", "->", "find", "(", "$", "item", "[", "'id'", "]", ")", ";", "$", "this", "->", "savePosition", "(", "$", "category", ",", "$", "position", ")", ";", "$", "this", "->", "makeItemChildOf", "(", "$", "category", ",", "null", ")", ";", "if", "(", "$", "this", "->", "hasChildren", "(", "$", "item", ")", ")", "{", "$", "this", "->", "handleChildrenForParent", "(", "$", "category", ",", "$", "item", "[", "'children'", "]", ")", ";", "}", "}" ]
Order recursively the categories @param int $position @param array $item
[ "Order", "recursively", "the", "categories" ]
0a835482d2888a05bfe145e1b453926832185ae0
https://github.com/laraplug/product-module/blob/0a835482d2888a05bfe145e1b453926832185ae0/Services/CategoryOrdener.php#L40-L49
232,845
yongtiger/yii2-tree-manager
src/widgets/TreeView.php
TreeView.registerClient
protected function registerClient() { $view = $this->getView(); TreeViewAsset::register($view); $selector = ArrayHelper::remove($this->clientOptions, 'selector', 'ol.sortable'); $view->registerJs("ns = $('{$selector}').nestedSortable(" . Json::htmlEncode($this->clientOptions) . ");"); $treeView = $this->options['id']; $loading = $this->loadingOptions['id']; $view->registerJs(<<<JS treeView = $('#{$treeView}'); loading = $('#{$loading}'); JS ); }
php
protected function registerClient() { $view = $this->getView(); TreeViewAsset::register($view); $selector = ArrayHelper::remove($this->clientOptions, 'selector', 'ol.sortable'); $view->registerJs("ns = $('{$selector}').nestedSortable(" . Json::htmlEncode($this->clientOptions) . ");"); $treeView = $this->options['id']; $loading = $this->loadingOptions['id']; $view->registerJs(<<<JS treeView = $('#{$treeView}'); loading = $('#{$loading}'); JS ); }
[ "protected", "function", "registerClient", "(", ")", "{", "$", "view", "=", "$", "this", "->", "getView", "(", ")", ";", "TreeViewAsset", "::", "register", "(", "$", "view", ")", ";", "$", "selector", "=", "ArrayHelper", "::", "remove", "(", "$", "this", "->", "clientOptions", ",", "'selector'", ",", "'ol.sortable'", ")", ";", "$", "view", "->", "registerJs", "(", "\"ns = $('{$selector}').nestedSortable(\"", ".", "Json", "::", "htmlEncode", "(", "$", "this", "->", "clientOptions", ")", ".", "\");\"", ")", ";", "$", "treeView", "=", "$", "this", "->", "options", "[", "'id'", "]", ";", "$", "loading", "=", "$", "this", "->", "loadingOptions", "[", "'id'", "]", ";", "$", "view", "->", "registerJs", "(", "<<<JS\ntreeView = $('#{$treeView}');\nloading = $('#{$loading}');\nJS", ")", ";", "}" ]
Registers client script.
[ "Registers", "client", "script", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/widgets/TreeView.php#L267-L282
232,846
yongtiger/yii2-tree-manager
src/widgets/TreeView.php
TreeView.renderLoading
protected function renderLoading() { $tag = ArrayHelper::remove($this->loadingOptions, 'tag', 'div'); echo Html::tag($tag, '', $this->loadingOptions); }
php
protected function renderLoading() { $tag = ArrayHelper::remove($this->loadingOptions, 'tag', 'div'); echo Html::tag($tag, '', $this->loadingOptions); }
[ "protected", "function", "renderLoading", "(", ")", "{", "$", "tag", "=", "ArrayHelper", "::", "remove", "(", "$", "this", "->", "loadingOptions", ",", "'tag'", ",", "'div'", ")", ";", "echo", "Html", "::", "tag", "(", "$", "tag", ",", "''", ",", "$", "this", "->", "loadingOptions", ")", ";", "}" ]
Renders loading.
[ "Renders", "loading", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/widgets/TreeView.php#L287-L291
232,847
yongtiger/yii2-tree-manager
src/widgets/TreeView.php
TreeView.renderTree
protected function renderTree() { $lines = []; $tag = ArrayHelper::remove($this->options, 'tag', 'div'); $lines[] = Html::beginTag($tag, $this->options); $lines[] = $this->renderToolbar(); $lines[] = $this->renderNodes($this->nodes); $lines[] = Html::endTag($tag); return implode("\n", $lines); }
php
protected function renderTree() { $lines = []; $tag = ArrayHelper::remove($this->options, 'tag', 'div'); $lines[] = Html::beginTag($tag, $this->options); $lines[] = $this->renderToolbar(); $lines[] = $this->renderNodes($this->nodes); $lines[] = Html::endTag($tag); return implode("\n", $lines); }
[ "protected", "function", "renderTree", "(", ")", "{", "$", "lines", "=", "[", "]", ";", "$", "tag", "=", "ArrayHelper", "::", "remove", "(", "$", "this", "->", "options", ",", "'tag'", ",", "'div'", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "beginTag", "(", "$", "tag", ",", "$", "this", "->", "options", ")", ";", "$", "lines", "[", "]", "=", "$", "this", "->", "renderToolbar", "(", ")", ";", "$", "lines", "[", "]", "=", "$", "this", "->", "renderNodes", "(", "$", "this", "->", "nodes", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "endTag", "(", "$", "tag", ")", ";", "return", "implode", "(", "\"\\n\"", ",", "$", "lines", ")", ";", "}" ]
Renders the tree. @return string the rendering result.
[ "Renders", "the", "tree", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/widgets/TreeView.php#L297-L310
232,848
yongtiger/yii2-tree-manager
src/widgets/TreeView.php
TreeView.renderToolbar
protected function renderToolbar() { $lines = []; $lines[] = Html::beginTag('div', ['class' => 'btn-group']); $title = Module::t('message', 'Create a root node'); $lines[] = Html::button(Module::t('message', 'Create'), [ 'title' => $title, 'aria-label' => $title, 'data-action-name' => 'create', 'class' => 'btn btn-success', 'onclick' => '{location.href="' . $this->createUrl('create') . '"}', ]); $lines[] = Html::button(Module::t('message', 'Collapse all'), [ 'id' => 'collapse-all', 'class' => 'btn btn-default', 'style' => $this->clientOptions['startCollapsed'] ? 'display: none' : 'display: block', ]); $lines[] = Html::button(Module::t('message', 'Expand all'), [ 'id' => 'expand-all', 'class' => 'btn btn-default', 'style' => $this->clientOptions['startCollapsed'] ? 'display: block' : 'display: none', ]); $lines[] = Html::endTag('div'); return implode("\n", $lines); }
php
protected function renderToolbar() { $lines = []; $lines[] = Html::beginTag('div', ['class' => 'btn-group']); $title = Module::t('message', 'Create a root node'); $lines[] = Html::button(Module::t('message', 'Create'), [ 'title' => $title, 'aria-label' => $title, 'data-action-name' => 'create', 'class' => 'btn btn-success', 'onclick' => '{location.href="' . $this->createUrl('create') . '"}', ]); $lines[] = Html::button(Module::t('message', 'Collapse all'), [ 'id' => 'collapse-all', 'class' => 'btn btn-default', 'style' => $this->clientOptions['startCollapsed'] ? 'display: none' : 'display: block', ]); $lines[] = Html::button(Module::t('message', 'Expand all'), [ 'id' => 'expand-all', 'class' => 'btn btn-default', 'style' => $this->clientOptions['startCollapsed'] ? 'display: block' : 'display: none', ]); $lines[] = Html::endTag('div'); return implode("\n", $lines); }
[ "protected", "function", "renderToolbar", "(", ")", "{", "$", "lines", "=", "[", "]", ";", "$", "lines", "[", "]", "=", "Html", "::", "beginTag", "(", "'div'", ",", "[", "'class'", "=>", "'btn-group'", "]", ")", ";", "$", "title", "=", "Module", "::", "t", "(", "'message'", ",", "'Create a root node'", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "button", "(", "Module", "::", "t", "(", "'message'", ",", "'Create'", ")", ",", "[", "'title'", "=>", "$", "title", ",", "'aria-label'", "=>", "$", "title", ",", "'data-action-name'", "=>", "'create'", ",", "'class'", "=>", "'btn btn-success'", ",", "'onclick'", "=>", "'{location.href=\"'", ".", "$", "this", "->", "createUrl", "(", "'create'", ")", ".", "'\"}'", ",", "]", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "button", "(", "Module", "::", "t", "(", "'message'", ",", "'Collapse all'", ")", ",", "[", "'id'", "=>", "'collapse-all'", ",", "'class'", "=>", "'btn btn-default'", ",", "'style'", "=>", "$", "this", "->", "clientOptions", "[", "'startCollapsed'", "]", "?", "'display: none'", ":", "'display: block'", ",", "]", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "button", "(", "Module", "::", "t", "(", "'message'", ",", "'Expand all'", ")", ",", "[", "'id'", "=>", "'expand-all'", ",", "'class'", "=>", "'btn btn-default'", ",", "'style'", "=>", "$", "this", "->", "clientOptions", "[", "'startCollapsed'", "]", "?", "'display: block'", ":", "'display: none'", ",", "]", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "endTag", "(", "'div'", ")", ";", "return", "implode", "(", "\"\\n\"", ",", "$", "lines", ")", ";", "}" ]
Renders the toolbar. @return string the rendering result.
[ "Renders", "the", "toolbar", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/widgets/TreeView.php#L316-L344
232,849
yongtiger/yii2-tree-manager
src/widgets/TreeView.php
TreeView.renderNodes
protected function renderNodes($nodes) { $lines = []; if (!empty($nodes)) { $nodesOptions = $this->nodesOptions; $tag = ArrayHelper::remove($nodesOptions, 'tag', 'ol'); $lines[] = Html::beginTag($tag, $nodesOptions); foreach ($nodes as $node) { if (isset($node['visible']) && !$node['visible']) { continue; } $lines[] = $this->renderNode($node); } $lines[] = Html::endTag($tag); } return implode("\n", $lines); }
php
protected function renderNodes($nodes) { $lines = []; if (!empty($nodes)) { $nodesOptions = $this->nodesOptions; $tag = ArrayHelper::remove($nodesOptions, 'tag', 'ol'); $lines[] = Html::beginTag($tag, $nodesOptions); foreach ($nodes as $node) { if (isset($node['visible']) && !$node['visible']) { continue; } $lines[] = $this->renderNode($node); } $lines[] = Html::endTag($tag); } return implode("\n", $lines); }
[ "protected", "function", "renderNodes", "(", "$", "nodes", ")", "{", "$", "lines", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "nodes", ")", ")", "{", "$", "nodesOptions", "=", "$", "this", "->", "nodesOptions", ";", "$", "tag", "=", "ArrayHelper", "::", "remove", "(", "$", "nodesOptions", ",", "'tag'", ",", "'ol'", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "beginTag", "(", "$", "tag", ",", "$", "nodesOptions", ")", ";", "foreach", "(", "$", "nodes", "as", "$", "node", ")", "{", "if", "(", "isset", "(", "$", "node", "[", "'visible'", "]", ")", "&&", "!", "$", "node", "[", "'visible'", "]", ")", "{", "continue", ";", "}", "$", "lines", "[", "]", "=", "$", "this", "->", "renderNode", "(", "$", "node", ")", ";", "}", "$", "lines", "[", "]", "=", "Html", "::", "endTag", "(", "$", "tag", ")", ";", "}", "return", "implode", "(", "\"\\n\"", ",", "$", "lines", ")", ";", "}" ]
Renders tree nodes. @param array $nodes @return string the rendering result.
[ "Renders", "tree", "nodes", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/widgets/TreeView.php#L351-L372
232,850
yongtiger/yii2-tree-manager
src/widgets/TreeView.php
TreeView.renderNode
protected function renderNode($node) { if (is_string($node)) { $node = ['name' => $node]; } if (!isset($node['name'])) { throw new InvalidConfigException("The 'name' option is required."); } $lines = []; $nodeOptions = array_merge([ 'data-node-id' => $node['id'], 'data-node-name' => Html::encode($node['name']), 'data-action-name' => 'move', ///[node move action] 'data-action-url' => Url::to(ArrayHelper::getValue($node, 'move-url', $this->createUrl('move', $node))), // more node data ... ], $this->nodeOptions, ArrayHelper::getValue($node, 'options', [])); $tag = ArrayHelper::remove($nodeOptions, 'tag', 'li'); $lines[] = Html::beginTag($tag, $nodeOptions); $lines[] = Html::beginTag('div'); $lines[] = $this->renderNodeName($node); $lines[] = $this->renderNodeActions($node); $lines[] = Html::endTag('div'); if (!empty($node['nodes'])) { $lines[] = $this->renderNodes($node['nodes']); } $lines[] = Html::endTag($tag); return implode("\n", $lines); }
php
protected function renderNode($node) { if (is_string($node)) { $node = ['name' => $node]; } if (!isset($node['name'])) { throw new InvalidConfigException("The 'name' option is required."); } $lines = []; $nodeOptions = array_merge([ 'data-node-id' => $node['id'], 'data-node-name' => Html::encode($node['name']), 'data-action-name' => 'move', ///[node move action] 'data-action-url' => Url::to(ArrayHelper::getValue($node, 'move-url', $this->createUrl('move', $node))), // more node data ... ], $this->nodeOptions, ArrayHelper::getValue($node, 'options', [])); $tag = ArrayHelper::remove($nodeOptions, 'tag', 'li'); $lines[] = Html::beginTag($tag, $nodeOptions); $lines[] = Html::beginTag('div'); $lines[] = $this->renderNodeName($node); $lines[] = $this->renderNodeActions($node); $lines[] = Html::endTag('div'); if (!empty($node['nodes'])) { $lines[] = $this->renderNodes($node['nodes']); } $lines[] = Html::endTag($tag); return implode("\n", $lines); }
[ "protected", "function", "renderNode", "(", "$", "node", ")", "{", "if", "(", "is_string", "(", "$", "node", ")", ")", "{", "$", "node", "=", "[", "'name'", "=>", "$", "node", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "node", "[", "'name'", "]", ")", ")", "{", "throw", "new", "InvalidConfigException", "(", "\"The 'name' option is required.\"", ")", ";", "}", "$", "lines", "=", "[", "]", ";", "$", "nodeOptions", "=", "array_merge", "(", "[", "'data-node-id'", "=>", "$", "node", "[", "'id'", "]", ",", "'data-node-name'", "=>", "Html", "::", "encode", "(", "$", "node", "[", "'name'", "]", ")", ",", "'data-action-name'", "=>", "'move'", ",", "///[node move action]", "'data-action-url'", "=>", "Url", "::", "to", "(", "ArrayHelper", "::", "getValue", "(", "$", "node", ",", "'move-url'", ",", "$", "this", "->", "createUrl", "(", "'move'", ",", "$", "node", ")", ")", ")", ",", "// more node data ...", "]", ",", "$", "this", "->", "nodeOptions", ",", "ArrayHelper", "::", "getValue", "(", "$", "node", ",", "'options'", ",", "[", "]", ")", ")", ";", "$", "tag", "=", "ArrayHelper", "::", "remove", "(", "$", "nodeOptions", ",", "'tag'", ",", "'li'", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "beginTag", "(", "$", "tag", ",", "$", "nodeOptions", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "beginTag", "(", "'div'", ")", ";", "$", "lines", "[", "]", "=", "$", "this", "->", "renderNodeName", "(", "$", "node", ")", ";", "$", "lines", "[", "]", "=", "$", "this", "->", "renderNodeActions", "(", "$", "node", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "endTag", "(", "'div'", ")", ";", "if", "(", "!", "empty", "(", "$", "node", "[", "'nodes'", "]", ")", ")", "{", "$", "lines", "[", "]", "=", "$", "this", "->", "renderNodes", "(", "$", "node", "[", "'nodes'", "]", ")", ";", "}", "$", "lines", "[", "]", "=", "Html", "::", "endTag", "(", "$", "tag", ")", ";", "return", "implode", "(", "\"\\n\"", ",", "$", "lines", ")", ";", "}" ]
Renders a tree node. @param string|array $node the node to render. @return string the rendering result. @throws InvalidConfigException
[ "Renders", "a", "tree", "node", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/widgets/TreeView.php#L380-L416
232,851
yongtiger/yii2-tree-manager
src/widgets/TreeView.php
TreeView.renderNodeName
protected function renderNodeName($node) { $encodeName = isset($node['encode']) ? $node['encode'] : $this->encodeNodeNames; $name = $encodeName ? Html::encode($node['name']) : $node['name']; $template = ArrayHelper::getValue($node, 'template', $this->nodeNameTemplate); return strtr($template, [ '{name}' => $name, ]); }
php
protected function renderNodeName($node) { $encodeName = isset($node['encode']) ? $node['encode'] : $this->encodeNodeNames; $name = $encodeName ? Html::encode($node['name']) : $node['name']; $template = ArrayHelper::getValue($node, 'template', $this->nodeNameTemplate); return strtr($template, [ '{name}' => $name, ]); }
[ "protected", "function", "renderNodeName", "(", "$", "node", ")", "{", "$", "encodeName", "=", "isset", "(", "$", "node", "[", "'encode'", "]", ")", "?", "$", "node", "[", "'encode'", "]", ":", "$", "this", "->", "encodeNodeNames", ";", "$", "name", "=", "$", "encodeName", "?", "Html", "::", "encode", "(", "$", "node", "[", "'name'", "]", ")", ":", "$", "node", "[", "'name'", "]", ";", "$", "template", "=", "ArrayHelper", "::", "getValue", "(", "$", "node", ",", "'template'", ",", "$", "this", "->", "nodeNameTemplate", ")", ";", "return", "strtr", "(", "$", "template", ",", "[", "'{name}'", "=>", "$", "name", ",", "]", ")", ";", "}" ]
Renders a node name. @param array $node @return string the rendering result.
[ "Renders", "a", "node", "name", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/widgets/TreeView.php#L423-L432
232,852
yongtiger/yii2-tree-manager
src/widgets/TreeView.php
TreeView.renderNodeActions
protected function renderNodeActions($node) { $lines = []; $nodeActionsOptions = $this->nodeActionsOptions; $tag = ArrayHelper::remove($nodeActionsOptions, 'tag', 'span'); $lines[] = Html::beginTag($tag, $nodeActionsOptions); foreach ($this->nodeActions as $actionName => $actionValue) { $lines[] = $this->renderNodeAction($node, $actionName, $actionValue); } $lines[] = Html::endTag($tag); return implode("\n", $lines); }
php
protected function renderNodeActions($node) { $lines = []; $nodeActionsOptions = $this->nodeActionsOptions; $tag = ArrayHelper::remove($nodeActionsOptions, 'tag', 'span'); $lines[] = Html::beginTag($tag, $nodeActionsOptions); foreach ($this->nodeActions as $actionName => $actionValue) { $lines[] = $this->renderNodeAction($node, $actionName, $actionValue); } $lines[] = Html::endTag($tag); return implode("\n", $lines); }
[ "protected", "function", "renderNodeActions", "(", "$", "node", ")", "{", "$", "lines", "=", "[", "]", ";", "$", "nodeActionsOptions", "=", "$", "this", "->", "nodeActionsOptions", ";", "$", "tag", "=", "ArrayHelper", "::", "remove", "(", "$", "nodeActionsOptions", ",", "'tag'", ",", "'span'", ")", ";", "$", "lines", "[", "]", "=", "Html", "::", "beginTag", "(", "$", "tag", ",", "$", "nodeActionsOptions", ")", ";", "foreach", "(", "$", "this", "->", "nodeActions", "as", "$", "actionName", "=>", "$", "actionValue", ")", "{", "$", "lines", "[", "]", "=", "$", "this", "->", "renderNodeAction", "(", "$", "node", ",", "$", "actionName", ",", "$", "actionValue", ")", ";", "}", "$", "lines", "[", "]", "=", "Html", "::", "endTag", "(", "$", "tag", ")", ";", "return", "implode", "(", "\"\\n\"", ",", "$", "lines", ")", ";", "}" ]
Renders node actions. @param array $node @return string the rendering result.
[ "Renders", "node", "actions", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/widgets/TreeView.php#L439-L454
232,853
yongtiger/yii2-tree-manager
src/widgets/TreeView.php
TreeView.renderNodeAction
protected function renderNodeAction($node, $actionName, $actionValue) { $lines = []; $nodeActionOptions = $this->nodeActionOptions; $tag = ArrayHelper::remove($nodeActionOptions, 'tag', 'a'); $title = Module::t('message', ucwords(implode(' ', explode('-', $actionName)))); $options = array_merge([ 'title' => $title, 'aria-label' => $title, 'data-node-id' => $node['id'], 'data-action-name' => "{$actionName}", ], $nodeActionOptions, $actionValue['actionOptions']); foreach ($options as $key => $option) { $options[$key] = strtr($option, [ '{action-url}' => Url::to(ArrayHelper::getValue($node, $actionName . '-url', $this->createUrl($actionName, $node))), ]); } $lines[] = Html::tag($tag, $actionValue['actionText'], $options); return implode("\n", $lines); }
php
protected function renderNodeAction($node, $actionName, $actionValue) { $lines = []; $nodeActionOptions = $this->nodeActionOptions; $tag = ArrayHelper::remove($nodeActionOptions, 'tag', 'a'); $title = Module::t('message', ucwords(implode(' ', explode('-', $actionName)))); $options = array_merge([ 'title' => $title, 'aria-label' => $title, 'data-node-id' => $node['id'], 'data-action-name' => "{$actionName}", ], $nodeActionOptions, $actionValue['actionOptions']); foreach ($options as $key => $option) { $options[$key] = strtr($option, [ '{action-url}' => Url::to(ArrayHelper::getValue($node, $actionName . '-url', $this->createUrl($actionName, $node))), ]); } $lines[] = Html::tag($tag, $actionValue['actionText'], $options); return implode("\n", $lines); }
[ "protected", "function", "renderNodeAction", "(", "$", "node", ",", "$", "actionName", ",", "$", "actionValue", ")", "{", "$", "lines", "=", "[", "]", ";", "$", "nodeActionOptions", "=", "$", "this", "->", "nodeActionOptions", ";", "$", "tag", "=", "ArrayHelper", "::", "remove", "(", "$", "nodeActionOptions", ",", "'tag'", ",", "'a'", ")", ";", "$", "title", "=", "Module", "::", "t", "(", "'message'", ",", "ucwords", "(", "implode", "(", "' '", ",", "explode", "(", "'-'", ",", "$", "actionName", ")", ")", ")", ")", ";", "$", "options", "=", "array_merge", "(", "[", "'title'", "=>", "$", "title", ",", "'aria-label'", "=>", "$", "title", ",", "'data-node-id'", "=>", "$", "node", "[", "'id'", "]", ",", "'data-action-name'", "=>", "\"{$actionName}\"", ",", "]", ",", "$", "nodeActionOptions", ",", "$", "actionValue", "[", "'actionOptions'", "]", ")", ";", "foreach", "(", "$", "options", "as", "$", "key", "=>", "$", "option", ")", "{", "$", "options", "[", "$", "key", "]", "=", "strtr", "(", "$", "option", ",", "[", "'{action-url}'", "=>", "Url", "::", "to", "(", "ArrayHelper", "::", "getValue", "(", "$", "node", ",", "$", "actionName", ".", "'-url'", ",", "$", "this", "->", "createUrl", "(", "$", "actionName", ",", "$", "node", ")", ")", ")", ",", "]", ")", ";", "}", "$", "lines", "[", "]", "=", "Html", "::", "tag", "(", "$", "tag", ",", "$", "actionValue", "[", "'actionText'", "]", ",", "$", "options", ")", ";", "return", "implode", "(", "\"\\n\"", ",", "$", "lines", ")", ";", "}" ]
Renders a node action. @param array $node @param string $actionName @param array $actionValue Array of a node action. @return string the rendering result.
[ "Renders", "a", "node", "action", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/widgets/TreeView.php#L463-L487
232,854
yongtiger/yii2-tree-manager
src/widgets/TreeView.php
TreeView.createUrl
protected function createUrl($actionName, $node = null) { if (isset($node) && is_callable($this->urlCreator)) { return call_user_func($this->urlCreator, $node, $actionName, $this); } else { $params = isset($node) ? ['id' => (string) $node['id']] : []; $params[0] = $this->controller ? $this->controller . '/' . $actionName : $actionName; return Url::toRoute($params); } }
php
protected function createUrl($actionName, $node = null) { if (isset($node) && is_callable($this->urlCreator)) { return call_user_func($this->urlCreator, $node, $actionName, $this); } else { $params = isset($node) ? ['id' => (string) $node['id']] : []; $params[0] = $this->controller ? $this->controller . '/' . $actionName : $actionName; return Url::toRoute($params); } }
[ "protected", "function", "createUrl", "(", "$", "actionName", ",", "$", "node", "=", "null", ")", "{", "if", "(", "isset", "(", "$", "node", ")", "&&", "is_callable", "(", "$", "this", "->", "urlCreator", ")", ")", "{", "return", "call_user_func", "(", "$", "this", "->", "urlCreator", ",", "$", "node", ",", "$", "actionName", ",", "$", "this", ")", ";", "}", "else", "{", "$", "params", "=", "isset", "(", "$", "node", ")", "?", "[", "'id'", "=>", "(", "string", ")", "$", "node", "[", "'id'", "]", "]", ":", "[", "]", ";", "$", "params", "[", "0", "]", "=", "$", "this", "->", "controller", "?", "$", "this", "->", "controller", ".", "'/'", ".", "$", "actionName", ":", "$", "actionName", ";", "return", "Url", "::", "toRoute", "(", "$", "params", ")", ";", "}", "}" ]
Creates a URL for the given action and node id. @see http://www.yiiframework.com/doc-2.0/yii-grid-actioncolumn.html @param string $actionName the action name (or action ID). @param array $node will be null while creating node (root node) from toolbar. @return string the created URL.
[ "Creates", "a", "URL", "for", "the", "given", "action", "and", "node", "id", "." ]
e3a6f8bca42f9a941847538200a9cdb234d3ed14
https://github.com/yongtiger/yii2-tree-manager/blob/e3a6f8bca42f9a941847538200a9cdb234d3ed14/src/widgets/TreeView.php#L496-L506
232,855
silverstripe-archive/deploynaut
code/api/DeploynautAPI.php
DeploynautAPI.getProject
protected function getProject() { $projectName = $this->getRequest()->param('Project'); return DNProject::get()->filter('Name', $projectName)->first(); }
php
protected function getProject() { $projectName = $this->getRequest()->param('Project'); return DNProject::get()->filter('Name', $projectName)->first(); }
[ "protected", "function", "getProject", "(", ")", "{", "$", "projectName", "=", "$", "this", "->", "getRequest", "(", ")", "->", "param", "(", "'Project'", ")", ";", "return", "DNProject", "::", "get", "(", ")", "->", "filter", "(", "'Name'", ",", "$", "projectName", ")", "->", "first", "(", ")", ";", "}" ]
Get project from URL @return DNProject
[ "Get", "project", "from", "URL" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/api/DeploynautAPI.php#L104-L107
232,856
silverstripe-archive/deploynaut
code/api/DeploynautAPI.php
DeploynautAPI.getEnvironment
protected function getEnvironment() { $projectName = $this->getRequest()->param('Project'); $project = DNProject::get()->filter('Name', $projectName)->first(); $environmentName = $this->getRequest()->param('Environment'); return $project->Environments()->filter('Name', $environmentName)->first(); }
php
protected function getEnvironment() { $projectName = $this->getRequest()->param('Project'); $project = DNProject::get()->filter('Name', $projectName)->first(); $environmentName = $this->getRequest()->param('Environment'); return $project->Environments()->filter('Name', $environmentName)->first(); }
[ "protected", "function", "getEnvironment", "(", ")", "{", "$", "projectName", "=", "$", "this", "->", "getRequest", "(", ")", "->", "param", "(", "'Project'", ")", ";", "$", "project", "=", "DNProject", "::", "get", "(", ")", "->", "filter", "(", "'Name'", ",", "$", "projectName", ")", "->", "first", "(", ")", ";", "$", "environmentName", "=", "$", "this", "->", "getRequest", "(", ")", "->", "param", "(", "'Environment'", ")", ";", "return", "$", "project", "->", "Environments", "(", ")", "->", "filter", "(", "'Name'", ",", "$", "environmentName", ")", "->", "first", "(", ")", ";", "}" ]
Get environment from URL @return DNEnvironment
[ "Get", "environment", "from", "URL" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/api/DeploynautAPI.php#L114-L119
232,857
asinfotrack/yii2-toolbox
helpers/PrimaryKey.php
PrimaryKey.asJson
public static function asJson($model) { //check if the model is valid if (!($model instanceof \yii\db\ActiveRecord)) { throw new InvalidParamException(Yii::t('app', 'The model must be of type ActiveRecord')); } //fetch the models pk $pk = $model->primaryKey(); //assert that a valid pk was received if ($pk === null || !is_array($pk) || count($pk) == 0) { $msg = Yii::t('app', 'Invalid primary key definition: please provide a pk-definition for table {table}', ['table'=>$model->tableName()]); throw new InvalidConfigException($msg); } //create final array and return it $arrPk = []; foreach ($pk as $pkCol) $arrPk[$pkCol] = $model->{$pkCol}; return Json::encode($arrPk); }
php
public static function asJson($model) { //check if the model is valid if (!($model instanceof \yii\db\ActiveRecord)) { throw new InvalidParamException(Yii::t('app', 'The model must be of type ActiveRecord')); } //fetch the models pk $pk = $model->primaryKey(); //assert that a valid pk was received if ($pk === null || !is_array($pk) || count($pk) == 0) { $msg = Yii::t('app', 'Invalid primary key definition: please provide a pk-definition for table {table}', ['table'=>$model->tableName()]); throw new InvalidConfigException($msg); } //create final array and return it $arrPk = []; foreach ($pk as $pkCol) $arrPk[$pkCol] = $model->{$pkCol}; return Json::encode($arrPk); }
[ "public", "static", "function", "asJson", "(", "$", "model", ")", "{", "//check if the model is valid", "if", "(", "!", "(", "$", "model", "instanceof", "\\", "yii", "\\", "db", "\\", "ActiveRecord", ")", ")", "{", "throw", "new", "InvalidParamException", "(", "Yii", "::", "t", "(", "'app'", ",", "'The model must be of type ActiveRecord'", ")", ")", ";", "}", "//fetch the models pk", "$", "pk", "=", "$", "model", "->", "primaryKey", "(", ")", ";", "//assert that a valid pk was received", "if", "(", "$", "pk", "===", "null", "||", "!", "is_array", "(", "$", "pk", ")", "||", "count", "(", "$", "pk", ")", "==", "0", ")", "{", "$", "msg", "=", "Yii", "::", "t", "(", "'app'", ",", "'Invalid primary key definition: please provide a pk-definition for table {table}'", ",", "[", "'table'", "=>", "$", "model", "->", "tableName", "(", ")", "]", ")", ";", "throw", "new", "InvalidConfigException", "(", "$", "msg", ")", ";", "}", "//create final array and return it", "$", "arrPk", "=", "[", "]", ";", "foreach", "(", "$", "pk", "as", "$", "pkCol", ")", "$", "arrPk", "[", "$", "pkCol", "]", "=", "$", "model", "->", "{", "$", "pkCol", "}", ";", "return", "Json", "::", "encode", "(", "$", "arrPk", ")", ";", "}" ]
Returns a models primary-key in json format. This works also with composite primary-keys @param \yii\db\ActiveRecord $model the model instance @return string the models pk in json-format @throws \yii\base\InvalidParamException if the model is not of type ActiveRecord @throws \yii\base\InvalidConfigException if the models pk is empty or invalid
[ "Returns", "a", "models", "primary", "-", "key", "in", "json", "format", ".", "This", "works", "also", "with", "composite", "primary", "-", "keys" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/PrimaryKey.php#L28-L47
232,858
laravel-notification-channels/hipchat
src/HipChatFile.php
HipChatFile.path
public function path($path) { $path = trim($path); if (str_empty($this->fileName)) { $this->fileName(basename($path)); } if (str_empty($this->fileType)) { $this->fileType(mime_content_type($path)); } $this->fileContent(fopen($path, 'r')); return $this; }
php
public function path($path) { $path = trim($path); if (str_empty($this->fileName)) { $this->fileName(basename($path)); } if (str_empty($this->fileType)) { $this->fileType(mime_content_type($path)); } $this->fileContent(fopen($path, 'r')); return $this; }
[ "public", "function", "path", "(", "$", "path", ")", "{", "$", "path", "=", "trim", "(", "$", "path", ")", ";", "if", "(", "str_empty", "(", "$", "this", "->", "fileName", ")", ")", "{", "$", "this", "->", "fileName", "(", "basename", "(", "$", "path", ")", ")", ";", "}", "if", "(", "str_empty", "(", "$", "this", "->", "fileType", ")", ")", "{", "$", "this", "->", "fileType", "(", "mime_content_type", "(", "$", "path", ")", ")", ";", "}", "$", "this", "->", "fileContent", "(", "fopen", "(", "$", "path", ",", "'r'", ")", ")", ";", "return", "$", "this", ";", "}" ]
Set the file path. @param string $path @return $this
[ "Set", "the", "file", "path", "." ]
c24bca85f7cf9f6804635aa206c961783e22e888
https://github.com/laravel-notification-channels/hipchat/blob/c24bca85f7cf9f6804635aa206c961783e22e888/src/HipChatFile.php#L109-L124
232,859
laravel-notification-channels/hipchat
src/HipChatFile.php
HipChatFile.fileContent
public function fileContent($content) { if (is_resource($this->fileContent)) { fclose($this->fileContent); } $this->fileContent = $content; if (is_resource($content) && empty($this->fileType)) { $this->fileType($this->getTypeFromResource($content)); } return $this; }
php
public function fileContent($content) { if (is_resource($this->fileContent)) { fclose($this->fileContent); } $this->fileContent = $content; if (is_resource($content) && empty($this->fileType)) { $this->fileType($this->getTypeFromResource($content)); } return $this; }
[ "public", "function", "fileContent", "(", "$", "content", ")", "{", "if", "(", "is_resource", "(", "$", "this", "->", "fileContent", ")", ")", "{", "fclose", "(", "$", "this", "->", "fileContent", ")", ";", "}", "$", "this", "->", "fileContent", "=", "$", "content", ";", "if", "(", "is_resource", "(", "$", "content", ")", "&&", "empty", "(", "$", "this", "->", "fileType", ")", ")", "{", "$", "this", "->", "fileType", "(", "$", "this", "->", "getTypeFromResource", "(", "$", "content", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
Explicitly set the content of the file. @param $content @return $this
[ "Explicitly", "set", "the", "content", "of", "the", "file", "." ]
c24bca85f7cf9f6804635aa206c961783e22e888
https://github.com/laravel-notification-channels/hipchat/blob/c24bca85f7cf9f6804635aa206c961783e22e888/src/HipChatFile.php#L132-L145
232,860
dmitriybelyy/yii2-cassandra-cql
phpcassa/SuperColumnFamily.php
SuperColumnFamily.get_super_column
public function get_super_column($key, $super_column, $column_slice=null, $column_names=null, $consistency_level=null) { $cp = $this->create_column_parent($super_column); $slice = $this->create_slice_predicate($column_names, $column_slice, false); return $this->_get($key, $cp, $slice, $consistency_level); }
php
public function get_super_column($key, $super_column, $column_slice=null, $column_names=null, $consistency_level=null) { $cp = $this->create_column_parent($super_column); $slice = $this->create_slice_predicate($column_names, $column_slice, false); return $this->_get($key, $cp, $slice, $consistency_level); }
[ "public", "function", "get_super_column", "(", "$", "key", ",", "$", "super_column", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "$", "cp", "=", "$", "this", "->", "create_column_parent", "(", "$", "super_column", ")", ";", "$", "slice", "=", "$", "this", "->", "create_slice_predicate", "(", "$", "column_names", ",", "$", "column_slice", ",", "false", ")", ";", "return", "$", "this", "->", "_get", "(", "$", "key", ",", "$", "cp", ",", "$", "slice", ",", "$", "consistency_level", ")", ";", "}" ]
Fetch a single super column. Returns an array of the subcolumns in that super column. @param string $key row key to fetch @param mixed $super_column return only subcolumns of this super column @param \phpcassa\ColumnSlice a slice of subcolumns to fetch, or null @param mixed[] $column_names limit the subcolumns fetched to this list @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @return mixed array(subcolumn_name => subcolumn_value)
[ "Fetch", "a", "single", "super", "column", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/SuperColumnFamily.php#L40-L49
232,861
dmitriybelyy/yii2-cassandra-cql
phpcassa/SuperColumnFamily.php
SuperColumnFamily.multiget_super_column
public function multiget_super_column($keys, $super_column, $column_slice=null, $column_names=null, $consistency_level=null, $buffer_size=16) { $cp = $this->create_column_parent($super_column); $slice = $this->create_slice_predicate($column_names, $column_slice, false); return $this->_multiget($keys, $cp, $slice, $consistency_level, $buffer_size); }
php
public function multiget_super_column($keys, $super_column, $column_slice=null, $column_names=null, $consistency_level=null, $buffer_size=16) { $cp = $this->create_column_parent($super_column); $slice = $this->create_slice_predicate($column_names, $column_slice, false); return $this->_multiget($keys, $cp, $slice, $consistency_level, $buffer_size); }
[ "public", "function", "multiget_super_column", "(", "$", "keys", ",", "$", "super_column", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ",", "$", "buffer_size", "=", "16", ")", "{", "$", "cp", "=", "$", "this", "->", "create_column_parent", "(", "$", "super_column", ")", ";", "$", "slice", "=", "$", "this", "->", "create_slice_predicate", "(", "$", "column_names", ",", "$", "column_slice", ",", "false", ")", ";", "return", "$", "this", "->", "_multiget", "(", "$", "keys", ",", "$", "cp", ",", "$", "slice", ",", "$", "consistency_level", ",", "$", "buffer_size", ")", ";", "}" ]
Fetch a super column from multiple rows from this column family. The returned array will map directly from keys to the subcolumn array; the super column layer is omitted. @param string[] $keys row keys to fetch @param mixed $super_column return only subcolumns of this super column @param \phpcassa\ColumnSlice a slice of subcolumns to fetch, or null @param mixed[] $column_names limit the subcolumns fetched to this list @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @param int $buffer_size the number of keys to multiget at a single time. If your rows are large, having a high buffer size gives poor performance; if your rows are small, consider increasing this value. @return mixed array(key => array(subcolumn_name => subcolumn_value))
[ "Fetch", "a", "super", "column", "from", "multiple", "rows", "from", "this", "column", "family", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/SuperColumnFamily.php#L69-L80
232,862
dmitriybelyy/yii2-cassandra-cql
phpcassa/SuperColumnFamily.php
SuperColumnFamily.get_subcolumn_count
public function get_subcolumn_count($key, $super_column, $column_slice=null, $column_names=null, $consistency_level=null) { $cp = $this->create_column_parent($super_column); $slice = $this->create_slice_predicate( $column_names, $column_slice, false, ColumnSlice::MAX_COUNT); return $this->_get_count($key, $cp, $slice, $consistency_level); }
php
public function get_subcolumn_count($key, $super_column, $column_slice=null, $column_names=null, $consistency_level=null) { $cp = $this->create_column_parent($super_column); $slice = $this->create_slice_predicate( $column_names, $column_slice, false, ColumnSlice::MAX_COUNT); return $this->_get_count($key, $cp, $slice, $consistency_level); }
[ "public", "function", "get_subcolumn_count", "(", "$", "key", ",", "$", "super_column", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "$", "cp", "=", "$", "this", "->", "create_column_parent", "(", "$", "super_column", ")", ";", "$", "slice", "=", "$", "this", "->", "create_slice_predicate", "(", "$", "column_names", ",", "$", "column_slice", ",", "false", ",", "ColumnSlice", "::", "MAX_COUNT", ")", ";", "return", "$", "this", "->", "_get_count", "(", "$", "key", ",", "$", "cp", ",", "$", "slice", ",", "$", "consistency_level", ")", ";", "}" ]
Count the number of subcolumns in a supercolumn. @param string $key row to be counted @param mixed $super_column count only subcolumns in this super column @param \phpcassa\ColumnSlice a slice of subcolumns to count, or null @param mixed[] $column_names limit the possible subcolumns or counted to this list @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @return int
[ "Count", "the", "number", "of", "subcolumns", "in", "a", "supercolumn", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/SuperColumnFamily.php#L94-L105
232,863
dmitriybelyy/yii2-cassandra-cql
phpcassa/SuperColumnFamily.php
SuperColumnFamily.multiget_subcolumn_count
public function multiget_subcolumn_count($keys, $super_column, $column_slice=null, $column_names=null, $consistency_level=null) { $cp = $this->create_column_parent($super_column); $slice = $this->create_slice_predicate( $column_names, $column_slice, false, ColumnSlice::MAX_COUNT); return $this->_multiget_count($keys, $cp, $slice, $consistency_level); }
php
public function multiget_subcolumn_count($keys, $super_column, $column_slice=null, $column_names=null, $consistency_level=null) { $cp = $this->create_column_parent($super_column); $slice = $this->create_slice_predicate( $column_names, $column_slice, false, ColumnSlice::MAX_COUNT); return $this->_multiget_count($keys, $cp, $slice, $consistency_level); }
[ "public", "function", "multiget_subcolumn_count", "(", "$", "keys", ",", "$", "super_column", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "$", "cp", "=", "$", "this", "->", "create_column_parent", "(", "$", "super_column", ")", ";", "$", "slice", "=", "$", "this", "->", "create_slice_predicate", "(", "$", "column_names", ",", "$", "column_slice", ",", "false", ",", "ColumnSlice", "::", "MAX_COUNT", ")", ";", "return", "$", "this", "->", "_multiget_count", "(", "$", "keys", ",", "$", "cp", ",", "$", "slice", ",", "$", "consistency_level", ")", ";", "}" ]
Count the number of subcolumns in a particular super column across a set of rows. @param string[] $keys rows to be counted @param mixed $super_column count only subcolumns in this super column @param \phpcassa\ColumnSlice a slice of subcolumns to count, or null @param mixed[] $column_names limit the possible subcolumns counted to this list @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @return mixed array(row_key => subcolumn_count)
[ "Count", "the", "number", "of", "subcolumns", "in", "a", "particular", "super", "column", "across", "a", "set", "of", "rows", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/SuperColumnFamily.php#L120-L131
232,864
dmitriybelyy/yii2-cassandra-cql
phpcassa/SuperColumnFamily.php
SuperColumnFamily.get_super_column_range
public function get_super_column_range($super_column, $key_start="", $key_finish="", $row_count=self::DEFAULT_ROW_COUNT, $column_slice=null, $column_names=null, $consistency_level=null, $buffer_size=null) { $cp = $this->create_column_parent($super_column); $slice = $this->create_slice_predicate($column_names, $column_slice, false); return $this->_get_range($key_start, $key_finish, $row_count, $cp, $slice, $consistency_level, $buffer_size); }
php
public function get_super_column_range($super_column, $key_start="", $key_finish="", $row_count=self::DEFAULT_ROW_COUNT, $column_slice=null, $column_names=null, $consistency_level=null, $buffer_size=null) { $cp = $this->create_column_parent($super_column); $slice = $this->create_slice_predicate($column_names, $column_slice, false); return $this->_get_range($key_start, $key_finish, $row_count, $cp, $slice, $consistency_level, $buffer_size); }
[ "public", "function", "get_super_column_range", "(", "$", "super_column", ",", "$", "key_start", "=", "\"\"", ",", "$", "key_finish", "=", "\"\"", ",", "$", "row_count", "=", "self", "::", "DEFAULT_ROW_COUNT", ",", "$", "column_slice", "=", "null", ",", "$", "column_names", "=", "null", ",", "$", "consistency_level", "=", "null", ",", "$", "buffer_size", "=", "null", ")", "{", "$", "cp", "=", "$", "this", "->", "create_column_parent", "(", "$", "super_column", ")", ";", "$", "slice", "=", "$", "this", "->", "create_slice_predicate", "(", "$", "column_names", ",", "$", "column_slice", ",", "false", ")", ";", "return", "$", "this", "->", "_get_range", "(", "$", "key_start", ",", "$", "key_finish", ",", "$", "row_count", ",", "$", "cp", ",", "$", "slice", ",", "$", "consistency_level", ",", "$", "buffer_size", ")", ";", "}" ]
Get an iterator over a particular super column across a range of rows. The returned iterator will return one array per row. This array will look like array($rowkey, $subcolumns). Note that the super column layer is omitted from the results. @param mixed $super_column return only columns in this super column @param mixed $key_start fetch rows with a key >= this @param mixed $key_finish fetch rows with a key <= this @param int $row_count limit the number of rows returned to this amount @param \phpcassa\ColumnSlice a slice of subcolumns to fetch, or null @param mixed[] $column_names limit the subcolumns fetched to this list @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @param int $buffer_size When calling `get_range`, the intermediate results need to be buffered if we are fetching many rows, otherwise the Cassandra server will overallocate memory and fail. This is the size of that buffer in number of rows. @return phpcassa\Iterator\RangeColumnFamilyIterator
[ "Get", "an", "iterator", "over", "a", "particular", "super", "column", "across", "a", "range", "of", "rows", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/SuperColumnFamily.php#L155-L169
232,865
dmitriybelyy/yii2-cassandra-cql
phpcassa/SuperColumnFamily.php
SuperColumnFamily.add
public function add($key, $super_column, $column, $value=1, $consistency_level=null) { $packed_key = $this->pack_key($key); $cp = $this->create_column_parent($super_column); $counter = new CounterColumn(); $counter->name = $this->pack_name($column); $counter->value = $value; return $this->pool->call("add", $packed_key, $cp, $counter, $this->wcl($consistency_level)); }
php
public function add($key, $super_column, $column, $value=1, $consistency_level=null) { $packed_key = $this->pack_key($key); $cp = $this->create_column_parent($super_column); $counter = new CounterColumn(); $counter->name = $this->pack_name($column); $counter->value = $value; return $this->pool->call("add", $packed_key, $cp, $counter, $this->wcl($consistency_level)); }
[ "public", "function", "add", "(", "$", "key", ",", "$", "super_column", ",", "$", "column", ",", "$", "value", "=", "1", ",", "$", "consistency_level", "=", "null", ")", "{", "$", "packed_key", "=", "$", "this", "->", "pack_key", "(", "$", "key", ")", ";", "$", "cp", "=", "$", "this", "->", "create_column_parent", "(", "$", "super_column", ")", ";", "$", "counter", "=", "new", "CounterColumn", "(", ")", ";", "$", "counter", "->", "name", "=", "$", "this", "->", "pack_name", "(", "$", "column", ")", ";", "$", "counter", "->", "value", "=", "$", "value", ";", "return", "$", "this", "->", "pool", "->", "call", "(", "\"add\"", ",", "$", "packed_key", ",", "$", "cp", ",", "$", "counter", ",", "$", "this", "->", "wcl", "(", "$", "consistency_level", ")", ")", ";", "}" ]
Increment or decrement a counter. `value` should be an integer, either positive or negative, to be added to a counter column. By default, `value` is 1. This method is not idempotent. Retrying a failed add may result in a double count. You should consider using a separate ConnectionPool with retries disabled for column families with counters. Only available in Cassandra 0.8.0 and later. @param string $key the row to insert or update the columns in @param mixed $super_column the super column to use @param mixed $column the column name of the counter @param int $value the amount to adjust the counter by @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns
[ "Increment", "or", "decrement", "a", "counter", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/SuperColumnFamily.php#L191-L200
232,866
dmitriybelyy/yii2-cassandra-cql
phpcassa/SuperColumnFamily.php
SuperColumnFamily.remove_super_column
public function remove_super_column($key, $super_column, $subcolumns=null, $consistency_level=null) { if ($subcolumns === null || count($subcolumns) == 1) { $cp = new ColumnPath(); $cp->column_family = $this->column_family; $cp->super_column = $this->pack_name($super_column, true); if ($subcolumns !== null) { $cp->column = $this->pack_name($subcolumns[0], false); } return $this->_remove_single($key, $cp, $consistency_level); } else { $deletion = new Deletion(); $deletion->super_column = $this->pack_name($super_column, true); if ($subcolumns !== null) { $predicate = $this->create_slice_predicate($subcolumns, null, false); $deletion->predicate = $predicate; } return $this->_remove_multi($key, $deletion, $consistency_level); } }
php
public function remove_super_column($key, $super_column, $subcolumns=null, $consistency_level=null) { if ($subcolumns === null || count($subcolumns) == 1) { $cp = new ColumnPath(); $cp->column_family = $this->column_family; $cp->super_column = $this->pack_name($super_column, true); if ($subcolumns !== null) { $cp->column = $this->pack_name($subcolumns[0], false); } return $this->_remove_single($key, $cp, $consistency_level); } else { $deletion = new Deletion(); $deletion->super_column = $this->pack_name($super_column, true); if ($subcolumns !== null) { $predicate = $this->create_slice_predicate($subcolumns, null, false); $deletion->predicate = $predicate; } return $this->_remove_multi($key, $deletion, $consistency_level); } }
[ "public", "function", "remove_super_column", "(", "$", "key", ",", "$", "super_column", ",", "$", "subcolumns", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "if", "(", "$", "subcolumns", "===", "null", "||", "count", "(", "$", "subcolumns", ")", "==", "1", ")", "{", "$", "cp", "=", "new", "ColumnPath", "(", ")", ";", "$", "cp", "->", "column_family", "=", "$", "this", "->", "column_family", ";", "$", "cp", "->", "super_column", "=", "$", "this", "->", "pack_name", "(", "$", "super_column", ",", "true", ")", ";", "if", "(", "$", "subcolumns", "!==", "null", ")", "{", "$", "cp", "->", "column", "=", "$", "this", "->", "pack_name", "(", "$", "subcolumns", "[", "0", "]", ",", "false", ")", ";", "}", "return", "$", "this", "->", "_remove_single", "(", "$", "key", ",", "$", "cp", ",", "$", "consistency_level", ")", ";", "}", "else", "{", "$", "deletion", "=", "new", "Deletion", "(", ")", ";", "$", "deletion", "->", "super_column", "=", "$", "this", "->", "pack_name", "(", "$", "super_column", ",", "true", ")", ";", "if", "(", "$", "subcolumns", "!==", "null", ")", "{", "$", "predicate", "=", "$", "this", "->", "create_slice_predicate", "(", "$", "subcolumns", ",", "null", ",", "false", ")", ";", "$", "deletion", "->", "predicate", "=", "$", "predicate", ";", "}", "return", "$", "this", "->", "_remove_multi", "(", "$", "key", ",", "$", "deletion", ",", "$", "consistency_level", ")", ";", "}", "}" ]
Remove a super column from a row or a set of subcolumns from a single super column. @param string $key the row to remove columns from @param mixed $super_column only remove this super column or its subcolumns @param mixed[] $subcolumns the subcolumns to remove. If null, the entire supercolumn will be removed. @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns @return int the timestamp for the operation
[ "Remove", "a", "super", "column", "from", "a", "row", "or", "a", "set", "of", "subcolumns", "from", "a", "single", "super", "column", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/SuperColumnFamily.php#L215-L235
232,867
dmitriybelyy/yii2-cassandra-cql
phpcassa/SuperColumnFamily.php
SuperColumnFamily.remove_counter
public function remove_counter($key, $super_column, $column=null, $consistency_level=null) { $cp = new ColumnPath(); $packed_key = $this->pack_key($key); $cp->column_family = $this->column_family; $cp->super_column = $this->pack_name($super_column, true); if ($column !== null) $cp->column = $this->pack_name($column); $this->pool->call("remove_counter", $packed_key, $cp, $this->wcl($consistency_level)); }
php
public function remove_counter($key, $super_column, $column=null, $consistency_level=null) { $cp = new ColumnPath(); $packed_key = $this->pack_key($key); $cp->column_family = $this->column_family; $cp->super_column = $this->pack_name($super_column, true); if ($column !== null) $cp->column = $this->pack_name($column); $this->pool->call("remove_counter", $packed_key, $cp, $this->wcl($consistency_level)); }
[ "public", "function", "remove_counter", "(", "$", "key", ",", "$", "super_column", ",", "$", "column", "=", "null", ",", "$", "consistency_level", "=", "null", ")", "{", "$", "cp", "=", "new", "ColumnPath", "(", ")", ";", "$", "packed_key", "=", "$", "this", "->", "pack_key", "(", "$", "key", ")", ";", "$", "cp", "->", "column_family", "=", "$", "this", "->", "column_family", ";", "$", "cp", "->", "super_column", "=", "$", "this", "->", "pack_name", "(", "$", "super_column", ",", "true", ")", ";", "if", "(", "$", "column", "!==", "null", ")", "$", "cp", "->", "column", "=", "$", "this", "->", "pack_name", "(", "$", "column", ")", ";", "$", "this", "->", "pool", "->", "call", "(", "\"remove_counter\"", ",", "$", "packed_key", ",", "$", "cp", ",", "$", "this", "->", "wcl", "(", "$", "consistency_level", ")", ")", ";", "}" ]
Remove a counter at the specified location. Note that counters have limited support for deletes: if you remove a counter, you must wait to issue any following update until the delete has reached all the nodes and all of them have been fully compacted. Available in Cassandra 0.8.0 and later. @param string $key the key for the row @param mixed $super_column the super column the counter is in @param mixed $column the column name of the counter; if left as null, the entire super column will be removed @param ConsistencyLevel $consistency_level affects the guaranteed number of nodes that must respond before the operation returns
[ "Remove", "a", "counter", "at", "the", "specified", "location", "." ]
fa0fd4914444f64baba20848c7d4146c1b430346
https://github.com/dmitriybelyy/yii2-cassandra-cql/blob/fa0fd4914444f64baba20848c7d4146c1b430346/phpcassa/SuperColumnFamily.php#L253-L263
232,868
asinfotrack/yii2-toolbox
helpers/MigrationHelper.php
MigrationHelper.cacheMigrations
protected static function cacheMigrations() { //check if already cached if (static::$MIGRATION_CACHE !== null) return true; //check if there is a connection if (!static::hasDbConnection() || Yii::$app->db->schema->getTableSchema('{{%migration}}') === null) { return false; } //load the data static::$MIGRATION_CACHE = []; $migrationData = (new Query()) ->select(['version','apply_time']) ->from('{{%migration}}') ->orderBy(['apply_time'=>SORT_ASC]) ->all(); //fill the cache foreach ($migrationData as $migration) { static::$MIGRATION_CACHE[$migration['version']] = $migration['apply_time']; } return true; }
php
protected static function cacheMigrations() { //check if already cached if (static::$MIGRATION_CACHE !== null) return true; //check if there is a connection if (!static::hasDbConnection() || Yii::$app->db->schema->getTableSchema('{{%migration}}') === null) { return false; } //load the data static::$MIGRATION_CACHE = []; $migrationData = (new Query()) ->select(['version','apply_time']) ->from('{{%migration}}') ->orderBy(['apply_time'=>SORT_ASC]) ->all(); //fill the cache foreach ($migrationData as $migration) { static::$MIGRATION_CACHE[$migration['version']] = $migration['apply_time']; } return true; }
[ "protected", "static", "function", "cacheMigrations", "(", ")", "{", "//check if already cached", "if", "(", "static", "::", "$", "MIGRATION_CACHE", "!==", "null", ")", "return", "true", ";", "//check if there is a connection", "if", "(", "!", "static", "::", "hasDbConnection", "(", ")", "||", "Yii", "::", "$", "app", "->", "db", "->", "schema", "->", "getTableSchema", "(", "'{{%migration}}'", ")", "===", "null", ")", "{", "return", "false", ";", "}", "//load the data", "static", "::", "$", "MIGRATION_CACHE", "=", "[", "]", ";", "$", "migrationData", "=", "(", "new", "Query", "(", ")", ")", "->", "select", "(", "[", "'version'", ",", "'apply_time'", "]", ")", "->", "from", "(", "'{{%migration}}'", ")", "->", "orderBy", "(", "[", "'apply_time'", "=>", "SORT_ASC", "]", ")", "->", "all", "(", ")", ";", "//fill the cache", "foreach", "(", "$", "migrationData", "as", "$", "migration", ")", "{", "static", "::", "$", "MIGRATION_CACHE", "[", "$", "migration", "[", "'version'", "]", "]", "=", "$", "migration", "[", "'apply_time'", "]", ";", "}", "return", "true", ";", "}" ]
Caches the migrations internally in a static var for faster access in subsequent calls @return boolean true if caching was successful
[ "Caches", "the", "migrations", "internally", "in", "a", "static", "var", "for", "faster", "access", "in", "subsequent", "calls" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/MigrationHelper.php#L41-L65
232,869
bav-php/bav
classes/dataBackend/DataBackendContainer.php
DataBackendContainer.buildDataBackend
private function buildDataBackend() { $configuration = ConfigurationRegistry::getConfiguration(); $backend = $this->makeDataBackend(); // Installation if ($configuration->isAutomaticInstallation() && ! $backend->isInstalled()) { $lock = new Lock(self::INSTALL_LOCK); $lock->executeOnce( function () use ($backend) { $backend->install(); } ); } // Update hook register_shutdown_function(array($this, "applyUpdatePlan"), $backend); return $backend; }
php
private function buildDataBackend() { $configuration = ConfigurationRegistry::getConfiguration(); $backend = $this->makeDataBackend(); // Installation if ($configuration->isAutomaticInstallation() && ! $backend->isInstalled()) { $lock = new Lock(self::INSTALL_LOCK); $lock->executeOnce( function () use ($backend) { $backend->install(); } ); } // Update hook register_shutdown_function(array($this, "applyUpdatePlan"), $backend); return $backend; }
[ "private", "function", "buildDataBackend", "(", ")", "{", "$", "configuration", "=", "ConfigurationRegistry", "::", "getConfiguration", "(", ")", ";", "$", "backend", "=", "$", "this", "->", "makeDataBackend", "(", ")", ";", "// Installation", "if", "(", "$", "configuration", "->", "isAutomaticInstallation", "(", ")", "&&", "!", "$", "backend", "->", "isInstalled", "(", ")", ")", "{", "$", "lock", "=", "new", "Lock", "(", "self", "::", "INSTALL_LOCK", ")", ";", "$", "lock", "->", "executeOnce", "(", "function", "(", ")", "use", "(", "$", "backend", ")", "{", "$", "backend", "->", "install", "(", ")", ";", "}", ")", ";", "}", "// Update hook", "register_shutdown_function", "(", "array", "(", "$", "this", ",", "\"applyUpdatePlan\"", ")", ",", "$", "backend", ")", ";", "return", "$", "backend", ";", "}" ]
Builds a configured data backend. If configured this method would automatically install the backend. I.e. a first call will take some amount of time. @return DataBackend @throws DataBackendException
[ "Builds", "a", "configured", "data", "backend", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/DataBackendContainer.php#L44-L63
232,870
bav-php/bav
classes/dataBackend/DataBackendContainer.php
DataBackendContainer.applyUpdatePlan
public function applyUpdatePlan(DataBackend $backend) { $plan = ConfigurationRegistry::getConfiguration()->getUpdatePlan(); if ($plan != null && $plan->isOutdated($backend)) { $plan->perform($backend); } }
php
public function applyUpdatePlan(DataBackend $backend) { $plan = ConfigurationRegistry::getConfiguration()->getUpdatePlan(); if ($plan != null && $plan->isOutdated($backend)) { $plan->perform($backend); } }
[ "public", "function", "applyUpdatePlan", "(", "DataBackend", "$", "backend", ")", "{", "$", "plan", "=", "ConfigurationRegistry", "::", "getConfiguration", "(", ")", "->", "getUpdatePlan", "(", ")", ";", "if", "(", "$", "plan", "!=", "null", "&&", "$", "plan", "->", "isOutdated", "(", "$", "backend", ")", ")", "{", "$", "plan", "->", "perform", "(", "$", "backend", ")", ";", "}", "}" ]
Shut down hook for applying the update plan.
[ "Shut", "down", "hook", "for", "applying", "the", "update", "plan", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/DataBackendContainer.php#L68-L75
232,871
bav-php/bav
classes/dataBackend/DataBackendContainer.php
DataBackendContainer.getDataBackend
public function getDataBackend() { if (is_null($this->backend)) { $this->backend = $this->buildDataBackend(); } return $this->backend; }
php
public function getDataBackend() { if (is_null($this->backend)) { $this->backend = $this->buildDataBackend(); } return $this->backend; }
[ "public", "function", "getDataBackend", "(", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "backend", ")", ")", "{", "$", "this", "->", "backend", "=", "$", "this", "->", "buildDataBackend", "(", ")", ";", "}", "return", "$", "this", "->", "backend", ";", "}" ]
Returns a configured data backend. If configured this method would automatically install and update the backend. I.e. some calls might take longer. @see Configuration::setAutomaticInstallation() @see DataBackend::install() @return DataBackend
[ "Returns", "a", "configured", "data", "backend", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/DataBackendContainer.php#L87-L94
232,872
asinfotrack/yii2-toolbox
behaviors/StateBehavior.php
StateBehavior.checkAndAdvanceState
public function checkAndAdvanceState($runValidation=true) { $transaction = Yii::$app->db->beginTransaction(); while ($this->hasNextState()) { if ($this->advanceOneState(false)) { if (!$this->saveStateAttribute($runValidation)) { $transaction->rollBack(); return false; } } else { break; } } $transaction->commit(); return true; }
php
public function checkAndAdvanceState($runValidation=true) { $transaction = Yii::$app->db->beginTransaction(); while ($this->hasNextState()) { if ($this->advanceOneState(false)) { if (!$this->saveStateAttribute($runValidation)) { $transaction->rollBack(); return false; } } else { break; } } $transaction->commit(); return true; }
[ "public", "function", "checkAndAdvanceState", "(", "$", "runValidation", "=", "true", ")", "{", "$", "transaction", "=", "Yii", "::", "$", "app", "->", "db", "->", "beginTransaction", "(", ")", ";", "while", "(", "$", "this", "->", "hasNextState", "(", ")", ")", "{", "if", "(", "$", "this", "->", "advanceOneState", "(", "false", ")", ")", "{", "if", "(", "!", "$", "this", "->", "saveStateAttribute", "(", "$", "runValidation", ")", ")", "{", "$", "transaction", "->", "rollBack", "(", ")", ";", "return", "false", ";", "}", "}", "else", "{", "break", ";", "}", "}", "$", "transaction", "->", "commit", "(", ")", ";", "return", "true", ";", "}" ]
Advances the owners state if possible @param bool $runValidation if set to true, the owner will be validated before saving @return bool true if ok, false if something went wrong
[ "Advances", "the", "owners", "state", "if", "possible" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/StateBehavior.php#L107-L124
232,873
asinfotrack/yii2-toolbox
behaviors/StateBehavior.php
StateBehavior.requestState
public function requestState($stateValue, $runValidation=true) { //validate state and that it doesn't have it already $this->stateExists($stateValue, true); if ($this->isInState($stateValue)) { $reqStateCfg = $this->getStateConfig($stateValue); $msg = Yii::t('app', 'The model is already in the requested state {state}', ['state'=>$reqStateCfg['label']]); throw new InvalidCallException($msg); } //try advancing $transaction = Yii::$app->db->beginTransaction(); while (!$this->isInState($stateValue)) { if ($this->advanceOneState(true)) { if (!$this->saveStateAttribute($runValidation)) { $transaction->rollBack(); return false; } } else { break; } } $transaction->commit(); return $this->isEqualOrHigherThanState($stateValue); }
php
public function requestState($stateValue, $runValidation=true) { //validate state and that it doesn't have it already $this->stateExists($stateValue, true); if ($this->isInState($stateValue)) { $reqStateCfg = $this->getStateConfig($stateValue); $msg = Yii::t('app', 'The model is already in the requested state {state}', ['state'=>$reqStateCfg['label']]); throw new InvalidCallException($msg); } //try advancing $transaction = Yii::$app->db->beginTransaction(); while (!$this->isInState($stateValue)) { if ($this->advanceOneState(true)) { if (!$this->saveStateAttribute($runValidation)) { $transaction->rollBack(); return false; } } else { break; } } $transaction->commit(); return $this->isEqualOrHigherThanState($stateValue); }
[ "public", "function", "requestState", "(", "$", "stateValue", ",", "$", "runValidation", "=", "true", ")", "{", "//validate state and that it doesn't have it already", "$", "this", "->", "stateExists", "(", "$", "stateValue", ",", "true", ")", ";", "if", "(", "$", "this", "->", "isInState", "(", "$", "stateValue", ")", ")", "{", "$", "reqStateCfg", "=", "$", "this", "->", "getStateConfig", "(", "$", "stateValue", ")", ";", "$", "msg", "=", "Yii", "::", "t", "(", "'app'", ",", "'The model is already in the requested state {state}'", ",", "[", "'state'", "=>", "$", "reqStateCfg", "[", "'label'", "]", "]", ")", ";", "throw", "new", "InvalidCallException", "(", "$", "msg", ")", ";", "}", "//try advancing", "$", "transaction", "=", "Yii", "::", "$", "app", "->", "db", "->", "beginTransaction", "(", ")", ";", "while", "(", "!", "$", "this", "->", "isInState", "(", "$", "stateValue", ")", ")", "{", "if", "(", "$", "this", "->", "advanceOneState", "(", "true", ")", ")", "{", "if", "(", "!", "$", "this", "->", "saveStateAttribute", "(", "$", "runValidation", ")", ")", "{", "$", "transaction", "->", "rollBack", "(", ")", ";", "return", "false", ";", "}", "}", "else", "{", "break", ";", "}", "}", "$", "transaction", "->", "commit", "(", ")", ";", "return", "$", "this", "->", "isEqualOrHigherThanState", "(", "$", "stateValue", ")", ";", "}" ]
Request the model to change into a certain state. The model will try to iterate over all the states between its current and the desired state. @param integer|string $stateValue the desired target state @param bool $runValidation if set to true, the owner will be validated before saving @return bool true upon success
[ "Request", "the", "model", "to", "change", "into", "a", "certain", "state", ".", "The", "model", "will", "try", "to", "iterate", "over", "all", "the", "states", "between", "its", "current", "and", "the", "desired", "state", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/StateBehavior.php#L134-L159
232,874
asinfotrack/yii2-toolbox
behaviors/StateBehavior.php
StateBehavior.advanceOneState
protected function advanceOneState($isManualRequest) { if (!$this->hasNextState()) return false; $nextCfg = $this->getStateConfig($this->getNextState()); //check preconditions if (!$this->meetsStatePreconditions($nextCfg['value'])) return false; //check auto entering if (!$isManualRequest) { $ae = $nextCfg['autoEnter']; $resAe = $ae instanceof \Closure ? call_user_func($ae, $this->owner, $nextCfg) : $ae; if (!$resAe) return false; } $this->owner->{$this->stateAttribute} = $nextCfg['value']; return true; }
php
protected function advanceOneState($isManualRequest) { if (!$this->hasNextState()) return false; $nextCfg = $this->getStateConfig($this->getNextState()); //check preconditions if (!$this->meetsStatePreconditions($nextCfg['value'])) return false; //check auto entering if (!$isManualRequest) { $ae = $nextCfg['autoEnter']; $resAe = $ae instanceof \Closure ? call_user_func($ae, $this->owner, $nextCfg) : $ae; if (!$resAe) return false; } $this->owner->{$this->stateAttribute} = $nextCfg['value']; return true; }
[ "protected", "function", "advanceOneState", "(", "$", "isManualRequest", ")", "{", "if", "(", "!", "$", "this", "->", "hasNextState", "(", ")", ")", "return", "false", ";", "$", "nextCfg", "=", "$", "this", "->", "getStateConfig", "(", "$", "this", "->", "getNextState", "(", ")", ")", ";", "//check preconditions", "if", "(", "!", "$", "this", "->", "meetsStatePreconditions", "(", "$", "nextCfg", "[", "'value'", "]", ")", ")", "return", "false", ";", "//check auto entering", "if", "(", "!", "$", "isManualRequest", ")", "{", "$", "ae", "=", "$", "nextCfg", "[", "'autoEnter'", "]", ";", "$", "resAe", "=", "$", "ae", "instanceof", "\\", "Closure", "?", "call_user_func", "(", "$", "ae", ",", "$", "this", "->", "owner", ",", "$", "nextCfg", ")", ":", "$", "ae", ";", "if", "(", "!", "$", "resAe", ")", "return", "false", ";", "}", "$", "this", "->", "owner", "->", "{", "$", "this", "->", "stateAttribute", "}", "=", "$", "nextCfg", "[", "'value'", "]", ";", "return", "true", ";", "}" ]
Does the actual work to advance one single state. @param bool $isManualRequest if set to true, a manual request is indicated if a preconditionCallback is present @return bool true upon success
[ "Does", "the", "actual", "work", "to", "advance", "one", "single", "state", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/StateBehavior.php#L168-L186
232,875
asinfotrack/yii2-toolbox
behaviors/StateBehavior.php
StateBehavior.meetsStatePreconditions
public function meetsStatePreconditions($stateValue) { $config = $this->getStateConfig($stateValue); if (isset($config['preconditionCallback'])) { return call_user_func($config['preconditionCallback'], $this->owner, $config); } else { return true; } }
php
public function meetsStatePreconditions($stateValue) { $config = $this->getStateConfig($stateValue); if (isset($config['preconditionCallback'])) { return call_user_func($config['preconditionCallback'], $this->owner, $config); } else { return true; } }
[ "public", "function", "meetsStatePreconditions", "(", "$", "stateValue", ")", "{", "$", "config", "=", "$", "this", "->", "getStateConfig", "(", "$", "stateValue", ")", ";", "if", "(", "isset", "(", "$", "config", "[", "'preconditionCallback'", "]", ")", ")", "{", "return", "call_user_func", "(", "$", "config", "[", "'preconditionCallback'", "]", ",", "$", "this", "->", "owner", ",", "$", "config", ")", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
Checks if the preconditions for a state are met @param integer|string $stateValue the value of the state to check @return bool true if an anonymous function is set and preconditions are met
[ "Checks", "if", "the", "preconditions", "for", "a", "state", "are", "met" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/StateBehavior.php#L251-L259
232,876
asinfotrack/yii2-toolbox
behaviors/StateBehavior.php
StateBehavior.stateExists
public function stateExists($stateValue, $throwException=false) { if (isset($this->cacheConfigMap[$stateValue])) { return true; } else if ($throwException) { $msg = Yii::t('app', 'There is no state with the value {val}', ['val'=>$stateValue]); throw new InvalidParamException($msg); } else { return false; } }
php
public function stateExists($stateValue, $throwException=false) { if (isset($this->cacheConfigMap[$stateValue])) { return true; } else if ($throwException) { $msg = Yii::t('app', 'There is no state with the value {val}', ['val'=>$stateValue]); throw new InvalidParamException($msg); } else { return false; } }
[ "public", "function", "stateExists", "(", "$", "stateValue", ",", "$", "throwException", "=", "false", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "cacheConfigMap", "[", "$", "stateValue", "]", ")", ")", "{", "return", "true", ";", "}", "else", "if", "(", "$", "throwException", ")", "{", "$", "msg", "=", "Yii", "::", "t", "(", "'app'", ",", "'There is no state with the value {val}'", ",", "[", "'val'", "=>", "$", "stateValue", "]", ")", ";", "throw", "new", "InvalidParamException", "(", "$", "msg", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Returns whether or not a state exists in the current config @param integer|string $stateValue the actual state value @param bool $throwException if set to true an exception will be thrown when the state doesn't exist @return bool true if it exists @throws InvalidParamException if it doesn't exist and exception is desired
[ "Returns", "whether", "or", "not", "a", "state", "exists", "in", "the", "current", "config" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/StateBehavior.php#L270-L280
232,877
asinfotrack/yii2-toolbox
behaviors/StateBehavior.php
StateBehavior.getStateConfig
public function getStateConfig($stateValue=null) { if ($stateValue === null) { $stateValue = $this->owner->{$this->stateAttribute}; } else { $this->stateExists($stateValue, true); } return $this->cacheConfigMap[$stateValue]; }
php
public function getStateConfig($stateValue=null) { if ($stateValue === null) { $stateValue = $this->owner->{$this->stateAttribute}; } else { $this->stateExists($stateValue, true); } return $this->cacheConfigMap[$stateValue]; }
[ "public", "function", "getStateConfig", "(", "$", "stateValue", "=", "null", ")", "{", "if", "(", "$", "stateValue", "===", "null", ")", "{", "$", "stateValue", "=", "$", "this", "->", "owner", "->", "{", "$", "this", "->", "stateAttribute", "}", ";", "}", "else", "{", "$", "this", "->", "stateExists", "(", "$", "stateValue", ",", "true", ")", ";", "}", "return", "$", "this", "->", "cacheConfigMap", "[", "$", "stateValue", "]", ";", "}" ]
Gets the config for a state @param integer|string $stateValue the value to get the config for (defaults to the owners current state) @return array config of the state @throws InvalidParamException if a state doesn't exist
[ "Gets", "the", "config", "for", "a", "state" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/StateBehavior.php#L299-L307
232,878
asinfotrack/yii2-toolbox
behaviors/StateBehavior.php
StateBehavior.hasNextState
public function hasNextState() { return $this->cacheIndexMap[$this->owner->{$this->stateAttribute}] + 1 < count($this->stateConfig); }
php
public function hasNextState() { return $this->cacheIndexMap[$this->owner->{$this->stateAttribute}] + 1 < count($this->stateConfig); }
[ "public", "function", "hasNextState", "(", ")", "{", "return", "$", "this", "->", "cacheIndexMap", "[", "$", "this", "->", "owner", "->", "{", "$", "this", "->", "stateAttribute", "}", "]", "+", "1", "<", "count", "(", "$", "this", "->", "stateConfig", ")", ";", "}" ]
Returns whether or not there are states after the current one @return bool true if there is a next state
[ "Returns", "whether", "or", "not", "there", "are", "states", "after", "the", "current", "one" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/StateBehavior.php#L314-L317
232,879
asinfotrack/yii2-toolbox
behaviors/StateBehavior.php
StateBehavior.getNextState
public function getNextState($stateValue=null, $configInsteadOfValue=false) { if ($stateValue === null) { $stateValue = $this->owner->{$this->stateAttribute}; } else { $this->stateExists($stateValue, true); } if ($this->hasNextState()) { $nextConfig = $this->stateConfig[$this->cacheIndexMap[$stateValue] + 1]; return $configInsteadOfValue ? $nextConfig : $nextConfig['value']; } else { return null; } }
php
public function getNextState($stateValue=null, $configInsteadOfValue=false) { if ($stateValue === null) { $stateValue = $this->owner->{$this->stateAttribute}; } else { $this->stateExists($stateValue, true); } if ($this->hasNextState()) { $nextConfig = $this->stateConfig[$this->cacheIndexMap[$stateValue] + 1]; return $configInsteadOfValue ? $nextConfig : $nextConfig['value']; } else { return null; } }
[ "public", "function", "getNextState", "(", "$", "stateValue", "=", "null", ",", "$", "configInsteadOfValue", "=", "false", ")", "{", "if", "(", "$", "stateValue", "===", "null", ")", "{", "$", "stateValue", "=", "$", "this", "->", "owner", "->", "{", "$", "this", "->", "stateAttribute", "}", ";", "}", "else", "{", "$", "this", "->", "stateExists", "(", "$", "stateValue", ",", "true", ")", ";", "}", "if", "(", "$", "this", "->", "hasNextState", "(", ")", ")", "{", "$", "nextConfig", "=", "$", "this", "->", "stateConfig", "[", "$", "this", "->", "cacheIndexMap", "[", "$", "stateValue", "]", "+", "1", "]", ";", "return", "$", "configInsteadOfValue", "?", "$", "nextConfig", ":", "$", "nextConfig", "[", "'value'", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the next states config or value if there is one. If the current state is the last step, null is returned. @param integer|string $stateValue the value to get the next state for (defaults to the owners current state) @param bool $configInsteadOfValue if set to true, the config of the next state is returned @return mixed|array|null either the next states value / config or null if no next state
[ "Returns", "the", "next", "states", "config", "or", "value", "if", "there", "is", "one", ".", "If", "the", "current", "state", "is", "the", "last", "step", "null", "is", "returned", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/StateBehavior.php#L327-L341
232,880
asinfotrack/yii2-toolbox
behaviors/StateBehavior.php
StateBehavior.validateStateConfig
protected function validateStateConfig() { if (empty($this->stateConfig)) { $msg = Yii::t('app', 'Empty state configurations are not allowed'); throw new InvalidConfigException($msg); } $config = &$this->stateConfig; foreach ($config as $i=>&$state) { //validate label and value if (empty($state['value']) || empty($state['label'])) { $msg = Yii::t('app', 'The label and the value of a state are mandatory'); throw new InvalidConfigException($msg); } if (!is_int($state['value']) && !is_string($state['value'])) { $msg = Yii::t('app', 'The value must be a string or an integer ({lbl})', ['lbl'=>$state['label']]); throw new InvalidConfigException($msg); } //validate closures $callbackAttributes = ['preconditionCallback', 'enterStateCallback', 'leaveStateCallback']; foreach ($callbackAttributes as $cbAttr) { if (isset($state[$cbAttr]) && !($state[$cbAttr] instanceof \Closure)) { $msg = Yii::t('app', 'For {cb-attr} only closures are allowed', ['cb-attr'=>$cbAttr]); throw new InvalidConfigException($msg); } } //default settings if (!isset($state['groups'])) $state['groups'] = []; if (!isset($state['autoEnter'])) $state['autoEnter'] = true; //validate groups foreach ($state['groups'] as &$group) { if (!is_string($group)) { $msg = Yii::t('app', 'Only strings allowed for group names'); throw new InvalidConfigException($msg); } $group = strtolower($group); } } return true; }
php
protected function validateStateConfig() { if (empty($this->stateConfig)) { $msg = Yii::t('app', 'Empty state configurations are not allowed'); throw new InvalidConfigException($msg); } $config = &$this->stateConfig; foreach ($config as $i=>&$state) { //validate label and value if (empty($state['value']) || empty($state['label'])) { $msg = Yii::t('app', 'The label and the value of a state are mandatory'); throw new InvalidConfigException($msg); } if (!is_int($state['value']) && !is_string($state['value'])) { $msg = Yii::t('app', 'The value must be a string or an integer ({lbl})', ['lbl'=>$state['label']]); throw new InvalidConfigException($msg); } //validate closures $callbackAttributes = ['preconditionCallback', 'enterStateCallback', 'leaveStateCallback']; foreach ($callbackAttributes as $cbAttr) { if (isset($state[$cbAttr]) && !($state[$cbAttr] instanceof \Closure)) { $msg = Yii::t('app', 'For {cb-attr} only closures are allowed', ['cb-attr'=>$cbAttr]); throw new InvalidConfigException($msg); } } //default settings if (!isset($state['groups'])) $state['groups'] = []; if (!isset($state['autoEnter'])) $state['autoEnter'] = true; //validate groups foreach ($state['groups'] as &$group) { if (!is_string($group)) { $msg = Yii::t('app', 'Only strings allowed for group names'); throw new InvalidConfigException($msg); } $group = strtolower($group); } } return true; }
[ "protected", "function", "validateStateConfig", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "stateConfig", ")", ")", "{", "$", "msg", "=", "Yii", "::", "t", "(", "'app'", ",", "'Empty state configurations are not allowed'", ")", ";", "throw", "new", "InvalidConfigException", "(", "$", "msg", ")", ";", "}", "$", "config", "=", "&", "$", "this", "->", "stateConfig", ";", "foreach", "(", "$", "config", "as", "$", "i", "=>", "&", "$", "state", ")", "{", "//validate label and value", "if", "(", "empty", "(", "$", "state", "[", "'value'", "]", ")", "||", "empty", "(", "$", "state", "[", "'label'", "]", ")", ")", "{", "$", "msg", "=", "Yii", "::", "t", "(", "'app'", ",", "'The label and the value of a state are mandatory'", ")", ";", "throw", "new", "InvalidConfigException", "(", "$", "msg", ")", ";", "}", "if", "(", "!", "is_int", "(", "$", "state", "[", "'value'", "]", ")", "&&", "!", "is_string", "(", "$", "state", "[", "'value'", "]", ")", ")", "{", "$", "msg", "=", "Yii", "::", "t", "(", "'app'", ",", "'The value must be a string or an integer ({lbl})'", ",", "[", "'lbl'", "=>", "$", "state", "[", "'label'", "]", "]", ")", ";", "throw", "new", "InvalidConfigException", "(", "$", "msg", ")", ";", "}", "//validate closures", "$", "callbackAttributes", "=", "[", "'preconditionCallback'", ",", "'enterStateCallback'", ",", "'leaveStateCallback'", "]", ";", "foreach", "(", "$", "callbackAttributes", "as", "$", "cbAttr", ")", "{", "if", "(", "isset", "(", "$", "state", "[", "$", "cbAttr", "]", ")", "&&", "!", "(", "$", "state", "[", "$", "cbAttr", "]", "instanceof", "\\", "Closure", ")", ")", "{", "$", "msg", "=", "Yii", "::", "t", "(", "'app'", ",", "'For {cb-attr} only closures are allowed'", ",", "[", "'cb-attr'", "=>", "$", "cbAttr", "]", ")", ";", "throw", "new", "InvalidConfigException", "(", "$", "msg", ")", ";", "}", "}", "//default settings", "if", "(", "!", "isset", "(", "$", "state", "[", "'groups'", "]", ")", ")", "$", "state", "[", "'groups'", "]", "=", "[", "]", ";", "if", "(", "!", "isset", "(", "$", "state", "[", "'autoEnter'", "]", ")", ")", "$", "state", "[", "'autoEnter'", "]", "=", "true", ";", "//validate groups", "foreach", "(", "$", "state", "[", "'groups'", "]", "as", "&", "$", "group", ")", "{", "if", "(", "!", "is_string", "(", "$", "group", ")", ")", "{", "$", "msg", "=", "Yii", "::", "t", "(", "'app'", ",", "'Only strings allowed for group names'", ")", ";", "throw", "new", "InvalidConfigException", "(", "$", "msg", ")", ";", "}", "$", "group", "=", "strtolower", "(", "$", "group", ")", ";", "}", "}", "return", "true", ";", "}" ]
Validates the state configuration @return bool true if config is ok @throws \yii\base\InvalidConfigException when config is illegal
[ "Validates", "the", "state", "configuration" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/StateBehavior.php#L388-L431
232,881
asinfotrack/yii2-toolbox
behaviors/StateBehavior.php
StateBehavior.saveStateAttribute
protected function saveStateAttribute($runValidation) { /* @var $owner \yii\db\ActiveRecord */ $owner = $this->owner; //catch unchanged state attribute if (!$this->hasChangedStateAttribute()) return false; //fetch relevant configs $curCfg = $this->getStateConfig($owner->getOldAttribute($this->stateAttribute)); $nextCfg = $this->getStateConfig(); //call leave state callback on old state if (isset($curCfg['leaveStateCallback'])) { call_user_func($curCfg['leaveStateCallback'], $owner, $curCfg); } //save it if ($owner->save($runValidation, [$this->stateAttribute])) { //call enter state callback on new state if (isset($nextCfg['enterStateCallback'])) { call_user_func($nextCfg['enterStateCallback'], $owner, $nextCfg); } return true; } else { return false; } }
php
protected function saveStateAttribute($runValidation) { /* @var $owner \yii\db\ActiveRecord */ $owner = $this->owner; //catch unchanged state attribute if (!$this->hasChangedStateAttribute()) return false; //fetch relevant configs $curCfg = $this->getStateConfig($owner->getOldAttribute($this->stateAttribute)); $nextCfg = $this->getStateConfig(); //call leave state callback on old state if (isset($curCfg['leaveStateCallback'])) { call_user_func($curCfg['leaveStateCallback'], $owner, $curCfg); } //save it if ($owner->save($runValidation, [$this->stateAttribute])) { //call enter state callback on new state if (isset($nextCfg['enterStateCallback'])) { call_user_func($nextCfg['enterStateCallback'], $owner, $nextCfg); } return true; } else { return false; } }
[ "protected", "function", "saveStateAttribute", "(", "$", "runValidation", ")", "{", "/* @var $owner \\yii\\db\\ActiveRecord */", "$", "owner", "=", "$", "this", "->", "owner", ";", "//catch unchanged state attribute", "if", "(", "!", "$", "this", "->", "hasChangedStateAttribute", "(", ")", ")", "return", "false", ";", "//fetch relevant configs", "$", "curCfg", "=", "$", "this", "->", "getStateConfig", "(", "$", "owner", "->", "getOldAttribute", "(", "$", "this", "->", "stateAttribute", ")", ")", ";", "$", "nextCfg", "=", "$", "this", "->", "getStateConfig", "(", ")", ";", "//call leave state callback on old state", "if", "(", "isset", "(", "$", "curCfg", "[", "'leaveStateCallback'", "]", ")", ")", "{", "call_user_func", "(", "$", "curCfg", "[", "'leaveStateCallback'", "]", ",", "$", "owner", ",", "$", "curCfg", ")", ";", "}", "//save it", "if", "(", "$", "owner", "->", "save", "(", "$", "runValidation", ",", "[", "$", "this", "->", "stateAttribute", "]", ")", ")", "{", "//call enter state callback on new state", "if", "(", "isset", "(", "$", "nextCfg", "[", "'enterStateCallback'", "]", ")", ")", "{", "call_user_func", "(", "$", "nextCfg", "[", "'enterStateCallback'", "]", ",", "$", "owner", ",", "$", "nextCfg", ")", ";", "}", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Saves the state attribute @param bool $runValidation whether or not to validate the state attribute @return bool true if successfully saved
[ "Saves", "the", "state", "attribute" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/behaviors/StateBehavior.php#L439-L466
232,882
mnapoli/dbal-schema
src/DbalSchemaCommand.php
DbalSchemaCommand.update
public function update(bool $force, OutputInterface $output) { $newSchema = new Schema(); $this->schemaDefinition->define($newSchema); $currentSchema = $this->db->getSchemaManager()->createSchema(); $migrationQueries = $currentSchema->getMigrateToSql($newSchema, $this->db->getDatabasePlatform()); $this->db->transactional(function () use ($migrationQueries, $force, $output) { foreach ($migrationQueries as $query) { $output->writeln(sprintf('Running <info>%s</info>', $query)); if ($force) { $this->db->exec($query); } } if (empty($migrationQueries)) { $output->writeln('<info>The database is up to date</info>'); } }); if (!$force) { $output->writeln('<comment>No query was run, use the --force option to run the queries</comment>'); } else { $output->writeln('<comment>Queries were successfully run against the database</comment>'); } }
php
public function update(bool $force, OutputInterface $output) { $newSchema = new Schema(); $this->schemaDefinition->define($newSchema); $currentSchema = $this->db->getSchemaManager()->createSchema(); $migrationQueries = $currentSchema->getMigrateToSql($newSchema, $this->db->getDatabasePlatform()); $this->db->transactional(function () use ($migrationQueries, $force, $output) { foreach ($migrationQueries as $query) { $output->writeln(sprintf('Running <info>%s</info>', $query)); if ($force) { $this->db->exec($query); } } if (empty($migrationQueries)) { $output->writeln('<info>The database is up to date</info>'); } }); if (!$force) { $output->writeln('<comment>No query was run, use the --force option to run the queries</comment>'); } else { $output->writeln('<comment>Queries were successfully run against the database</comment>'); } }
[ "public", "function", "update", "(", "bool", "$", "force", ",", "OutputInterface", "$", "output", ")", "{", "$", "newSchema", "=", "new", "Schema", "(", ")", ";", "$", "this", "->", "schemaDefinition", "->", "define", "(", "$", "newSchema", ")", ";", "$", "currentSchema", "=", "$", "this", "->", "db", "->", "getSchemaManager", "(", ")", "->", "createSchema", "(", ")", ";", "$", "migrationQueries", "=", "$", "currentSchema", "->", "getMigrateToSql", "(", "$", "newSchema", ",", "$", "this", "->", "db", "->", "getDatabasePlatform", "(", ")", ")", ";", "$", "this", "->", "db", "->", "transactional", "(", "function", "(", ")", "use", "(", "$", "migrationQueries", ",", "$", "force", ",", "$", "output", ")", "{", "foreach", "(", "$", "migrationQueries", "as", "$", "query", ")", "{", "$", "output", "->", "writeln", "(", "sprintf", "(", "'Running <info>%s</info>'", ",", "$", "query", ")", ")", ";", "if", "(", "$", "force", ")", "{", "$", "this", "->", "db", "->", "exec", "(", "$", "query", ")", ";", "}", "}", "if", "(", "empty", "(", "$", "migrationQueries", ")", ")", "{", "$", "output", "->", "writeln", "(", "'<info>The database is up to date</info>'", ")", ";", "}", "}", ")", ";", "if", "(", "!", "$", "force", ")", "{", "$", "output", "->", "writeln", "(", "'<comment>No query was run, use the --force option to run the queries</comment>'", ")", ";", "}", "else", "{", "$", "output", "->", "writeln", "(", "'<comment>Queries were successfully run against the database</comment>'", ")", ";", "}", "}" ]
Update the database schema to match the schema definition.
[ "Update", "the", "database", "schema", "to", "match", "the", "schema", "definition", "." ]
2d4022fee5c7bb0886da87bcb08dc24f622b800b
https://github.com/mnapoli/dbal-schema/blob/2d4022fee5c7bb0886da87bcb08dc24f622b800b/src/DbalSchemaCommand.php#L34-L59
232,883
mnapoli/dbal-schema
src/DbalSchemaCommand.php
DbalSchemaCommand.purge
public function purge(bool $force, OutputInterface $output) { $tables = $this->db->getSchemaManager()->listTableNames(); foreach ($tables as $table) { $output->writeln("<info>Dropping table $table</info>"); if ($force) { $this->db->getSchemaManager()->dropTable($table); } } if (!$force) { $output->writeln('<comment>No query was run, use the --force option to run the queries</comment>'); } else { $output->writeln('<comment>Queries were successfully run against the database</comment>'); } $this->update($force, $output); }
php
public function purge(bool $force, OutputInterface $output) { $tables = $this->db->getSchemaManager()->listTableNames(); foreach ($tables as $table) { $output->writeln("<info>Dropping table $table</info>"); if ($force) { $this->db->getSchemaManager()->dropTable($table); } } if (!$force) { $output->writeln('<comment>No query was run, use the --force option to run the queries</comment>'); } else { $output->writeln('<comment>Queries were successfully run against the database</comment>'); } $this->update($force, $output); }
[ "public", "function", "purge", "(", "bool", "$", "force", ",", "OutputInterface", "$", "output", ")", "{", "$", "tables", "=", "$", "this", "->", "db", "->", "getSchemaManager", "(", ")", "->", "listTableNames", "(", ")", ";", "foreach", "(", "$", "tables", "as", "$", "table", ")", "{", "$", "output", "->", "writeln", "(", "\"<info>Dropping table $table</info>\"", ")", ";", "if", "(", "$", "force", ")", "{", "$", "this", "->", "db", "->", "getSchemaManager", "(", ")", "->", "dropTable", "(", "$", "table", ")", ";", "}", "}", "if", "(", "!", "$", "force", ")", "{", "$", "output", "->", "writeln", "(", "'<comment>No query was run, use the --force option to run the queries</comment>'", ")", ";", "}", "else", "{", "$", "output", "->", "writeln", "(", "'<comment>Queries were successfully run against the database</comment>'", ")", ";", "}", "$", "this", "->", "update", "(", "$", "force", ",", "$", "output", ")", ";", "}" ]
Drops all the tables and re-creates them.
[ "Drops", "all", "the", "tables", "and", "re", "-", "creates", "them", "." ]
2d4022fee5c7bb0886da87bcb08dc24f622b800b
https://github.com/mnapoli/dbal-schema/blob/2d4022fee5c7bb0886da87bcb08dc24f622b800b/src/DbalSchemaCommand.php#L64-L81
232,884
bigpaulie/yii2-social-share
src/Share.php
Share.run
public function run() { echo Html::beginTag($this->tag, $this->htmlOptions); $networks = $this->getNetworks(); $networks_available = $this->include ?: array_keys($networks); foreach ($networks_available as $network) { echo $this->parseTemplate($network); } echo Html::endTag($this->tag); }
php
public function run() { echo Html::beginTag($this->tag, $this->htmlOptions); $networks = $this->getNetworks(); $networks_available = $this->include ?: array_keys($networks); foreach ($networks_available as $network) { echo $this->parseTemplate($network); } echo Html::endTag($this->tag); }
[ "public", "function", "run", "(", ")", "{", "echo", "Html", "::", "beginTag", "(", "$", "this", "->", "tag", ",", "$", "this", "->", "htmlOptions", ")", ";", "$", "networks", "=", "$", "this", "->", "getNetworks", "(", ")", ";", "$", "networks_available", "=", "$", "this", "->", "include", "?", ":", "array_keys", "(", "$", "networks", ")", ";", "foreach", "(", "$", "networks_available", "as", "$", "network", ")", "{", "echo", "$", "this", "->", "parseTemplate", "(", "$", "network", ")", ";", "}", "echo", "Html", "::", "endTag", "(", "$", "this", "->", "tag", ")", ";", "}" ]
Build the HTML
[ "Build", "the", "HTML" ]
49a0855616a52387997af5ce123040d762724bec
https://github.com/bigpaulie/yii2-social-share/blob/49a0855616a52387997af5ce123040d762724bec/src/Share.php#L17-L27
232,885
silverstripe-archive/deploynaut
code/backends/PackageGenerator.php
PackageGenerator.getPackageFilename
function getPackageFilename($identifier, $sha, $repositoryDir, DeploynautLogFile $log) { // Fetch through the cache if($this->cache) { $identifier .= '-' . get_class($this) . '-' . $this->getIdentifier(); return $this->cache->getPackageFilename($this, $identifier, $sha, $repositoryDir, $log); // Default, cacheless implementation } else { $filename = TEMP_FOLDER .'/' . $sha . '.tar.gz'; if($this->generatePackage($sha, $repositoryDir, $outputFilename, $log)) { return $filename; } } }
php
function getPackageFilename($identifier, $sha, $repositoryDir, DeploynautLogFile $log) { // Fetch through the cache if($this->cache) { $identifier .= '-' . get_class($this) . '-' . $this->getIdentifier(); return $this->cache->getPackageFilename($this, $identifier, $sha, $repositoryDir, $log); // Default, cacheless implementation } else { $filename = TEMP_FOLDER .'/' . $sha . '.tar.gz'; if($this->generatePackage($sha, $repositoryDir, $outputFilename, $log)) { return $filename; } } }
[ "function", "getPackageFilename", "(", "$", "identifier", ",", "$", "sha", ",", "$", "repositoryDir", ",", "DeploynautLogFile", "$", "log", ")", "{", "// Fetch through the cache", "if", "(", "$", "this", "->", "cache", ")", "{", "$", "identifier", ".=", "'-'", ".", "get_class", "(", "$", "this", ")", ".", "'-'", ".", "$", "this", "->", "getIdentifier", "(", ")", ";", "return", "$", "this", "->", "cache", "->", "getPackageFilename", "(", "$", "this", ",", "$", "identifier", ",", "$", "sha", ",", "$", "repositoryDir", ",", "$", "log", ")", ";", "// Default, cacheless implementation", "}", "else", "{", "$", "filename", "=", "TEMP_FOLDER", ".", "'/'", ".", "$", "sha", ".", "'.tar.gz'", ";", "if", "(", "$", "this", "->", "generatePackage", "(", "$", "sha", ",", "$", "repositoryDir", ",", "$", "outputFilename", ",", "$", "log", ")", ")", "{", "return", "$", "filename", ";", "}", "}", "}" ]
Generate or retrieve a package from the cache @param string $identifier A unique identifier for the generator; used to partition the cache @param string $sha The SHA of the commit to be deployed @param string $repositoryDir The directory where the repository resides @param DeploynautLogFile $log The log to write status output to, including package-generation commands
[ "Generate", "or", "retrieve", "a", "package", "from", "the", "cache" ]
0b04dadcd089f606d99728f7ee57f374a06211c9
https://github.com/silverstripe-archive/deploynaut/blob/0b04dadcd089f606d99728f7ee57f374a06211c9/code/backends/PackageGenerator.php#L48-L61
232,886
bav-php/bav
classes/dataBackend/DataBackend.php
DataBackend.getBank
public function getBank($bankID) { if (! isset($this->instances[$bankID])) { $this->instances[$bankID] = $this->getNewBank($bankID); } return $this->instances[$bankID]; }
php
public function getBank($bankID) { if (! isset($this->instances[$bankID])) { $this->instances[$bankID] = $this->getNewBank($bankID); } return $this->instances[$bankID]; }
[ "public", "function", "getBank", "(", "$", "bankID", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "instances", "[", "$", "bankID", "]", ")", ")", "{", "$", "this", "->", "instances", "[", "$", "bankID", "]", "=", "$", "this", "->", "getNewBank", "(", "$", "bankID", ")", ";", "}", "return", "$", "this", "->", "instances", "[", "$", "bankID", "]", ";", "}" ]
With this method you get the Bank objects for certain IDs. Note that a call to this method with an identical id will return the same objects. @throws BankNotFoundException @throws DataBackendException @param string @return Bank
[ "With", "this", "method", "you", "get", "the", "Bank", "objects", "for", "certain", "IDs", ".", "Note", "that", "a", "call", "to", "this", "method", "with", "an", "identical", "id", "will", "return", "the", "same", "objects", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/dataBackend/DataBackend.php#L80-L87
232,887
bav-php/bav
classes/util/Lock.php
Lock.executeOnce
public function executeOnce(\Closure $task) { $isBlocked = $this->checkedLock(); $error = null; try { if (! $isBlocked) { call_user_func($task); } } catch (\Exception $e) { $error = $e; } $this->unlock(); if (! is_null($error)) { throw $error; } }
php
public function executeOnce(\Closure $task) { $isBlocked = $this->checkedLock(); $error = null; try { if (! $isBlocked) { call_user_func($task); } } catch (\Exception $e) { $error = $e; } $this->unlock(); if (! is_null($error)) { throw $error; } }
[ "public", "function", "executeOnce", "(", "\\", "Closure", "$", "task", ")", "{", "$", "isBlocked", "=", "$", "this", "->", "checkedLock", "(", ")", ";", "$", "error", "=", "null", ";", "try", "{", "if", "(", "!", "$", "isBlocked", ")", "{", "call_user_func", "(", "$", "task", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "error", "=", "$", "e", ";", "}", "$", "this", "->", "unlock", "(", ")", ";", "if", "(", "!", "is_null", "(", "$", "error", ")", ")", "{", "throw", "$", "error", ";", "}", "}" ]
Get a lock and execute a task. If more processes call this method only the process which aquired the lock will execute the task. The others will block but won't execute the task. @throws Exception
[ "Get", "a", "lock", "and", "execute", "a", "task", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/util/Lock.php#L52-L70
232,888
bav-php/bav
classes/util/Lock.php
Lock.nonblockingExecuteOnce
public function nonblockingExecuteOnce(\Closure $task) { if (! $this->nonblockingLock()) { return; } $error = null; try { call_user_func($task); } catch (\Exception $e) { $error = $e; } $this->unlock(); if (! is_null($error)) { throw $error; } }
php
public function nonblockingExecuteOnce(\Closure $task) { if (! $this->nonblockingLock()) { return; } $error = null; try { call_user_func($task); } catch (\Exception $e) { $error = $e; } $this->unlock(); if (! is_null($error)) { throw $error; } }
[ "public", "function", "nonblockingExecuteOnce", "(", "\\", "Closure", "$", "task", ")", "{", "if", "(", "!", "$", "this", "->", "nonblockingLock", "(", ")", ")", "{", "return", ";", "}", "$", "error", "=", "null", ";", "try", "{", "call_user_func", "(", "$", "task", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "error", "=", "$", "e", ";", "}", "$", "this", "->", "unlock", "(", ")", ";", "if", "(", "!", "is_null", "(", "$", "error", ")", ")", "{", "throw", "$", "error", ";", "}", "}" ]
Get a lock and execute a task only if the lock was aquired. If more processes call this method only the process which aquired the lock will execute the task. The others will continue execution. @throws Exception
[ "Get", "a", "lock", "and", "execute", "a", "task", "only", "if", "the", "lock", "was", "aquired", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/util/Lock.php#L80-L99
232,889
bav-php/bav
classes/util/Lock.php
Lock.checkedLock
public function checkedLock() { $isLocked = ! flock($this->handle, LOCK_EX | LOCK_NB); if ($isLocked) { $this->lock(); } return $isLocked; }
php
public function checkedLock() { $isLocked = ! flock($this->handle, LOCK_EX | LOCK_NB); if ($isLocked) { $this->lock(); } return $isLocked; }
[ "public", "function", "checkedLock", "(", ")", "{", "$", "isLocked", "=", "!", "flock", "(", "$", "this", "->", "handle", ",", "LOCK_EX", "|", "LOCK_NB", ")", ";", "if", "(", "$", "isLocked", ")", "{", "$", "this", "->", "lock", "(", ")", ";", "}", "return", "$", "isLocked", ";", "}" ]
Blocking lock which returns if the lock did block. @throws LockException @return bool true if the lock was blocked.
[ "Blocking", "lock", "which", "returns", "if", "the", "lock", "did", "block", "." ]
2ad288cfc065d5c1ce31184de05aa0693e94bdb9
https://github.com/bav-php/bav/blob/2ad288cfc065d5c1ce31184de05aa0693e94bdb9/classes/util/Lock.php#L130-L138
232,890
chillerlan/php-bbcode
src/Output/BBCodeModuleAbstract.php
BBCodeModuleAbstract.getAttribute
protected function getAttribute(string $name, $default = false){ return isset($this->attributes[$name]) && !empty($this->attributes[$name]) ? $this->attributes[$name] : $default; }
php
protected function getAttribute(string $name, $default = false){ return isset($this->attributes[$name]) && !empty($this->attributes[$name]) ? $this->attributes[$name] : $default; }
[ "protected", "function", "getAttribute", "(", "string", "$", "name", ",", "$", "default", "=", "false", ")", "{", "return", "isset", "(", "$", "this", "->", "attributes", "[", "$", "name", "]", ")", "&&", "!", "empty", "(", "$", "this", "->", "attributes", "[", "$", "name", "]", ")", "?", "$", "this", "->", "attributes", "[", "$", "name", "]", ":", "$", "default", ";", "}" ]
Retrieves an attribute's value by it's name @param string $name the desired attributes name @param mixed $default [optional] a default value in case the attribute isn't set, defaults to false @return mixed the attribute's value in case it exists, otherwise $default
[ "Retrieves", "an", "attribute", "s", "value", "by", "it", "s", "name" ]
902bdcce41ffc74ae4c419a6890268468d6741b2
https://github.com/chillerlan/php-bbcode/blob/902bdcce41ffc74ae4c419a6890268468d6741b2/src/Output/BBCodeModuleAbstract.php#L195-L197
232,891
chillerlan/php-bbcode
src/Output/BBCodeModuleAbstract.php
BBCodeModuleAbstract.eol
protected function eol(string $str, string $eol = '', int $count = null):string{ return str_replace($this->options->placeholder_eol, $eol, $str, $count); }
php
protected function eol(string $str, string $eol = '', int $count = null):string{ return str_replace($this->options->placeholder_eol, $eol, $str, $count); }
[ "protected", "function", "eol", "(", "string", "$", "str", ",", "string", "$", "eol", "=", "''", ",", "int", "$", "count", "=", "null", ")", ":", "string", "{", "return", "str_replace", "(", "$", "this", "->", "options", "->", "placeholder_eol", ",", "$", "eol", ",", "$", "str", ",", "$", "count", ")", ";", "}" ]
Replaces the EOL placeholder in the given string with a custom token @param string $str haystack @param string $eol [optional] custom EOL token, default: '' @param int $count [optional] replace first $count occurences @return string
[ "Replaces", "the", "EOL", "placeholder", "in", "the", "given", "string", "with", "a", "custom", "token" ]
902bdcce41ffc74ae4c419a6890268468d6741b2
https://github.com/chillerlan/php-bbcode/blob/902bdcce41ffc74ae4c419a6890268468d6741b2/src/Output/BBCodeModuleAbstract.php#L231-L233
232,892
chillerlan/php-bbcode
src/Output/BBCodeModuleAbstract.php
BBCodeModuleAbstract.attributeIn
protected function attributeIn(string $name, array $whitelist, $default = false){ return isset($this->attributes[$name]) && in_array($this->attributes[$name], $whitelist) ? $default !== false ? $this->attributes[$name] : true : $default; }
php
protected function attributeIn(string $name, array $whitelist, $default = false){ return isset($this->attributes[$name]) && in_array($this->attributes[$name], $whitelist) ? $default !== false ? $this->attributes[$name] : true : $default; }
[ "protected", "function", "attributeIn", "(", "string", "$", "name", ",", "array", "$", "whitelist", ",", "$", "default", "=", "false", ")", "{", "return", "isset", "(", "$", "this", "->", "attributes", "[", "$", "name", "]", ")", "&&", "in_array", "(", "$", "this", "->", "attributes", "[", "$", "name", "]", ",", "$", "whitelist", ")", "?", "$", "default", "!==", "false", "?", "$", "this", "->", "attributes", "[", "$", "name", "]", ":", "true", ":", "$", "default", ";", "}" ]
Retrieves an attribute's value by it's name and checks if it's whitelisted @param string $name the desired attributes name @param array $whitelist an array with whitelisted values @param mixed $default [optional] a default value in case the attribute isn't set, defaults to false @return mixed boolean if no $default is set, otherwise the attribute's value in case it exists and is whitelisted or $default
[ "Retrieves", "an", "attribute", "s", "value", "by", "it", "s", "name", "and", "checks", "if", "it", "s", "whitelisted" ]
902bdcce41ffc74ae4c419a6890268468d6741b2
https://github.com/chillerlan/php-bbcode/blob/902bdcce41ffc74ae4c419a6890268468d6741b2/src/Output/BBCodeModuleAbstract.php#L244-L250
232,893
chillerlan/php-bbcode
src/Output/BBCodeModuleAbstract.php
BBCodeModuleAbstract.attributeKeyIn
protected function attributeKeyIn(string $name, array $whitelist, $default = false){ return isset($this->attributes[$name]) && array_key_exists($this->attributes[$name], $whitelist) ? $default !== false ? $whitelist[$this->attributes[$name]] : true : $default; }
php
protected function attributeKeyIn(string $name, array $whitelist, $default = false){ return isset($this->attributes[$name]) && array_key_exists($this->attributes[$name], $whitelist) ? $default !== false ? $whitelist[$this->attributes[$name]] : true : $default; }
[ "protected", "function", "attributeKeyIn", "(", "string", "$", "name", ",", "array", "$", "whitelist", ",", "$", "default", "=", "false", ")", "{", "return", "isset", "(", "$", "this", "->", "attributes", "[", "$", "name", "]", ")", "&&", "array_key_exists", "(", "$", "this", "->", "attributes", "[", "$", "name", "]", ",", "$", "whitelist", ")", "?", "$", "default", "!==", "false", "?", "$", "whitelist", "[", "$", "this", "->", "attributes", "[", "$", "name", "]", "]", ":", "true", ":", "$", "default", ";", "}" ]
Checks if an attribute exists and if it exists as key in a whitelist @param string $name the desired attributes name @param array $whitelist an array with whitelisted key -> value pairs @param mixed $default [optional] a default value in case the attribute isn't set, defaults to false @return mixed boolean if no $default is set, otherwise the whitelist value to the given key in case it exists or $default
[ "Checks", "if", "an", "attribute", "exists", "and", "if", "it", "exists", "as", "key", "in", "a", "whitelist" ]
902bdcce41ffc74ae4c419a6890268468d6741b2
https://github.com/chillerlan/php-bbcode/blob/902bdcce41ffc74ae4c419a6890268468d6741b2/src/Output/BBCodeModuleAbstract.php#L261-L265
232,894
chillerlan/php-bbcode
src/Output/BBCodeModuleAbstract.php
BBCodeModuleAbstract.tagIn
protected function tagIn(array $whitelist, $default = false){ return in_array($this->tag, $whitelist) ? $default !== false ? $this->tag : true : $default; }
php
protected function tagIn(array $whitelist, $default = false){ return in_array($this->tag, $whitelist) ? $default !== false ? $this->tag : true : $default; }
[ "protected", "function", "tagIn", "(", "array", "$", "whitelist", ",", "$", "default", "=", "false", ")", "{", "return", "in_array", "(", "$", "this", "->", "tag", ",", "$", "whitelist", ")", "?", "$", "default", "!==", "false", "?", "$", "this", "->", "tag", ":", "true", ":", "$", "default", ";", "}" ]
Checks if the current tag is whitelisted @param array $whitelist an array with whitelisted tag names @param mixed $default [optional] a default value in case the tag isn't whitelisted @return mixed boolean if no $default is set, otherwise the whitelisted tag or $default
[ "Checks", "if", "the", "current", "tag", "is", "whitelisted" ]
902bdcce41ffc74ae4c419a6890268468d6741b2
https://github.com/chillerlan/php-bbcode/blob/902bdcce41ffc74ae4c419a6890268468d6741b2/src/Output/BBCodeModuleAbstract.php#L275-L279
232,895
asinfotrack/yii2-toolbox
helpers/ServerConfig.php
ServerConfig.checkExtensions
public static function checkExtensions($extConstants, $requireAll=true) { if (is_array($extConstants)) { foreach ($extConstants as $ext) { if (static::extLoaded($ext)) { if (!$requireAll) return true; } else { if ($requireAll) return false; } } return true; } else { return static::extLoaded($extConstants); } }
php
public static function checkExtensions($extConstants, $requireAll=true) { if (is_array($extConstants)) { foreach ($extConstants as $ext) { if (static::extLoaded($ext)) { if (!$requireAll) return true; } else { if ($requireAll) return false; } } return true; } else { return static::extLoaded($extConstants); } }
[ "public", "static", "function", "checkExtensions", "(", "$", "extConstants", ",", "$", "requireAll", "=", "true", ")", "{", "if", "(", "is_array", "(", "$", "extConstants", ")", ")", "{", "foreach", "(", "$", "extConstants", "as", "$", "ext", ")", "{", "if", "(", "static", "::", "extLoaded", "(", "$", "ext", ")", ")", "{", "if", "(", "!", "$", "requireAll", ")", "return", "true", ";", "}", "else", "{", "if", "(", "$", "requireAll", ")", "return", "false", ";", "}", "}", "return", "true", ";", "}", "else", "{", "return", "static", "::", "extLoaded", "(", "$", "extConstants", ")", ";", "}", "}" ]
This function takes several EXT_-constants of this class combined and checks if they are available. If the requirements are met, true is returned. @param string|string[] $extConstants either one or an array of extension constants @param boolean $requireAll if set to true, all passed extensions must be available, otherwise only one of them is enough (defaults to true). This second param is only relevant if the first param is an array @return boolean true if requirements are met
[ "This", "function", "takes", "several", "EXT_", "-", "constants", "of", "this", "class", "combined", "and", "checks", "if", "they", "are", "available", ".", "If", "the", "requirements", "are", "met", "true", "is", "returned", "." ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/helpers/ServerConfig.php#L179-L193
232,896
ncaneldiee/rajaongkir
src/Helper/Curl.php
Curl.request
public static function request($url, $method = 'GET', array $parameter = [], array $option = []) { $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_AUTOREFERER => true, CURLOPT_FOLLOWLOCATION => true, ]); if (isset($option[CURLOPT_CONNECTTIMEOUT])) { curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $option[CURLOPT_CONNECTTIMEOUT]); } if (isset($option[CURLOPT_TIMEOUT])) { curl_setopt($curl, CURLOPT_TIMEOUT, $option[CURLOPT_TIMEOUT]); } $query = empty($parameter) ? '' : http_build_query($parameter, '', '&'); switch ($method) { case 'GET': if ($query) { $url .= '?' . $query; } curl_setopt($curl, CURLOPT_HTTPGET, true); break; case 'POST': if ($query) { curl_setopt($curl, CURLOPT_POSTFIELDS, $query); } if (isset($option[CURLOPT_HTTPHEADER]) && is_array($option[CURLOPT_HTTPHEADER])) { $option[CURLOPT_HTTPHEADER] = array_merge($option[CURLOPT_HTTPHEADER], [ 'content-type: application/x-www-form-urlencoded', ]); } else { $option[CURLOPT_HTTPHEADER] = [ 'content-type: application/x-www-form-urlencoded', ]; } curl_setopt($curl, CURLOPT_POST, true); break; default: curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); break; } if (!empty($option)) { curl_setopt_array($curl, $option); } curl_setopt($curl, CURLOPT_URL, $url); $body = curl_exec($curl); if (false === $body) { $error = curl_error($curl); $code = curl_errno($curl); curl_close($curl); } $header = (object) curl_getinfo($curl); curl_close($curl); if (mb_strpos($header->content_type, 'application/json') !== false) { $body = mb_substr($body, $header->header_size); $body = json_decode($body); } return (object) [ 'header' => $header, 'body' => $body, ]; }
php
public static function request($url, $method = 'GET', array $parameter = [], array $option = []) { $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_AUTOREFERER => true, CURLOPT_FOLLOWLOCATION => true, ]); if (isset($option[CURLOPT_CONNECTTIMEOUT])) { curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $option[CURLOPT_CONNECTTIMEOUT]); } if (isset($option[CURLOPT_TIMEOUT])) { curl_setopt($curl, CURLOPT_TIMEOUT, $option[CURLOPT_TIMEOUT]); } $query = empty($parameter) ? '' : http_build_query($parameter, '', '&'); switch ($method) { case 'GET': if ($query) { $url .= '?' . $query; } curl_setopt($curl, CURLOPT_HTTPGET, true); break; case 'POST': if ($query) { curl_setopt($curl, CURLOPT_POSTFIELDS, $query); } if (isset($option[CURLOPT_HTTPHEADER]) && is_array($option[CURLOPT_HTTPHEADER])) { $option[CURLOPT_HTTPHEADER] = array_merge($option[CURLOPT_HTTPHEADER], [ 'content-type: application/x-www-form-urlencoded', ]); } else { $option[CURLOPT_HTTPHEADER] = [ 'content-type: application/x-www-form-urlencoded', ]; } curl_setopt($curl, CURLOPT_POST, true); break; default: curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); break; } if (!empty($option)) { curl_setopt_array($curl, $option); } curl_setopt($curl, CURLOPT_URL, $url); $body = curl_exec($curl); if (false === $body) { $error = curl_error($curl); $code = curl_errno($curl); curl_close($curl); } $header = (object) curl_getinfo($curl); curl_close($curl); if (mb_strpos($header->content_type, 'application/json') !== false) { $body = mb_substr($body, $header->header_size); $body = json_decode($body); } return (object) [ 'header' => $header, 'body' => $body, ]; }
[ "public", "static", "function", "request", "(", "$", "url", ",", "$", "method", "=", "'GET'", ",", "array", "$", "parameter", "=", "[", "]", ",", "array", "$", "option", "=", "[", "]", ")", "{", "$", "curl", "=", "curl_init", "(", ")", ";", "curl_setopt_array", "(", "$", "curl", ",", "[", "CURLOPT_HEADER", "=>", "true", ",", "CURLOPT_RETURNTRANSFER", "=>", "true", ",", "CURLOPT_AUTOREFERER", "=>", "true", ",", "CURLOPT_FOLLOWLOCATION", "=>", "true", ",", "]", ")", ";", "if", "(", "isset", "(", "$", "option", "[", "CURLOPT_CONNECTTIMEOUT", "]", ")", ")", "{", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_CONNECTTIMEOUT", ",", "$", "option", "[", "CURLOPT_CONNECTTIMEOUT", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "option", "[", "CURLOPT_TIMEOUT", "]", ")", ")", "{", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_TIMEOUT", ",", "$", "option", "[", "CURLOPT_TIMEOUT", "]", ")", ";", "}", "$", "query", "=", "empty", "(", "$", "parameter", ")", "?", "''", ":", "http_build_query", "(", "$", "parameter", ",", "''", ",", "'&'", ")", ";", "switch", "(", "$", "method", ")", "{", "case", "'GET'", ":", "if", "(", "$", "query", ")", "{", "$", "url", ".=", "'?'", ".", "$", "query", ";", "}", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_HTTPGET", ",", "true", ")", ";", "break", ";", "case", "'POST'", ":", "if", "(", "$", "query", ")", "{", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_POSTFIELDS", ",", "$", "query", ")", ";", "}", "if", "(", "isset", "(", "$", "option", "[", "CURLOPT_HTTPHEADER", "]", ")", "&&", "is_array", "(", "$", "option", "[", "CURLOPT_HTTPHEADER", "]", ")", ")", "{", "$", "option", "[", "CURLOPT_HTTPHEADER", "]", "=", "array_merge", "(", "$", "option", "[", "CURLOPT_HTTPHEADER", "]", ",", "[", "'content-type: application/x-www-form-urlencoded'", ",", "]", ")", ";", "}", "else", "{", "$", "option", "[", "CURLOPT_HTTPHEADER", "]", "=", "[", "'content-type: application/x-www-form-urlencoded'", ",", "]", ";", "}", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_POST", ",", "true", ")", ";", "break", ";", "default", ":", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_CUSTOMREQUEST", ",", "$", "method", ")", ";", "break", ";", "}", "if", "(", "!", "empty", "(", "$", "option", ")", ")", "{", "curl_setopt_array", "(", "$", "curl", ",", "$", "option", ")", ";", "}", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "$", "body", "=", "curl_exec", "(", "$", "curl", ")", ";", "if", "(", "false", "===", "$", "body", ")", "{", "$", "error", "=", "curl_error", "(", "$", "curl", ")", ";", "$", "code", "=", "curl_errno", "(", "$", "curl", ")", ";", "curl_close", "(", "$", "curl", ")", ";", "}", "$", "header", "=", "(", "object", ")", "curl_getinfo", "(", "$", "curl", ")", ";", "curl_close", "(", "$", "curl", ")", ";", "if", "(", "mb_strpos", "(", "$", "header", "->", "content_type", ",", "'application/json'", ")", "!==", "false", ")", "{", "$", "body", "=", "mb_substr", "(", "$", "body", ",", "$", "header", "->", "header_size", ")", ";", "$", "body", "=", "json_decode", "(", "$", "body", ")", ";", "}", "return", "(", "object", ")", "[", "'header'", "=>", "$", "header", ",", "'body'", "=>", "$", "body", ",", "]", ";", "}" ]
Create an HTTP request of the specified method to a url. @param string $url @param string $method @param array $parameter @param array $option @return object
[ "Create", "an", "HTTP", "request", "of", "the", "specified", "method", "to", "a", "url", "." ]
98e5c40a1b359953dcc913dd5070b8e8560a86a5
https://github.com/ncaneldiee/rajaongkir/blob/98e5c40a1b359953dcc913dd5070b8e8560a86a5/src/Helper/Curl.php#L41-L123
232,897
asinfotrack/yii2-toolbox
widgets/SimpleNav.php
SimpleNav.renderItem
protected function renderItem($item, $depth=0) { //visibility if (isset($item['visible']) && $item['visible'] === false) return ''; //prepare options $options = isset($item['options']) ? $item['options'] : []; Html::addCssClass($options, 'depth-' . $depth); if (isset($item['active']) && $item['active']) Html::addCssClass($options, 'active'); if (isset($item['items']) && count($item['items']) > 0) Html::addCssClass($options, 'is-parent'); //prepare returned code $ret = Html::beginTag('li', $options); $ret .= $this->createEntry($item, $depth); //render children recursively if (isset($item['items']) && ($this->maxDepth === null || ($this->maxDepth !== null && $depth + 1 <= $this->maxDepth))) { $ret .= Html::beginTag('ul'); foreach ($item['items'] as $subItem) { $ret .= $this->renderItem($subItem, $depth + 1); } $ret .= Html::endTag('ul'); } //finish and return $ret .= Html::endTag('li'); return $ret; }
php
protected function renderItem($item, $depth=0) { //visibility if (isset($item['visible']) && $item['visible'] === false) return ''; //prepare options $options = isset($item['options']) ? $item['options'] : []; Html::addCssClass($options, 'depth-' . $depth); if (isset($item['active']) && $item['active']) Html::addCssClass($options, 'active'); if (isset($item['items']) && count($item['items']) > 0) Html::addCssClass($options, 'is-parent'); //prepare returned code $ret = Html::beginTag('li', $options); $ret .= $this->createEntry($item, $depth); //render children recursively if (isset($item['items']) && ($this->maxDepth === null || ($this->maxDepth !== null && $depth + 1 <= $this->maxDepth))) { $ret .= Html::beginTag('ul'); foreach ($item['items'] as $subItem) { $ret .= $this->renderItem($subItem, $depth + 1); } $ret .= Html::endTag('ul'); } //finish and return $ret .= Html::endTag('li'); return $ret; }
[ "protected", "function", "renderItem", "(", "$", "item", ",", "$", "depth", "=", "0", ")", "{", "//visibility", "if", "(", "isset", "(", "$", "item", "[", "'visible'", "]", ")", "&&", "$", "item", "[", "'visible'", "]", "===", "false", ")", "return", "''", ";", "//prepare options", "$", "options", "=", "isset", "(", "$", "item", "[", "'options'", "]", ")", "?", "$", "item", "[", "'options'", "]", ":", "[", "]", ";", "Html", "::", "addCssClass", "(", "$", "options", ",", "'depth-'", ".", "$", "depth", ")", ";", "if", "(", "isset", "(", "$", "item", "[", "'active'", "]", ")", "&&", "$", "item", "[", "'active'", "]", ")", "Html", "::", "addCssClass", "(", "$", "options", ",", "'active'", ")", ";", "if", "(", "isset", "(", "$", "item", "[", "'items'", "]", ")", "&&", "count", "(", "$", "item", "[", "'items'", "]", ")", ">", "0", ")", "Html", "::", "addCssClass", "(", "$", "options", ",", "'is-parent'", ")", ";", "//prepare returned code", "$", "ret", "=", "Html", "::", "beginTag", "(", "'li'", ",", "$", "options", ")", ";", "$", "ret", ".=", "$", "this", "->", "createEntry", "(", "$", "item", ",", "$", "depth", ")", ";", "//render children recursively", "if", "(", "isset", "(", "$", "item", "[", "'items'", "]", ")", "&&", "(", "$", "this", "->", "maxDepth", "===", "null", "||", "(", "$", "this", "->", "maxDepth", "!==", "null", "&&", "$", "depth", "+", "1", "<=", "$", "this", "->", "maxDepth", ")", ")", ")", "{", "$", "ret", ".=", "Html", "::", "beginTag", "(", "'ul'", ")", ";", "foreach", "(", "$", "item", "[", "'items'", "]", "as", "$", "subItem", ")", "{", "$", "ret", ".=", "$", "this", "->", "renderItem", "(", "$", "subItem", ",", "$", "depth", "+", "1", ")", ";", "}", "$", "ret", ".=", "Html", "::", "endTag", "(", "'ul'", ")", ";", "}", "//finish and return", "$", "ret", ".=", "Html", "::", "endTag", "(", "'li'", ")", ";", "return", "$", "ret", ";", "}" ]
Renders an actual item with its children recursively @param array $item the item config @param integer $depth the current depth @return string the resulting html code
[ "Renders", "an", "actual", "item", "with", "its", "children", "recursively" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/widgets/SimpleNav.php#L105-L132
232,898
asinfotrack/yii2-toolbox
widgets/SimpleNav.php
SimpleNav.createEntry
protected function createEntry($item, $depth) { $label = $item['label']; $prefix = ''; if ($this->entryPrefix !== null) { if (is_callable($this->entryPrefix)) { $prefix = call_user_func($this->entryPrefix, $item, $depth); } else { $prefix = $this->entryPrefix; } } $itemOptions = isset($item['itemOptions']) ? $item['itemOptions'] : []; if (isset($item['url'])) { if ($this->entryPrefixInsideLink) { return Html::a($prefix . $label, $item['url'], $itemOptions); } else { return $prefix . Html::a($label, $item['url'], $itemOptions); } } else { return Html::tag($this->noLinkTagName, $prefix . $label, $itemOptions); } }
php
protected function createEntry($item, $depth) { $label = $item['label']; $prefix = ''; if ($this->entryPrefix !== null) { if (is_callable($this->entryPrefix)) { $prefix = call_user_func($this->entryPrefix, $item, $depth); } else { $prefix = $this->entryPrefix; } } $itemOptions = isset($item['itemOptions']) ? $item['itemOptions'] : []; if (isset($item['url'])) { if ($this->entryPrefixInsideLink) { return Html::a($prefix . $label, $item['url'], $itemOptions); } else { return $prefix . Html::a($label, $item['url'], $itemOptions); } } else { return Html::tag($this->noLinkTagName, $prefix . $label, $itemOptions); } }
[ "protected", "function", "createEntry", "(", "$", "item", ",", "$", "depth", ")", "{", "$", "label", "=", "$", "item", "[", "'label'", "]", ";", "$", "prefix", "=", "''", ";", "if", "(", "$", "this", "->", "entryPrefix", "!==", "null", ")", "{", "if", "(", "is_callable", "(", "$", "this", "->", "entryPrefix", ")", ")", "{", "$", "prefix", "=", "call_user_func", "(", "$", "this", "->", "entryPrefix", ",", "$", "item", ",", "$", "depth", ")", ";", "}", "else", "{", "$", "prefix", "=", "$", "this", "->", "entryPrefix", ";", "}", "}", "$", "itemOptions", "=", "isset", "(", "$", "item", "[", "'itemOptions'", "]", ")", "?", "$", "item", "[", "'itemOptions'", "]", ":", "[", "]", ";", "if", "(", "isset", "(", "$", "item", "[", "'url'", "]", ")", ")", "{", "if", "(", "$", "this", "->", "entryPrefixInsideLink", ")", "{", "return", "Html", "::", "a", "(", "$", "prefix", ".", "$", "label", ",", "$", "item", "[", "'url'", "]", ",", "$", "itemOptions", ")", ";", "}", "else", "{", "return", "$", "prefix", ".", "Html", "::", "a", "(", "$", "label", ",", "$", "item", "[", "'url'", "]", ",", "$", "itemOptions", ")", ";", "}", "}", "else", "{", "return", "Html", "::", "tag", "(", "$", "this", "->", "noLinkTagName", ",", "$", "prefix", ".", "$", "label", ",", "$", "itemOptions", ")", ";", "}", "}" ]
Creates the actual label-content of the item. Depending if an url is present it will be a link or otherwise the in the options defined tag @param array $item the item config @param int $depth the depth of the item to create @return string the resulting html code
[ "Creates", "the", "actual", "label", "-", "content", "of", "the", "item", ".", "Depending", "if", "an", "url", "is", "present", "it", "will", "be", "a", "link", "or", "otherwise", "the", "in", "the", "options", "defined", "tag" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/widgets/SimpleNav.php#L142-L164
232,899
asinfotrack/yii2-toolbox
widgets/SimpleNav.php
SimpleNav.activateItems
protected function activateItems(&$item) { $hasActiveChild = false; if (isset($item['items'])) { foreach ($item['items'] as &$childItem) { if ($this->activateItems($childItem)) $hasActiveChild = true; } } $isActive = isset($item['active']) ? $item['active'] : $this->isItemActive($item); if (!$isActive && $hasActiveChild) $isActive = true; $item['active'] = $isActive; return $isActive; }
php
protected function activateItems(&$item) { $hasActiveChild = false; if (isset($item['items'])) { foreach ($item['items'] as &$childItem) { if ($this->activateItems($childItem)) $hasActiveChild = true; } } $isActive = isset($item['active']) ? $item['active'] : $this->isItemActive($item); if (!$isActive && $hasActiveChild) $isActive = true; $item['active'] = $isActive; return $isActive; }
[ "protected", "function", "activateItems", "(", "&", "$", "item", ")", "{", "$", "hasActiveChild", "=", "false", ";", "if", "(", "isset", "(", "$", "item", "[", "'items'", "]", ")", ")", "{", "foreach", "(", "$", "item", "[", "'items'", "]", "as", "&", "$", "childItem", ")", "{", "if", "(", "$", "this", "->", "activateItems", "(", "$", "childItem", ")", ")", "$", "hasActiveChild", "=", "true", ";", "}", "}", "$", "isActive", "=", "isset", "(", "$", "item", "[", "'active'", "]", ")", "?", "$", "item", "[", "'active'", "]", ":", "$", "this", "->", "isItemActive", "(", "$", "item", ")", ";", "if", "(", "!", "$", "isActive", "&&", "$", "hasActiveChild", ")", "$", "isActive", "=", "true", ";", "$", "item", "[", "'active'", "]", "=", "$", "isActive", ";", "return", "$", "isActive", ";", "}" ]
Traverses over an item and its children recursively to determine if it is active or not @param array $item the item config @return bool true if active
[ "Traverses", "over", "an", "item", "and", "its", "children", "recursively", "to", "determine", "if", "it", "is", "active", "or", "not" ]
236f41e4b6e30117b3d7f9b1a5598633c5aed376
https://github.com/asinfotrack/yii2-toolbox/blob/236f41e4b6e30117b3d7f9b1a5598633c5aed376/widgets/SimpleNav.php#L173-L187