repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.canDelete
public function canDelete($member = null) { $member = $this->getMember($member); if (!$member) { return false; } $extended = $this->extendedCan('canDelete', $member); if ($extended !== null) { return $extended; } return $this->canEdit($member); }
php
public function canDelete($member = null) { $member = $this->getMember($member); if (!$member) { return false; } $extended = $this->extendedCan('canDelete', $member); if ($extended !== null) { return $extended; } return $this->canEdit($member); }
[ "public", "function", "canDelete", "(", "$", "member", "=", "null", ")", "{", "$", "member", "=", "$", "this", "->", "getMember", "(", "$", "member", ")", ";", "if", "(", "!", "$", "member", ")", "{", "return", "false", ";", "}", "$", "extended", "=", "$", "this", "->", "extendedCan", "(", "'canDelete'", ",", "$", "member", ")", ";", "if", "(", "$", "extended", "!==", "null", ")", "{", "return", "$", "extended", ";", "}", "return", "$", "this", "->", "canEdit", "(", "$", "member", ")", ";", "}" ]
Checks if the comment can be deleted. @param null|int|Member $member @return Boolean
[ "Checks", "if", "the", "comment", "can", "be", "deleted", "." ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L404-L418
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.getMember
protected function getMember($member = null) { if (!$member) { $member = Member::currentUser(); } if (is_numeric($member)) { $member = DataObject::get_by_id(Member::class, $member, true); } return $member; }
php
protected function getMember($member = null) { if (!$member) { $member = Member::currentUser(); } if (is_numeric($member)) { $member = DataObject::get_by_id(Member::class, $member, true); } return $member; }
[ "protected", "function", "getMember", "(", "$", "member", "=", "null", ")", "{", "if", "(", "!", "$", "member", ")", "{", "$", "member", "=", "Member", "::", "currentUser", "(", ")", ";", "}", "if", "(", "is_numeric", "(", "$", "member", ")", ")", "{", "$", "member", "=", "DataObject", "::", "get_by_id", "(", "Member", "::", "class", ",", "$", "member", ",", "true", ")", ";", "}", "return", "$", "member", ";", "}" ]
Resolves Member object. @param Member|int|null $member @return Member|null
[ "Resolves", "Member", "object", "." ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L426-L437
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.getAuthorName
public function getAuthorName() { if ($this->Name) { return $this->Name; } elseif ($author = $this->Author()) { return $author->getName(); } }
php
public function getAuthorName() { if ($this->Name) { return $this->Name; } elseif ($author = $this->Author()) { return $author->getName(); } }
[ "public", "function", "getAuthorName", "(", ")", "{", "if", "(", "$", "this", "->", "Name", ")", "{", "return", "$", "this", "->", "Name", ";", "}", "elseif", "(", "$", "author", "=", "$", "this", "->", "Author", "(", ")", ")", "{", "return", "$", "author", "->", "getName", "(", ")", ";", "}", "}" ]
Return the authors name for the comment @return string
[ "Return", "the", "authors", "name", "for", "the", "comment" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L444-L451
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.getAuthorEmail
public function getAuthorEmail() { if ($this->Email) { return $this->Email; } elseif ($author = $this->Author()) { return $author->Email; } }
php
public function getAuthorEmail() { if ($this->Email) { return $this->Email; } elseif ($author = $this->Author()) { return $author->Email; } }
[ "public", "function", "getAuthorEmail", "(", ")", "{", "if", "(", "$", "this", "->", "Email", ")", "{", "return", "$", "this", "->", "Email", ";", "}", "elseif", "(", "$", "author", "=", "$", "this", "->", "Author", "(", ")", ")", "{", "return", "$", "author", "->", "Email", ";", "}", "}" ]
Return the comment authors email address @return string
[ "Return", "the", "comment", "authors", "email", "address" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L458-L465
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.actionLink
protected function actionLink($action, $member = null) { if (!$member) { $member = Member::currentUser(); } if (!$member) { return false; } /** * @todo: How do we handle "DataObject" instances that don't have a Link to reject/spam/delete?? This may * we have to make CMS a hard dependency instead. */ // if (!$this->Parent()->hasMethod('Link')) { // return false; // } $url = Controller::join_links( Director::baseURL(), 'comments', $action, $this->ID ); // Limit access for this user $token = $this->getSecurityToken(); return $token->addToUrl($url, $member); }
php
protected function actionLink($action, $member = null) { if (!$member) { $member = Member::currentUser(); } if (!$member) { return false; } /** * @todo: How do we handle "DataObject" instances that don't have a Link to reject/spam/delete?? This may * we have to make CMS a hard dependency instead. */ // if (!$this->Parent()->hasMethod('Link')) { // return false; // } $url = Controller::join_links( Director::baseURL(), 'comments', $action, $this->ID ); // Limit access for this user $token = $this->getSecurityToken(); return $token->addToUrl($url, $member); }
[ "protected", "function", "actionLink", "(", "$", "action", ",", "$", "member", "=", "null", ")", "{", "if", "(", "!", "$", "member", ")", "{", "$", "member", "=", "Member", "::", "currentUser", "(", ")", ";", "}", "if", "(", "!", "$", "member", ")", "{", "return", "false", ";", "}", "/**\n * @todo: How do we handle \"DataObject\" instances that don't have a Link to reject/spam/delete?? This may\n * we have to make CMS a hard dependency instead.\n */", "// if (!$this->Parent()->hasMethod('Link')) {", "// return false;", "// }", "$", "url", "=", "Controller", "::", "join_links", "(", "Director", "::", "baseURL", "(", ")", ",", "'comments'", ",", "$", "action", ",", "$", "this", "->", "ID", ")", ";", "// Limit access for this user", "$", "token", "=", "$", "this", "->", "getSecurityToken", "(", ")", ";", "return", "$", "token", "->", "addToUrl", "(", "$", "url", ",", "$", "member", ")", ";", "}" ]
Generate a secure admin-action link authorised for the specified member @param string $action An action on CommentingController to link to @param Member $member The member authorised to invoke this action @return string
[ "Generate", "a", "secure", "admin", "-", "action", "link", "authorised", "for", "the", "specified", "member" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L475-L502
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.SpamLink
public function SpamLink($member = null) { if ($this->canEdit($member) && !$this->IsSpam) { return $this->actionLink('spam', $member); } }
php
public function SpamLink($member = null) { if ($this->canEdit($member) && !$this->IsSpam) { return $this->actionLink('spam', $member); } }
[ "public", "function", "SpamLink", "(", "$", "member", "=", "null", ")", "{", "if", "(", "$", "this", "->", "canEdit", "(", "$", "member", ")", "&&", "!", "$", "this", "->", "IsSpam", ")", "{", "return", "$", "this", "->", "actionLink", "(", "'spam'", ",", "$", "member", ")", ";", "}", "}" ]
Link to mark as spam @param Member $member @return string
[ "Link", "to", "mark", "as", "spam" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L525-L530
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.ApproveLink
public function ApproveLink($member = null) { if ($this->canEdit($member) && !$this->Moderated) { return $this->actionLink('approve', $member); } }
php
public function ApproveLink($member = null) { if ($this->canEdit($member) && !$this->Moderated) { return $this->actionLink('approve', $member); } }
[ "public", "function", "ApproveLink", "(", "$", "member", "=", "null", ")", "{", "if", "(", "$", "this", "->", "canEdit", "(", "$", "member", ")", "&&", "!", "$", "this", "->", "Moderated", ")", "{", "return", "$", "this", "->", "actionLink", "(", "'approve'", ",", "$", "member", ")", ";", "}", "}" ]
Link to approve this comment @param Member $member @return string
[ "Link", "to", "approve", "this", "comment" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L553-L558
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.markSpam
public function markSpam() { $this->IsSpam = true; $this->Moderated = true; $this->write(); $this->extend('afterMarkSpam'); }
php
public function markSpam() { $this->IsSpam = true; $this->Moderated = true; $this->write(); $this->extend('afterMarkSpam'); }
[ "public", "function", "markSpam", "(", ")", "{", "$", "this", "->", "IsSpam", "=", "true", ";", "$", "this", "->", "Moderated", "=", "true", ";", "$", "this", "->", "write", "(", ")", ";", "$", "this", "->", "extend", "(", "'afterMarkSpam'", ")", ";", "}" ]
Mark this comment as spam
[ "Mark", "this", "comment", "as", "spam" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L563-L569
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.markApproved
public function markApproved() { $this->IsSpam = false; $this->Moderated = true; $this->write(); $this->extend('afterMarkApproved'); }
php
public function markApproved() { $this->IsSpam = false; $this->Moderated = true; $this->write(); $this->extend('afterMarkApproved'); }
[ "public", "function", "markApproved", "(", ")", "{", "$", "this", "->", "IsSpam", "=", "false", ";", "$", "this", "->", "Moderated", "=", "true", ";", "$", "this", "->", "write", "(", ")", ";", "$", "this", "->", "extend", "(", "'afterMarkApproved'", ")", ";", "}" ]
Mark this comment as approved
[ "Mark", "this", "comment", "as", "approved" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L574-L580
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.Gravatar
public function Gravatar() { $gravatar = ''; $use_gravatar = $this->getOption('use_gravatar'); if ($use_gravatar) { $gravatar = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($this->Email))); $gravatarsize = $this->getOption('gravatar_size'); $gravatardefault = $this->getOption('gravatar_default'); $gravatarrating = $this->getOption('gravatar_rating'); $gravatar .= '?' . http_build_query(array( 's' => $gravatarsize, 'd' => $gravatardefault, 'r' => $gravatarrating, )); } return $gravatar; }
php
public function Gravatar() { $gravatar = ''; $use_gravatar = $this->getOption('use_gravatar'); if ($use_gravatar) { $gravatar = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($this->Email))); $gravatarsize = $this->getOption('gravatar_size'); $gravatardefault = $this->getOption('gravatar_default'); $gravatarrating = $this->getOption('gravatar_rating'); $gravatar .= '?' . http_build_query(array( 's' => $gravatarsize, 'd' => $gravatardefault, 'r' => $gravatarrating, )); } return $gravatar; }
[ "public", "function", "Gravatar", "(", ")", "{", "$", "gravatar", "=", "''", ";", "$", "use_gravatar", "=", "$", "this", "->", "getOption", "(", "'use_gravatar'", ")", ";", "if", "(", "$", "use_gravatar", ")", "{", "$", "gravatar", "=", "'https://www.gravatar.com/avatar/'", ".", "md5", "(", "strtolower", "(", "trim", "(", "$", "this", "->", "Email", ")", ")", ")", ";", "$", "gravatarsize", "=", "$", "this", "->", "getOption", "(", "'gravatar_size'", ")", ";", "$", "gravatardefault", "=", "$", "this", "->", "getOption", "(", "'gravatar_default'", ")", ";", "$", "gravatarrating", "=", "$", "this", "->", "getOption", "(", "'gravatar_rating'", ")", ";", "$", "gravatar", ".=", "'?'", ".", "http_build_query", "(", "array", "(", "'s'", "=>", "$", "gravatarsize", ",", "'d'", "=>", "$", "gravatardefault", ",", "'r'", "=>", "$", "gravatarrating", ",", ")", ")", ";", "}", "return", "$", "gravatar", ";", "}" ]
Calculate the Gravatar link from the email address @return string
[ "Calculate", "the", "Gravatar", "link", "from", "the", "email", "address" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L744-L762
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.getRepliesEnabled
public function getRepliesEnabled() { // Check reply option if (!$this->getOption('nested_comments')) { return false; } // Check if depth is limited $maxLevel = $this->getOption('nested_depth'); $notSpam = ($this->SpamClass() == 'notspam'); return $notSpam && (!$maxLevel || $this->Depth < $maxLevel); }
php
public function getRepliesEnabled() { // Check reply option if (!$this->getOption('nested_comments')) { return false; } // Check if depth is limited $maxLevel = $this->getOption('nested_depth'); $notSpam = ($this->SpamClass() == 'notspam'); return $notSpam && (!$maxLevel || $this->Depth < $maxLevel); }
[ "public", "function", "getRepliesEnabled", "(", ")", "{", "// Check reply option", "if", "(", "!", "$", "this", "->", "getOption", "(", "'nested_comments'", ")", ")", "{", "return", "false", ";", "}", "// Check if depth is limited", "$", "maxLevel", "=", "$", "this", "->", "getOption", "(", "'nested_depth'", ")", ";", "$", "notSpam", "=", "(", "$", "this", "->", "SpamClass", "(", ")", "==", "'notspam'", ")", ";", "return", "$", "notSpam", "&&", "(", "!", "$", "maxLevel", "||", "$", "this", "->", "Depth", "<", "$", "maxLevel", ")", ";", "}" ]
Determine if replies are enabled for this instance @return boolean
[ "Determine", "if", "replies", "are", "enabled", "for", "this", "instance" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L769-L780
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.canPostComment
public function canPostComment($member = null) { return $this->Parent() && $this->Parent()->exists() && $this->Parent()->canPostComment($member); }
php
public function canPostComment($member = null) { return $this->Parent() && $this->Parent()->exists() && $this->Parent()->canPostComment($member); }
[ "public", "function", "canPostComment", "(", "$", "member", "=", "null", ")", "{", "return", "$", "this", "->", "Parent", "(", ")", "&&", "$", "this", "->", "Parent", "(", ")", "->", "exists", "(", ")", "&&", "$", "this", "->", "Parent", "(", ")", "->", "canPostComment", "(", "$", "member", ")", ";", "}" ]
Proxy for checking whether the has permission to comment on the comment parent. @param Member $member Member to check @return boolean
[ "Proxy", "for", "checking", "whether", "the", "has", "permission", "to", "comment", "on", "the", "comment", "parent", "." ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L789-L794
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.AllReplies
public function AllReplies() { // No replies if disabled if (!$this->getRepliesEnabled()) { return new ArrayList(); } // Get all non-spam comments $order = $this->getOption('order_replies_by') ?: $this->getOption('order_comments_by'); $list = $this ->ChildComments() ->sort($order); $this->extend('updateAllReplies', $list); return $list; }
php
public function AllReplies() { // No replies if disabled if (!$this->getRepliesEnabled()) { return new ArrayList(); } // Get all non-spam comments $order = $this->getOption('order_replies_by') ?: $this->getOption('order_comments_by'); $list = $this ->ChildComments() ->sort($order); $this->extend('updateAllReplies', $list); return $list; }
[ "public", "function", "AllReplies", "(", ")", "{", "// No replies if disabled", "if", "(", "!", "$", "this", "->", "getRepliesEnabled", "(", ")", ")", "{", "return", "new", "ArrayList", "(", ")", ";", "}", "// Get all non-spam comments", "$", "order", "=", "$", "this", "->", "getOption", "(", "'order_replies_by'", ")", "?", ":", "$", "this", "->", "getOption", "(", "'order_comments_by'", ")", ";", "$", "list", "=", "$", "this", "->", "ChildComments", "(", ")", "->", "sort", "(", "$", "order", ")", ";", "$", "this", "->", "extend", "(", "'updateAllReplies'", ",", "$", "list", ")", ";", "return", "$", "list", ";", "}" ]
Returns the list of all replies @return SS_List
[ "Returns", "the", "list", "of", "all", "replies" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L801-L817
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.Replies
public function Replies() { // No replies if disabled if (!$this->getRepliesEnabled()) { return new ArrayList(); } $list = $this->AllReplies(); // Filter spam comments for non-administrators if configured $parent = $this->Parent(); $showSpam = $this->getOption('frontend_spam') && $parent && $parent->canModerateComments(); if (!$showSpam) { $list = $list->filter('IsSpam', 0); } // Filter un-moderated comments for non-administrators if moderation is enabled $showUnmoderated = $parent && ( ($parent->ModerationRequired === 'None') || ($this->getOption('frontend_moderation') && $parent->canModerateComments()) ); if (!$showUnmoderated) { $list = $list->filter('Moderated', 1); } $this->extend('updateReplies', $list); return $list; }
php
public function Replies() { // No replies if disabled if (!$this->getRepliesEnabled()) { return new ArrayList(); } $list = $this->AllReplies(); // Filter spam comments for non-administrators if configured $parent = $this->Parent(); $showSpam = $this->getOption('frontend_spam') && $parent && $parent->canModerateComments(); if (!$showSpam) { $list = $list->filter('IsSpam', 0); } // Filter un-moderated comments for non-administrators if moderation is enabled $showUnmoderated = $parent && ( ($parent->ModerationRequired === 'None') || ($this->getOption('frontend_moderation') && $parent->canModerateComments()) ); if (!$showUnmoderated) { $list = $list->filter('Moderated', 1); } $this->extend('updateReplies', $list); return $list; }
[ "public", "function", "Replies", "(", ")", "{", "// No replies if disabled", "if", "(", "!", "$", "this", "->", "getRepliesEnabled", "(", ")", ")", "{", "return", "new", "ArrayList", "(", ")", ";", "}", "$", "list", "=", "$", "this", "->", "AllReplies", "(", ")", ";", "// Filter spam comments for non-administrators if configured", "$", "parent", "=", "$", "this", "->", "Parent", "(", ")", ";", "$", "showSpam", "=", "$", "this", "->", "getOption", "(", "'frontend_spam'", ")", "&&", "$", "parent", "&&", "$", "parent", "->", "canModerateComments", "(", ")", ";", "if", "(", "!", "$", "showSpam", ")", "{", "$", "list", "=", "$", "list", "->", "filter", "(", "'IsSpam'", ",", "0", ")", ";", "}", "// Filter un-moderated comments for non-administrators if moderation is enabled", "$", "showUnmoderated", "=", "$", "parent", "&&", "(", "(", "$", "parent", "->", "ModerationRequired", "===", "'None'", ")", "||", "(", "$", "this", "->", "getOption", "(", "'frontend_moderation'", ")", "&&", "$", "parent", "->", "canModerateComments", "(", ")", ")", ")", ";", "if", "(", "!", "$", "showUnmoderated", ")", "{", "$", "list", "=", "$", "list", "->", "filter", "(", "'Moderated'", ",", "1", ")", ";", "}", "$", "this", "->", "extend", "(", "'updateReplies'", ",", "$", "list", ")", ";", "return", "$", "list", ";", "}" ]
Returns the list of replies, with spam and unmoderated items excluded, for use in the frontend @return SS_List
[ "Returns", "the", "list", "of", "replies", "with", "spam", "and", "unmoderated", "items", "excluded", "for", "use", "in", "the", "frontend" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L824-L850
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.PagedReplies
public function PagedReplies() { $list = $this->Replies(); // Add pagination $list = new PaginatedList($list, Controller::curr()->getRequest()); $list->setPaginationGetVar('repliesstart' . $this->ID); $list->setPageLength($this->getOption('comments_per_page')); $this->extend('updatePagedReplies', $list); return $list; }
php
public function PagedReplies() { $list = $this->Replies(); // Add pagination $list = new PaginatedList($list, Controller::curr()->getRequest()); $list->setPaginationGetVar('repliesstart' . $this->ID); $list->setPageLength($this->getOption('comments_per_page')); $this->extend('updatePagedReplies', $list); return $list; }
[ "public", "function", "PagedReplies", "(", ")", "{", "$", "list", "=", "$", "this", "->", "Replies", "(", ")", ";", "// Add pagination", "$", "list", "=", "new", "PaginatedList", "(", "$", "list", ",", "Controller", "::", "curr", "(", ")", "->", "getRequest", "(", ")", ")", ";", "$", "list", "->", "setPaginationGetVar", "(", "'repliesstart'", ".", "$", "this", "->", "ID", ")", ";", "$", "list", "->", "setPageLength", "(", "$", "this", "->", "getOption", "(", "'comments_per_page'", ")", ")", ";", "$", "this", "->", "extend", "(", "'updatePagedReplies'", ",", "$", "list", ")", ";", "return", "$", "list", ";", "}" ]
Returns the list of replies paged, with spam and unmoderated items excluded, for use in the frontend @return PaginatedList
[ "Returns", "the", "list", "of", "replies", "paged", "with", "spam", "and", "unmoderated", "items", "excluded", "for", "use", "in", "the", "frontend" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L857-L868
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.ReplyForm
public function ReplyForm() { // Ensure replies are enabled if (!$this->getRepliesEnabled()) { return null; } // Check parent is available $parent = $this->Parent(); if (!$parent || !$parent->exists()) { return null; } // Build reply controller $controller = CommentingController::create(); $controller->setOwnerRecord($parent); $controller->setParentClass($parent->ClassName); $controller->setOwnerController(Controller::curr()); return $controller->ReplyForm($this); }
php
public function ReplyForm() { // Ensure replies are enabled if (!$this->getRepliesEnabled()) { return null; } // Check parent is available $parent = $this->Parent(); if (!$parent || !$parent->exists()) { return null; } // Build reply controller $controller = CommentingController::create(); $controller->setOwnerRecord($parent); $controller->setParentClass($parent->ClassName); $controller->setOwnerController(Controller::curr()); return $controller->ReplyForm($this); }
[ "public", "function", "ReplyForm", "(", ")", "{", "// Ensure replies are enabled", "if", "(", "!", "$", "this", "->", "getRepliesEnabled", "(", ")", ")", "{", "return", "null", ";", "}", "// Check parent is available", "$", "parent", "=", "$", "this", "->", "Parent", "(", ")", ";", "if", "(", "!", "$", "parent", "||", "!", "$", "parent", "->", "exists", "(", ")", ")", "{", "return", "null", ";", "}", "// Build reply controller", "$", "controller", "=", "CommentingController", "::", "create", "(", ")", ";", "$", "controller", "->", "setOwnerRecord", "(", "$", "parent", ")", ";", "$", "controller", "->", "setParentClass", "(", "$", "parent", "->", "ClassName", ")", ";", "$", "controller", "->", "setOwnerController", "(", "Controller", "::", "curr", "(", ")", ")", ";", "return", "$", "controller", "->", "ReplyForm", "(", "$", "this", ")", ";", "}" ]
Generate a reply form for this comment @return Form
[ "Generate", "a", "reply", "form", "for", "this", "comment" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L875-L895
train
silverstripe/silverstripe-comments
src/Model/Comment.php
Comment.updateDepth
public function updateDepth() { $parent = $this->ParentComment(); if ($parent && $parent->exists()) { $parent->updateDepth(); $this->Depth = $parent->Depth + 1; } else { $this->Depth = 1; } }
php
public function updateDepth() { $parent = $this->ParentComment(); if ($parent && $parent->exists()) { $parent->updateDepth(); $this->Depth = $parent->Depth + 1; } else { $this->Depth = 1; } }
[ "public", "function", "updateDepth", "(", ")", "{", "$", "parent", "=", "$", "this", "->", "ParentComment", "(", ")", ";", "if", "(", "$", "parent", "&&", "$", "parent", "->", "exists", "(", ")", ")", "{", "$", "parent", "->", "updateDepth", "(", ")", ";", "$", "this", "->", "Depth", "=", "$", "parent", "->", "Depth", "+", "1", ";", "}", "else", "{", "$", "this", "->", "Depth", "=", "1", ";", "}", "}" ]
Refresh of this comment in the hierarchy
[ "Refresh", "of", "this", "comment", "in", "the", "hierarchy" ]
d8602d0e0246af209cf0de24c376cabafdb5d6db
https://github.com/silverstripe/silverstripe-comments/blob/d8602d0e0246af209cf0de24c376cabafdb5d6db/src/Model/Comment.php#L908-L917
train
ZooRoyal/coding-standard
src/main/php/CommandLine/FileFinders/DiffCheckableFileFinder.php
DiffCheckableFileFinder.findFiles
public function findFiles( string $filter = '', string $blacklistToken = '', string $whitelistToken = '', $targetBranch = '' ) : GitChangeSet { if (empty($targetBranch)) { throw new InvalidArgumentException( 'Finding a diff makes no sense without a target branch.', 1553857649 ); } $rawDiff = $this->findFilesInDiffToTarget($targetBranch); $this->fileFilter->filter($rawDiff, $filter, $blacklistToken, $whitelistToken); return $rawDiff; }
php
public function findFiles( string $filter = '', string $blacklistToken = '', string $whitelistToken = '', $targetBranch = '' ) : GitChangeSet { if (empty($targetBranch)) { throw new InvalidArgumentException( 'Finding a diff makes no sense without a target branch.', 1553857649 ); } $rawDiff = $this->findFilesInDiffToTarget($targetBranch); $this->fileFilter->filter($rawDiff, $filter, $blacklistToken, $whitelistToken); return $rawDiff; }
[ "public", "function", "findFiles", "(", "string", "$", "filter", "=", "''", ",", "string", "$", "blacklistToken", "=", "''", ",", "string", "$", "whitelistToken", "=", "''", ",", "$", "targetBranch", "=", "''", ")", ":", "GitChangeSet", "{", "if", "(", "empty", "(", "$", "targetBranch", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Finding a diff makes no sense without a target branch.'", ",", "1553857649", ")", ";", "}", "$", "rawDiff", "=", "$", "this", "->", "findFilesInDiffToTarget", "(", "$", "targetBranch", ")", ";", "$", "this", "->", "fileFilter", "->", "filter", "(", "$", "rawDiff", ",", "$", "filter", ",", "$", "blacklistToken", ",", "$", "whitelistToken", ")", ";", "return", "$", "rawDiff", ";", "}" ]
This function searches for files to check in a certain diff only. @param string $filter @param string $blacklistToken @param string $whitelistToken @param string|false $targetBranch @return GitChangeSet @throws InvalidArgumentException
[ "This", "function", "searches", "for", "files", "to", "check", "in", "a", "certain", "diff", "only", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/FileFinders/DiffCheckableFileFinder.php#L49-L66
train
ZooRoyal/coding-standard
src/main/php/CommandLine/FileFinders/DiffCheckableFileFinder.php
DiffCheckableFileFinder.findFilesInDiffToTarget
private function findFilesInDiffToTarget(string $targetBranch) : GitChangeSet { $mergeBase = $this->processRunner->runAsProcess('git', 'merge-base', 'HEAD', $targetBranch); $rawDiffUnfilteredString = $this->processRunner->runAsProcess( 'git', 'diff', '--name-only', '--diff-filter=d', $mergeBase ); $rawDiffUnfiltered = explode("\n", trim($rawDiffUnfilteredString)); $result = $this->gitChangeSetFactory->build($rawDiffUnfiltered, $mergeBase); return $result; }
php
private function findFilesInDiffToTarget(string $targetBranch) : GitChangeSet { $mergeBase = $this->processRunner->runAsProcess('git', 'merge-base', 'HEAD', $targetBranch); $rawDiffUnfilteredString = $this->processRunner->runAsProcess( 'git', 'diff', '--name-only', '--diff-filter=d', $mergeBase ); $rawDiffUnfiltered = explode("\n", trim($rawDiffUnfilteredString)); $result = $this->gitChangeSetFactory->build($rawDiffUnfiltered, $mergeBase); return $result; }
[ "private", "function", "findFilesInDiffToTarget", "(", "string", "$", "targetBranch", ")", ":", "GitChangeSet", "{", "$", "mergeBase", "=", "$", "this", "->", "processRunner", "->", "runAsProcess", "(", "'git'", ",", "'merge-base'", ",", "'HEAD'", ",", "$", "targetBranch", ")", ";", "$", "rawDiffUnfilteredString", "=", "$", "this", "->", "processRunner", "->", "runAsProcess", "(", "'git'", ",", "'diff'", ",", "'--name-only'", ",", "'--diff-filter=d'", ",", "$", "mergeBase", ")", ";", "$", "rawDiffUnfiltered", "=", "explode", "(", "\"\\n\"", ",", "trim", "(", "$", "rawDiffUnfilteredString", ")", ")", ";", "$", "result", "=", "$", "this", "->", "gitChangeSetFactory", "->", "build", "(", "$", "rawDiffUnfiltered", ",", "$", "mergeBase", ")", ";", "return", "$", "result", ";", "}" ]
This method finds all files in diff to target branch. @param string $targetBranch @return GitChangeSet
[ "This", "method", "finds", "all", "files", "in", "diff", "to", "target", "branch", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/FileFinders/DiffCheckableFileFinder.php#L75-L92
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/GenericCommandRunner.php
GenericCommandRunner.runWhitelistCommand
public function runWhitelistCommand( string $template, $targetBranch, string $blacklistToken, string $filter, bool $processIsolation = false, string $glue = ',' ) : int { $exitCode = 0; $whitelistArguments = $this->buildWhitelistArguments( $targetBranch, $blacklistToken, $filter, $processIsolation, $glue ); foreach ($whitelistArguments as $argument) { $commandWithParameters = $this->buildCommand($template, $argument); $exitCode = $this->runAndWriteToOutput($commandWithParameters); } return $exitCode; }
php
public function runWhitelistCommand( string $template, $targetBranch, string $blacklistToken, string $filter, bool $processIsolation = false, string $glue = ',' ) : int { $exitCode = 0; $whitelistArguments = $this->buildWhitelistArguments( $targetBranch, $blacklistToken, $filter, $processIsolation, $glue ); foreach ($whitelistArguments as $argument) { $commandWithParameters = $this->buildCommand($template, $argument); $exitCode = $this->runAndWriteToOutput($commandWithParameters); } return $exitCode; }
[ "public", "function", "runWhitelistCommand", "(", "string", "$", "template", ",", "$", "targetBranch", ",", "string", "$", "blacklistToken", ",", "string", "$", "filter", ",", "bool", "$", "processIsolation", "=", "false", ",", "string", "$", "glue", "=", "','", ")", ":", "int", "{", "$", "exitCode", "=", "0", ";", "$", "whitelistArguments", "=", "$", "this", "->", "buildWhitelistArguments", "(", "$", "targetBranch", ",", "$", "blacklistToken", ",", "$", "filter", ",", "$", "processIsolation", ",", "$", "glue", ")", ";", "foreach", "(", "$", "whitelistArguments", "as", "$", "argument", ")", "{", "$", "commandWithParameters", "=", "$", "this", "->", "buildCommand", "(", "$", "template", ",", "$", "argument", ")", ";", "$", "exitCode", "=", "$", "this", "->", "runAndWriteToOutput", "(", "$", "commandWithParameters", ")", ";", "}", "return", "$", "exitCode", ";", "}" ]
Builds a CLI-Command by inserting a whitelist of file paths in the command template and executes it. @param string $template @param string|null $targetBranch @param string $blacklistToken @param string $filter @param bool $processIsolation @param string $glue @return int
[ "Builds", "a", "CLI", "-", "Command", "by", "inserting", "a", "whitelist", "of", "file", "paths", "in", "the", "command", "template", "and", "executes", "it", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/GenericCommandRunner.php#L55-L79
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/GenericCommandRunner.php
GenericCommandRunner.runBlacklistCommand
public function runBlacklistCommand( string $template, string $blacklistToken, string $prefix = '', string $glue = ',', bool $escape = false ) { $blackList = $this->blacklistFactory->build($blacklistToken); if ($escape) { $blackList = array_map( function ($value) { return preg_quote(preg_quote($value, '/'), '/'); }, $blackList ); } $argument = $prefix . implode($glue . $prefix, $blackList); $command = $this->buildCommand($template, $argument); return $this->runAndWriteToOutput($command); }
php
public function runBlacklistCommand( string $template, string $blacklistToken, string $prefix = '', string $glue = ',', bool $escape = false ) { $blackList = $this->blacklistFactory->build($blacklistToken); if ($escape) { $blackList = array_map( function ($value) { return preg_quote(preg_quote($value, '/'), '/'); }, $blackList ); } $argument = $prefix . implode($glue . $prefix, $blackList); $command = $this->buildCommand($template, $argument); return $this->runAndWriteToOutput($command); }
[ "public", "function", "runBlacklistCommand", "(", "string", "$", "template", ",", "string", "$", "blacklistToken", ",", "string", "$", "prefix", "=", "''", ",", "string", "$", "glue", "=", "','", ",", "bool", "$", "escape", "=", "false", ")", "{", "$", "blackList", "=", "$", "this", "->", "blacklistFactory", "->", "build", "(", "$", "blacklistToken", ")", ";", "if", "(", "$", "escape", ")", "{", "$", "blackList", "=", "array_map", "(", "function", "(", "$", "value", ")", "{", "return", "preg_quote", "(", "preg_quote", "(", "$", "value", ",", "'/'", ")", ",", "'/'", ")", ";", "}", ",", "$", "blackList", ")", ";", "}", "$", "argument", "=", "$", "prefix", ".", "implode", "(", "$", "glue", ".", "$", "prefix", ",", "$", "blackList", ")", ";", "$", "command", "=", "$", "this", "->", "buildCommand", "(", "$", "template", ",", "$", "argument", ")", ";", "return", "$", "this", "->", "runAndWriteToOutput", "(", "$", "command", ")", ";", "}" ]
Builds a CLI-Command by inserting a blacklist of file paths in the command template and executes it. @param string $template @param string $blacklistToken @param string $prefix @param string $glue @param bool $escape if true the blacklist entries will be escaped for regexp @return int|null
[ "Builds", "a", "CLI", "-", "Command", "by", "inserting", "a", "blacklist", "of", "file", "paths", "in", "the", "command", "template", "and", "executes", "it", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/GenericCommandRunner.php#L92-L113
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/GenericCommandRunner.php
GenericCommandRunner.buildWhitelistArguments
private function buildWhitelistArguments( $targetBranch, string $blacklistToken, string $filter, bool $processIsolation, string $glue = ',' ) : array { $gitChangeSet = $this->adaptableFileFinder->findFiles($filter, $blacklistToken, '', $targetBranch); $changedFiles = $gitChangeSet->getFiles(); $whitelistArguments = empty($changedFiles) || $processIsolation ? $changedFiles : [implode($glue, $changedFiles)]; $this->output->writeln( 'Checking diff to ' . $gitChangeSet->getCommitHash(), OutputInterface::OUTPUT_NORMAL ); $this->output->writeln( 'Files to handle:' . "\n" . implode("\n", $changedFiles) . "\n", OutputInterface::VERBOSITY_VERBOSE ); return $whitelistArguments; }
php
private function buildWhitelistArguments( $targetBranch, string $blacklistToken, string $filter, bool $processIsolation, string $glue = ',' ) : array { $gitChangeSet = $this->adaptableFileFinder->findFiles($filter, $blacklistToken, '', $targetBranch); $changedFiles = $gitChangeSet->getFiles(); $whitelistArguments = empty($changedFiles) || $processIsolation ? $changedFiles : [implode($glue, $changedFiles)]; $this->output->writeln( 'Checking diff to ' . $gitChangeSet->getCommitHash(), OutputInterface::OUTPUT_NORMAL ); $this->output->writeln( 'Files to handle:' . "\n" . implode("\n", $changedFiles) . "\n", OutputInterface::VERBOSITY_VERBOSE ); return $whitelistArguments; }
[ "private", "function", "buildWhitelistArguments", "(", "$", "targetBranch", ",", "string", "$", "blacklistToken", ",", "string", "$", "filter", ",", "bool", "$", "processIsolation", ",", "string", "$", "glue", "=", "','", ")", ":", "array", "{", "$", "gitChangeSet", "=", "$", "this", "->", "adaptableFileFinder", "->", "findFiles", "(", "$", "filter", ",", "$", "blacklistToken", ",", "''", ",", "$", "targetBranch", ")", ";", "$", "changedFiles", "=", "$", "gitChangeSet", "->", "getFiles", "(", ")", ";", "$", "whitelistArguments", "=", "empty", "(", "$", "changedFiles", ")", "||", "$", "processIsolation", "?", "$", "changedFiles", ":", "[", "implode", "(", "$", "glue", ",", "$", "changedFiles", ")", "]", ";", "$", "this", "->", "output", "->", "writeln", "(", "'Checking diff to '", ".", "$", "gitChangeSet", "->", "getCommitHash", "(", ")", ",", "OutputInterface", "::", "OUTPUT_NORMAL", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "'Files to handle:'", ".", "\"\\n\"", ".", "implode", "(", "\"\\n\"", ",", "$", "changedFiles", ")", ".", "\"\\n\"", ",", "OutputInterface", "::", "VERBOSITY_VERBOSE", ")", ";", "return", "$", "whitelistArguments", ";", "}" ]
Builds a list of arguments for insertion into the template. @param string|null $targetBranch @param string $blacklistToken @param string $filter @param bool $processIsolation @param string $glue @return string[]
[ "Builds", "a", "list", "of", "arguments", "for", "insertion", "into", "the", "template", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/GenericCommandRunner.php#L126-L151
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/GenericCommandRunner.php
GenericCommandRunner.runAndWriteToOutput
private function runAndWriteToOutput($commandWithParameters) { $exitCode = 0; $process = $this->processRunner->runAsProcessReturningProcessObject( $commandWithParameters ); if ($process->getExitCode() !== 0) { $exitCode = $process->getExitCode(); $this->output->writeln($process->getOutput(), OutputInterface::OUTPUT_NORMAL); $this->output->writeln($process->getErrorOutput(), OutputInterface::VERBOSITY_NORMAL); } return $exitCode; }
php
private function runAndWriteToOutput($commandWithParameters) { $exitCode = 0; $process = $this->processRunner->runAsProcessReturningProcessObject( $commandWithParameters ); if ($process->getExitCode() !== 0) { $exitCode = $process->getExitCode(); $this->output->writeln($process->getOutput(), OutputInterface::OUTPUT_NORMAL); $this->output->writeln($process->getErrorOutput(), OutputInterface::VERBOSITY_NORMAL); } return $exitCode; }
[ "private", "function", "runAndWriteToOutput", "(", "$", "commandWithParameters", ")", "{", "$", "exitCode", "=", "0", ";", "$", "process", "=", "$", "this", "->", "processRunner", "->", "runAsProcessReturningProcessObject", "(", "$", "commandWithParameters", ")", ";", "if", "(", "$", "process", "->", "getExitCode", "(", ")", "!==", "0", ")", "{", "$", "exitCode", "=", "$", "process", "->", "getExitCode", "(", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "$", "process", "->", "getOutput", "(", ")", ",", "OutputInterface", "::", "OUTPUT_NORMAL", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "$", "process", "->", "getErrorOutput", "(", ")", ",", "OutputInterface", "::", "VERBOSITY_NORMAL", ")", ";", "}", "return", "$", "exitCode", ";", "}" ]
Runs a command and prints the output to the screen if the command couldn't be executed without errors. @param string $commandWithParameters @return int
[ "Runs", "a", "command", "and", "prints", "the", "output", "to", "the", "screen", "if", "the", "command", "couldn", "t", "be", "executed", "without", "errors", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/GenericCommandRunner.php#L161-L174
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/GenericCommandRunner.php
GenericCommandRunner.buildCommand
private function buildCommand($command, $argument) { $command = sprintf($command, $argument); $this->output->writeln( 'Calling following command:' . "\n" . $command, OutputInterface::VERBOSITY_DEBUG ); return $command; }
php
private function buildCommand($command, $argument) { $command = sprintf($command, $argument); $this->output->writeln( 'Calling following command:' . "\n" . $command, OutputInterface::VERBOSITY_DEBUG ); return $command; }
[ "private", "function", "buildCommand", "(", "$", "command", ",", "$", "argument", ")", "{", "$", "command", "=", "sprintf", "(", "$", "command", ",", "$", "argument", ")", ";", "$", "this", "->", "output", "->", "writeln", "(", "'Calling following command:'", ".", "\"\\n\"", ".", "$", "command", ",", "OutputInterface", "::", "VERBOSITY_DEBUG", ")", ";", "return", "$", "command", ";", "}" ]
Builds a command from themplate and argument. @param string $command @param string $argument @return string
[ "Builds", "a", "command", "from", "themplate", "and", "argument", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/GenericCommandRunner.php#L184-L193
train
ZooRoyal/coding-standard
src/main/php/Plugin/Plugin.php
Plugin.npmInstall
public function npmInstall() { $inputOutput = $this->inputOutput; if ($inputOutput->isVerbose()) { $inputOutput->write(sprintf('<info>%s</info>', 'Installing NPM-Packages for Coding-Standard')); } if ($inputOutput->isVeryVerbose()) { $inputOutput->write(sprintf('Executed Command: <info>%s</info>', $this->process->getCommandLine())); } $inputOutput->write('<info>NPM install</info> for zooroyal/coding-standard:'); $this->process->run( function ($type, $buffer) use ($inputOutput) { $inputOutput->write($buffer); } ); $this->process->wait(); $inputOutput->write('<info>NPM packages installed</info> for zooroyal/coding-standard'); }
php
public function npmInstall() { $inputOutput = $this->inputOutput; if ($inputOutput->isVerbose()) { $inputOutput->write(sprintf('<info>%s</info>', 'Installing NPM-Packages for Coding-Standard')); } if ($inputOutput->isVeryVerbose()) { $inputOutput->write(sprintf('Executed Command: <info>%s</info>', $this->process->getCommandLine())); } $inputOutput->write('<info>NPM install</info> for zooroyal/coding-standard:'); $this->process->run( function ($type, $buffer) use ($inputOutput) { $inputOutput->write($buffer); } ); $this->process->wait(); $inputOutput->write('<info>NPM packages installed</info> for zooroyal/coding-standard'); }
[ "public", "function", "npmInstall", "(", ")", "{", "$", "inputOutput", "=", "$", "this", "->", "inputOutput", ";", "if", "(", "$", "inputOutput", "->", "isVerbose", "(", ")", ")", "{", "$", "inputOutput", "->", "write", "(", "sprintf", "(", "'<info>%s</info>'", ",", "'Installing NPM-Packages for Coding-Standard'", ")", ")", ";", "}", "if", "(", "$", "inputOutput", "->", "isVeryVerbose", "(", ")", ")", "{", "$", "inputOutput", "->", "write", "(", "sprintf", "(", "'Executed Command: <info>%s</info>'", ",", "$", "this", "->", "process", "->", "getCommandLine", "(", ")", ")", ")", ";", "}", "$", "inputOutput", "->", "write", "(", "'<info>NPM install</info> for zooroyal/coding-standard:'", ")", ";", "$", "this", "->", "process", "->", "run", "(", "function", "(", "$", "type", ",", "$", "buffer", ")", "use", "(", "$", "inputOutput", ")", "{", "$", "inputOutput", "->", "write", "(", "$", "buffer", ")", ";", "}", ")", ";", "$", "this", "->", "process", "->", "wait", "(", ")", ";", "$", "inputOutput", "->", "write", "(", "'<info>NPM packages installed</info> for zooroyal/coding-standard'", ")", ";", "}" ]
Calls NPM on the command line to install package.json into vendor directory @SuppressWarnings(PHPMD.UnusedLocalVariable) @throws LogicException @throws \Symfony\Component\Process\Exception\RuntimeException @throws ProcessFailedException
[ "Calls", "NPM", "on", "the", "command", "line", "to", "install", "package", ".", "json", "into", "vendor", "directory" ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/Plugin/Plugin.php#L90-L112
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Factories/ContainerFactory.php
ContainerFactory.getContainerInstance
public static function getContainerInstance() : Container { if (self::$container === null) { self::$container = self::getUnboundContainerInstance(); } return self::$container; }
php
public static function getContainerInstance() : Container { if (self::$container === null) { self::$container = self::getUnboundContainerInstance(); } return self::$container; }
[ "public", "static", "function", "getContainerInstance", "(", ")", ":", "Container", "{", "if", "(", "self", "::", "$", "container", "===", "null", ")", "{", "self", "::", "$", "container", "=", "self", "::", "getUnboundContainerInstance", "(", ")", ";", "}", "return", "self", "::", "$", "container", ";", "}" ]
Returns the single application container instance to use. @return Container @throws Exception
[ "Returns", "the", "single", "application", "container", "instance", "to", "use", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Factories/ContainerFactory.php#L28-L35
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Factories/ContainerFactory.php
ContainerFactory.getUnboundContainerInstance
public static function getUnboundContainerInstance() : Container { $builder = new ContainerBuilder(); $builder->useAnnotations(true); $builder->useAutowiring(true); $builder->addDefinitions(__DIR__ . '/../../../../config/phpdi/phpdi.php'); return $builder->build(); }
php
public static function getUnboundContainerInstance() : Container { $builder = new ContainerBuilder(); $builder->useAnnotations(true); $builder->useAutowiring(true); $builder->addDefinitions(__DIR__ . '/../../../../config/phpdi/phpdi.php'); return $builder->build(); }
[ "public", "static", "function", "getUnboundContainerInstance", "(", ")", ":", "Container", "{", "$", "builder", "=", "new", "ContainerBuilder", "(", ")", ";", "$", "builder", "->", "useAnnotations", "(", "true", ")", ";", "$", "builder", "->", "useAutowiring", "(", "true", ")", ";", "$", "builder", "->", "addDefinitions", "(", "__DIR__", ".", "'/../../../../config/phpdi/phpdi.php'", ")", ";", "return", "$", "builder", "->", "build", "(", ")", ";", "}" ]
Returns an unbound Container which is configured like the application container. This is meant to be used for functional tests only. @return Container @throws Exception
[ "Returns", "an", "unbound", "Container", "which", "is", "configured", "like", "the", "application", "container", ".", "This", "is", "meant", "to", "be", "used", "for", "functional", "tests", "only", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Factories/ContainerFactory.php#L44-L51
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Commands/Checks/ForbiddenChangesCommand.php
ForbiddenChangesCommand.publishFindingsToUser
private function publishFindingsToUser(OutputInterface $output, array $wrongfullyChangedFiles) { if (empty($wrongfullyChangedFiles)) { $output->writeln('All good!'); } else { $output->writeln( 'The following files violate change constraints: ' . PHP_EOL . implode(PHP_EOL, $wrongfullyChangedFiles) ); } }
php
private function publishFindingsToUser(OutputInterface $output, array $wrongfullyChangedFiles) { if (empty($wrongfullyChangedFiles)) { $output->writeln('All good!'); } else { $output->writeln( 'The following files violate change constraints: ' . PHP_EOL . implode(PHP_EOL, $wrongfullyChangedFiles) ); } }
[ "private", "function", "publishFindingsToUser", "(", "OutputInterface", "$", "output", ",", "array", "$", "wrongfullyChangedFiles", ")", "{", "if", "(", "empty", "(", "$", "wrongfullyChangedFiles", ")", ")", "{", "$", "output", "->", "writeln", "(", "'All good!'", ")", ";", "}", "else", "{", "$", "output", "->", "writeln", "(", "'The following files violate change constraints: '", ".", "PHP_EOL", ".", "implode", "(", "PHP_EOL", ",", "$", "wrongfullyChangedFiles", ")", ")", ";", "}", "}" ]
Communicates the result to the User. @param OutputInterface $output @param string[] $wrongfullyChangedFiles
[ "Communicates", "the", "result", "to", "the", "User", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Commands/Checks/ForbiddenChangesCommand.php#L99-L109
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/GitChangeSetFilter.php
GitChangeSetFilter.filter
public function filter( GitChangeSet $gitChangeSet, string $filter = '', string $blacklistToken = '', string $whitelistToken = '' ) { $whitelist = []; $deDuped = true; if ($whitelistToken !== '') { $deDuped = false; $whitelist = $this->blacklistFactory->findTokenDirectories($whitelistToken); } $blacklist = $this->blacklistFactory->build($blacklistToken, $deDuped); $list = $this->mergeLists($blacklist, $whitelist); $files = $gitChangeSet->getFiles(); $result = $this->iterateOverFiles($filter, $files, $list); $gitChangeSet->setFiles($result); }
php
public function filter( GitChangeSet $gitChangeSet, string $filter = '', string $blacklistToken = '', string $whitelistToken = '' ) { $whitelist = []; $deDuped = true; if ($whitelistToken !== '') { $deDuped = false; $whitelist = $this->blacklistFactory->findTokenDirectories($whitelistToken); } $blacklist = $this->blacklistFactory->build($blacklistToken, $deDuped); $list = $this->mergeLists($blacklist, $whitelist); $files = $gitChangeSet->getFiles(); $result = $this->iterateOverFiles($filter, $files, $list); $gitChangeSet->setFiles($result); }
[ "public", "function", "filter", "(", "GitChangeSet", "$", "gitChangeSet", ",", "string", "$", "filter", "=", "''", ",", "string", "$", "blacklistToken", "=", "''", ",", "string", "$", "whitelistToken", "=", "''", ")", "{", "$", "whitelist", "=", "[", "]", ";", "$", "deDuped", "=", "true", ";", "if", "(", "$", "whitelistToken", "!==", "''", ")", "{", "$", "deDuped", "=", "false", ";", "$", "whitelist", "=", "$", "this", "->", "blacklistFactory", "->", "findTokenDirectories", "(", "$", "whitelistToken", ")", ";", "}", "$", "blacklist", "=", "$", "this", "->", "blacklistFactory", "->", "build", "(", "$", "blacklistToken", ",", "$", "deDuped", ")", ";", "$", "list", "=", "$", "this", "->", "mergeLists", "(", "$", "blacklist", ",", "$", "whitelist", ")", ";", "$", "files", "=", "$", "gitChangeSet", "->", "getFiles", "(", ")", ";", "$", "result", "=", "$", "this", "->", "iterateOverFiles", "(", "$", "filter", ",", "$", "files", ",", "$", "list", ")", ";", "$", "gitChangeSet", "->", "setFiles", "(", "$", "result", ")", ";", "}" ]
Filters file paths by filter and global Blacklist. @param GitChangeSet $gitChangeSet @param string $filter @param string $blacklistToken @param string $whitelistToken
[ "Filters", "file", "paths", "by", "filter", "and", "global", "Blacklist", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/GitChangeSetFilter.php#L36-L57
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/GitChangeSetFilter.php
GitChangeSetFilter.iterateOverFiles
protected function iterateOverFiles(string $filter, array $files, array $list) : array { $result = []; foreach ($files as $filePath) { //Filter by filter. if ($filter !== '' && substr($filePath, -strlen($filter)) !== $filter) { continue; } //Filter by black/white List $directory = dirname($filePath); $lastDirectoryPath = $filePath; while (!in_array($directory, [$this->environment->getRootDirectory(), '', $lastDirectoryPath], true) ) { if (array_key_exists($directory, $list)) { if ($list[$directory] === true) { $result[] = $filePath; } continue 2; } $lastDirectoryPath = $directory; $directory = dirname($directory); } $result[] = $filePath; } return $result; }
php
protected function iterateOverFiles(string $filter, array $files, array $list) : array { $result = []; foreach ($files as $filePath) { //Filter by filter. if ($filter !== '' && substr($filePath, -strlen($filter)) !== $filter) { continue; } //Filter by black/white List $directory = dirname($filePath); $lastDirectoryPath = $filePath; while (!in_array($directory, [$this->environment->getRootDirectory(), '', $lastDirectoryPath], true) ) { if (array_key_exists($directory, $list)) { if ($list[$directory] === true) { $result[] = $filePath; } continue 2; } $lastDirectoryPath = $directory; $directory = dirname($directory); } $result[] = $filePath; } return $result; }
[ "protected", "function", "iterateOverFiles", "(", "string", "$", "filter", ",", "array", "$", "files", ",", "array", "$", "list", ")", ":", "array", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "files", "as", "$", "filePath", ")", "{", "//Filter by filter.", "if", "(", "$", "filter", "!==", "''", "&&", "substr", "(", "$", "filePath", ",", "-", "strlen", "(", "$", "filter", ")", ")", "!==", "$", "filter", ")", "{", "continue", ";", "}", "//Filter by black/white List", "$", "directory", "=", "dirname", "(", "$", "filePath", ")", ";", "$", "lastDirectoryPath", "=", "$", "filePath", ";", "while", "(", "!", "in_array", "(", "$", "directory", ",", "[", "$", "this", "->", "environment", "->", "getRootDirectory", "(", ")", ",", "''", ",", "$", "lastDirectoryPath", "]", ",", "true", ")", ")", "{", "if", "(", "array_key_exists", "(", "$", "directory", ",", "$", "list", ")", ")", "{", "if", "(", "$", "list", "[", "$", "directory", "]", "===", "true", ")", "{", "$", "result", "[", "]", "=", "$", "filePath", ";", "}", "continue", "2", ";", "}", "$", "lastDirectoryPath", "=", "$", "directory", ";", "$", "directory", "=", "dirname", "(", "$", "directory", ")", ";", "}", "$", "result", "[", "]", "=", "$", "filePath", ";", "}", "return", "$", "result", ";", "}" ]
Iterates over the files and returns files as configured in list and filter. @param string $filter @param string[] $files @param bool[] $list @return array
[ "Iterates", "over", "the", "files", "and", "returns", "files", "as", "configured", "in", "list", "and", "filter", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/GitChangeSetFilter.php#L68-L93
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/GitChangeSetFilter.php
GitChangeSetFilter.mergeLists
private function mergeLists(array $blacklist, array $whitelist) : array { if (count(array_intersect($blacklist, $whitelist)) !== 0) { throw new LogicException('Directories can\'t be black- and whitelisted at the same time', 1553780055); } return array_merge( array_fill_keys($blacklist, false), array_fill_keys($whitelist, true) ); }
php
private function mergeLists(array $blacklist, array $whitelist) : array { if (count(array_intersect($blacklist, $whitelist)) !== 0) { throw new LogicException('Directories can\'t be black- and whitelisted at the same time', 1553780055); } return array_merge( array_fill_keys($blacklist, false), array_fill_keys($whitelist, true) ); }
[ "private", "function", "mergeLists", "(", "array", "$", "blacklist", ",", "array", "$", "whitelist", ")", ":", "array", "{", "if", "(", "count", "(", "array_intersect", "(", "$", "blacklist", ",", "$", "whitelist", ")", ")", "!==", "0", ")", "{", "throw", "new", "LogicException", "(", "'Directories can\\'t be black- and whitelisted at the same time'", ",", "1553780055", ")", ";", "}", "return", "array_merge", "(", "array_fill_keys", "(", "$", "blacklist", ",", "false", ")", ",", "array_fill_keys", "(", "$", "whitelist", ",", "true", ")", ")", ";", "}" ]
Generate merged list. @param string[] $blacklist @param string[] $whitelist @return array @throws LogicException
[ "Generate", "merged", "list", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/GitChangeSetFilter.php#L105-L115
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Factories/FinderFactory.php
FinderFactory.build
public function build() { $result = new Finder(); if (method_exists($result, 'useBestAdapter')) { $result->useBestAdapter(); } $result->ignoreDotFiles(false); $result->ignoreVCS(false); return $result; }
php
public function build() { $result = new Finder(); if (method_exists($result, 'useBestAdapter')) { $result->useBestAdapter(); } $result->ignoreDotFiles(false); $result->ignoreVCS(false); return $result; }
[ "public", "function", "build", "(", ")", "{", "$", "result", "=", "new", "Finder", "(", ")", ";", "if", "(", "method_exists", "(", "$", "result", ",", "'useBestAdapter'", ")", ")", "{", "$", "result", "->", "useBestAdapter", "(", ")", ";", "}", "$", "result", "->", "ignoreDotFiles", "(", "false", ")", ";", "$", "result", "->", "ignoreVCS", "(", "false", ")", ";", "return", "$", "result", ";", "}" ]
This method returns a new Finder instance. @return Finder
[ "This", "method", "returns", "a", "new", "Finder", "instance", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Factories/FinderFactory.php#L17-L27
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Commands/StaticCodeAnalysis/AbstractFixableToolCommand.php
AbstractFixableToolCommand.buildInputDefinition
protected function buildInputDefinition() : InputDefinition { return new InputDefinition( [ new InputOption( 'target', 't', InputOption::VALUE_REQUIRED, 'Finds Files which have changed since the current branch parted from the target branch ' . 'only. The Value has to be a commit-ish.', false ), new InputOption( 'auto-target', 'a', InputOption::VALUE_NONE, 'Finds Files which have changed since the current branch parted from the parent branch ' . 'only. It tries to find the parent branch by automagic.' ), new InputOption( 'fix', 'f', InputOption::VALUE_NONE, 'Runs tool to try to fix violations automagically.' ), new InputOption( 'process-isolation', 'p', InputOption::VALUE_NONE, 'Runs all checks in separate processes. Slow but not as resource hungry.' ), ] ); }
php
protected function buildInputDefinition() : InputDefinition { return new InputDefinition( [ new InputOption( 'target', 't', InputOption::VALUE_REQUIRED, 'Finds Files which have changed since the current branch parted from the target branch ' . 'only. The Value has to be a commit-ish.', false ), new InputOption( 'auto-target', 'a', InputOption::VALUE_NONE, 'Finds Files which have changed since the current branch parted from the parent branch ' . 'only. It tries to find the parent branch by automagic.' ), new InputOption( 'fix', 'f', InputOption::VALUE_NONE, 'Runs tool to try to fix violations automagically.' ), new InputOption( 'process-isolation', 'p', InputOption::VALUE_NONE, 'Runs all checks in separate processes. Slow but not as resource hungry.' ), ] ); }
[ "protected", "function", "buildInputDefinition", "(", ")", ":", "InputDefinition", "{", "return", "new", "InputDefinition", "(", "[", "new", "InputOption", "(", "'target'", ",", "'t'", ",", "InputOption", "::", "VALUE_REQUIRED", ",", "'Finds Files which have changed since the current branch parted from the target branch '", ".", "'only. The Value has to be a commit-ish.'", ",", "false", ")", ",", "new", "InputOption", "(", "'auto-target'", ",", "'a'", ",", "InputOption", "::", "VALUE_NONE", ",", "'Finds Files which have changed since the current branch parted from the parent branch '", ".", "'only. It tries to find the parent branch by automagic.'", ")", ",", "new", "InputOption", "(", "'fix'", ",", "'f'", ",", "InputOption", "::", "VALUE_NONE", ",", "'Runs tool to try to fix violations automagically.'", ")", ",", "new", "InputOption", "(", "'process-isolation'", ",", "'p'", ",", "InputOption", "::", "VALUE_NONE", ",", "'Runs all checks in separate processes. Slow but not as resource hungry.'", ")", ",", "]", ")", ";", "}" ]
Builds InputDefinition for Command. @return InputDefinition
[ "Builds", "InputDefinition", "for", "Command", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Commands/StaticCodeAnalysis/AbstractFixableToolCommand.php#L41-L74
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Commands/StaticCodeAnalysis/FindFilesToCheckCommand.php
FindFilesToCheckCommand.buildInputDefinition
private function buildInputDefinition() : InputDefinition { return new InputDefinition( [ new InputOption( 'target', 't', InputOption::VALUE_REQUIRED, 'Finds files which have changed since the current branch parted from the target branch ' . 'only. The Value has to be a commit-ish.', false ), new InputOption( 'auto-target', 'a', InputOption::VALUE_NONE, 'Finds Files which have changed since the current branch parted from the parent branch ' . 'only. It tries to find the parent branch by automagic.' ), new InputOption( 'blacklist-token', 'b', InputOption::VALUE_REQUIRED, 'Name of the file which triggers the exclusion of the path', '' ), new InputOption( 'whitelist-token', 'w', InputOption::VALUE_REQUIRED, 'Name of the file which triggers the inclusion of the path', '' ), new InputOption( 'filter', 'f', InputOption::VALUE_REQUIRED, 'Filters the Filename. For example .php for PHP-Files', '' ), new InputOption( 'exclusionList', 'e', InputOption::VALUE_NONE, 'Gathers list of directories which should be excluded' ), ] ); }
php
private function buildInputDefinition() : InputDefinition { return new InputDefinition( [ new InputOption( 'target', 't', InputOption::VALUE_REQUIRED, 'Finds files which have changed since the current branch parted from the target branch ' . 'only. The Value has to be a commit-ish.', false ), new InputOption( 'auto-target', 'a', InputOption::VALUE_NONE, 'Finds Files which have changed since the current branch parted from the parent branch ' . 'only. It tries to find the parent branch by automagic.' ), new InputOption( 'blacklist-token', 'b', InputOption::VALUE_REQUIRED, 'Name of the file which triggers the exclusion of the path', '' ), new InputOption( 'whitelist-token', 'w', InputOption::VALUE_REQUIRED, 'Name of the file which triggers the inclusion of the path', '' ), new InputOption( 'filter', 'f', InputOption::VALUE_REQUIRED, 'Filters the Filename. For example .php for PHP-Files', '' ), new InputOption( 'exclusionList', 'e', InputOption::VALUE_NONE, 'Gathers list of directories which should be excluded' ), ] ); }
[ "private", "function", "buildInputDefinition", "(", ")", ":", "InputDefinition", "{", "return", "new", "InputDefinition", "(", "[", "new", "InputOption", "(", "'target'", ",", "'t'", ",", "InputOption", "::", "VALUE_REQUIRED", ",", "'Finds files which have changed since the current branch parted from the target branch '", ".", "'only. The Value has to be a commit-ish.'", ",", "false", ")", ",", "new", "InputOption", "(", "'auto-target'", ",", "'a'", ",", "InputOption", "::", "VALUE_NONE", ",", "'Finds Files which have changed since the current branch parted from the parent branch '", ".", "'only. It tries to find the parent branch by automagic.'", ")", ",", "new", "InputOption", "(", "'blacklist-token'", ",", "'b'", ",", "InputOption", "::", "VALUE_REQUIRED", ",", "'Name of the file which triggers the exclusion of the path'", ",", "''", ")", ",", "new", "InputOption", "(", "'whitelist-token'", ",", "'w'", ",", "InputOption", "::", "VALUE_REQUIRED", ",", "'Name of the file which triggers the inclusion of the path'", ",", "''", ")", ",", "new", "InputOption", "(", "'filter'", ",", "'f'", ",", "InputOption", "::", "VALUE_REQUIRED", ",", "'Filters the Filename. For example .php for PHP-Files'", ",", "''", ")", ",", "new", "InputOption", "(", "'exclusionList'", ",", "'e'", ",", "InputOption", "::", "VALUE_NONE", ",", "'Gathers list of directories which should be excluded'", ")", ",", "]", ")", ";", "}" ]
Builds InputDefinition for Command @return InputDefinition @SuppressWarnings(PHPMD.ExcessiveMethodLength)
[ "Builds", "InputDefinition", "for", "Command" ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Commands/StaticCodeAnalysis/FindFilesToCheckCommand.php#L79-L127
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Factories/BlacklistFactory.php
BlacklistFactory.build
public function build(string $token = '', bool $deDuped = true) : array { $rawExcludePathsByFileByToken = []; if ($token !== '') { $rawExcludePathsByFileByToken = $this->findTokenDirectories($token); } $rawExcludePathsByFileByGit = $this->findGitDirectories(); $rawExcludePathsByBlacklist = $this->findDirectoriesFromEnvironment($this->environment); $rawExcludePaths = array_merge( $rawExcludePathsByBlacklist, $rawExcludePathsByFileByToken, $rawExcludePathsByFileByGit ); $filteredArray = $deDuped === true ? $this->deDupePaths($rawExcludePaths) : $rawExcludePaths; return $filteredArray; }
php
public function build(string $token = '', bool $deDuped = true) : array { $rawExcludePathsByFileByToken = []; if ($token !== '') { $rawExcludePathsByFileByToken = $this->findTokenDirectories($token); } $rawExcludePathsByFileByGit = $this->findGitDirectories(); $rawExcludePathsByBlacklist = $this->findDirectoriesFromEnvironment($this->environment); $rawExcludePaths = array_merge( $rawExcludePathsByBlacklist, $rawExcludePathsByFileByToken, $rawExcludePathsByFileByGit ); $filteredArray = $deDuped === true ? $this->deDupePaths($rawExcludePaths) : $rawExcludePaths; return $filteredArray; }
[ "public", "function", "build", "(", "string", "$", "token", "=", "''", ",", "bool", "$", "deDuped", "=", "true", ")", ":", "array", "{", "$", "rawExcludePathsByFileByToken", "=", "[", "]", ";", "if", "(", "$", "token", "!==", "''", ")", "{", "$", "rawExcludePathsByFileByToken", "=", "$", "this", "->", "findTokenDirectories", "(", "$", "token", ")", ";", "}", "$", "rawExcludePathsByFileByGit", "=", "$", "this", "->", "findGitDirectories", "(", ")", ";", "$", "rawExcludePathsByBlacklist", "=", "$", "this", "->", "findDirectoriesFromEnvironment", "(", "$", "this", "->", "environment", ")", ";", "$", "rawExcludePaths", "=", "array_merge", "(", "$", "rawExcludePathsByBlacklist", ",", "$", "rawExcludePathsByFileByToken", ",", "$", "rawExcludePathsByFileByGit", ")", ";", "$", "filteredArray", "=", "$", "deDuped", "===", "true", "?", "$", "this", "->", "deDupePaths", "(", "$", "rawExcludePaths", ")", ":", "$", "rawExcludePaths", ";", "return", "$", "filteredArray", ";", "}" ]
This function computes a blacklist of directories which should not be checked. @param string $token @param bool $deDuped @return string[]
[ "This", "function", "computes", "a", "blacklist", "of", "directories", "which", "should", "not", "be", "checked", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Factories/BlacklistFactory.php#L42-L61
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Factories/BlacklistFactory.php
BlacklistFactory.findTokenDirectories
public function findTokenDirectories(string $token) : array { $tokenFinder = $this->finderFactory->build(); $tokenFinder->in($this->environment->getRootDirectory())->files()->name($token); $rawExcludePathsByToken = $this->finderToRealPathConverter ->finderToArrayOfPaths($tokenFinder); return array_map('dirname', $rawExcludePathsByToken); }
php
public function findTokenDirectories(string $token) : array { $tokenFinder = $this->finderFactory->build(); $tokenFinder->in($this->environment->getRootDirectory())->files()->name($token); $rawExcludePathsByToken = $this->finderToRealPathConverter ->finderToArrayOfPaths($tokenFinder); return array_map('dirname', $rawExcludePathsByToken); }
[ "public", "function", "findTokenDirectories", "(", "string", "$", "token", ")", ":", "array", "{", "$", "tokenFinder", "=", "$", "this", "->", "finderFactory", "->", "build", "(", ")", ";", "$", "tokenFinder", "->", "in", "(", "$", "this", "->", "environment", "->", "getRootDirectory", "(", ")", ")", "->", "files", "(", ")", "->", "name", "(", "$", "token", ")", ";", "$", "rawExcludePathsByToken", "=", "$", "this", "->", "finderToRealPathConverter", "->", "finderToArrayOfPaths", "(", "$", "tokenFinder", ")", ";", "return", "array_map", "(", "'dirname'", ",", "$", "rawExcludePathsByToken", ")", ";", "}" ]
Searches for directories containing stopword files. @param string $token @return string[]
[ "Searches", "for", "directories", "containing", "stopword", "files", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Factories/BlacklistFactory.php#L98-L105
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Factories/BlacklistFactory.php
BlacklistFactory.findGitDirectories
private function findGitDirectories() : array { $finderGit = $this->finderFactory->build(); $finderGit->in($this->environment->getRootDirectory())->depth('> 0')->path('/.git$/'); $rawExcludePathsByFileByGit = $this->finderToRealPathConverter->finderToArrayOfPaths($finderGit); return array_map('dirname', $rawExcludePathsByFileByGit); }
php
private function findGitDirectories() : array { $finderGit = $this->finderFactory->build(); $finderGit->in($this->environment->getRootDirectory())->depth('> 0')->path('/.git$/'); $rawExcludePathsByFileByGit = $this->finderToRealPathConverter->finderToArrayOfPaths($finderGit); return array_map('dirname', $rawExcludePathsByFileByGit); }
[ "private", "function", "findGitDirectories", "(", ")", ":", "array", "{", "$", "finderGit", "=", "$", "this", "->", "finderFactory", "->", "build", "(", ")", ";", "$", "finderGit", "->", "in", "(", "$", "this", "->", "environment", "->", "getRootDirectory", "(", ")", ")", "->", "depth", "(", "'> 0'", ")", "->", "path", "(", "'/.git$/'", ")", ";", "$", "rawExcludePathsByFileByGit", "=", "$", "this", "->", "finderToRealPathConverter", "->", "finderToArrayOfPaths", "(", "$", "finderGit", ")", ";", "return", "array_map", "(", "'dirname'", ",", "$", "rawExcludePathsByFileByGit", ")", ";", "}" ]
Finds submodules of in the project directory. @return string[]
[ "Finds", "submodules", "of", "in", "the", "project", "directory", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Factories/BlacklistFactory.php#L112-L118
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Factories/BlacklistFactory.php
BlacklistFactory.findDirectoriesFromEnvironment
private function findDirectoriesFromEnvironment(Environment $environment) : array { $finderBlacklist = $this->finderFactory->build(); $finderBlacklist->in($environment->getRootDirectory())->directories(); foreach ($environment->getBlacklistedDirectories() as $blacklistedDirectory) { $finderBlacklist->path('/' . preg_quote($blacklistedDirectory, '/') . '$/') ->notPath('/' . preg_quote($blacklistedDirectory, '/') . './'); } $rawExcludePathsByBlacklist = $this->finderToRealPathConverter->finderToArrayOfPaths($finderBlacklist); return $rawExcludePathsByBlacklist; }
php
private function findDirectoriesFromEnvironment(Environment $environment) : array { $finderBlacklist = $this->finderFactory->build(); $finderBlacklist->in($environment->getRootDirectory())->directories(); foreach ($environment->getBlacklistedDirectories() as $blacklistedDirectory) { $finderBlacklist->path('/' . preg_quote($blacklistedDirectory, '/') . '$/') ->notPath('/' . preg_quote($blacklistedDirectory, '/') . './'); } $rawExcludePathsByBlacklist = $this->finderToRealPathConverter->finderToArrayOfPaths($finderBlacklist); return $rawExcludePathsByBlacklist; }
[ "private", "function", "findDirectoriesFromEnvironment", "(", "Environment", "$", "environment", ")", ":", "array", "{", "$", "finderBlacklist", "=", "$", "this", "->", "finderFactory", "->", "build", "(", ")", ";", "$", "finderBlacklist", "->", "in", "(", "$", "environment", "->", "getRootDirectory", "(", ")", ")", "->", "directories", "(", ")", ";", "foreach", "(", "$", "environment", "->", "getBlacklistedDirectories", "(", ")", "as", "$", "blacklistedDirectory", ")", "{", "$", "finderBlacklist", "->", "path", "(", "'/'", ".", "preg_quote", "(", "$", "blacklistedDirectory", ",", "'/'", ")", ".", "'$/'", ")", "->", "notPath", "(", "'/'", ".", "preg_quote", "(", "$", "blacklistedDirectory", ",", "'/'", ")", ".", "'./'", ")", ";", "}", "$", "rawExcludePathsByBlacklist", "=", "$", "this", "->", "finderToRealPathConverter", "->", "finderToArrayOfPaths", "(", "$", "finderBlacklist", ")", ";", "return", "$", "rawExcludePathsByBlacklist", ";", "}" ]
Finds blacklisted directories by Environment. @param Environment $environment @return string[]
[ "Finds", "blacklisted", "directories", "by", "Environment", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Factories/BlacklistFactory.php#L127-L137
train
ZooRoyal/coding-standard
src/main/php/CommandLine/FileFinders/AllCheckableFileFinder.php
AllCheckableFileFinder.findFiles
public function findFiles( string $filter = '', string $blacklistToken = '', string $whitelistToken = '', $targetBranch = '' ) : GitChangeSet { $filesFromGit = explode("\n", trim($this->processRunner->runAsProcess('git', 'ls-files'))); $gitChangeSet = $this->gitChangeSetFactory->build($filesFromGit, ''); $this->gitChangeSetFilter->filter($gitChangeSet, $filter, $blacklistToken); return $gitChangeSet; }
php
public function findFiles( string $filter = '', string $blacklistToken = '', string $whitelistToken = '', $targetBranch = '' ) : GitChangeSet { $filesFromGit = explode("\n", trim($this->processRunner->runAsProcess('git', 'ls-files'))); $gitChangeSet = $this->gitChangeSetFactory->build($filesFromGit, ''); $this->gitChangeSetFilter->filter($gitChangeSet, $filter, $blacklistToken); return $gitChangeSet; }
[ "public", "function", "findFiles", "(", "string", "$", "filter", "=", "''", ",", "string", "$", "blacklistToken", "=", "''", ",", "string", "$", "whitelistToken", "=", "''", ",", "$", "targetBranch", "=", "''", ")", ":", "GitChangeSet", "{", "$", "filesFromGit", "=", "explode", "(", "\"\\n\"", ",", "trim", "(", "$", "this", "->", "processRunner", "->", "runAsProcess", "(", "'git'", ",", "'ls-files'", ")", ")", ")", ";", "$", "gitChangeSet", "=", "$", "this", "->", "gitChangeSetFactory", "->", "build", "(", "$", "filesFromGit", ",", "''", ")", ";", "$", "this", "->", "gitChangeSetFilter", "->", "filter", "(", "$", "gitChangeSet", ",", "$", "filter", ",", "$", "blacklistToken", ")", ";", "return", "$", "gitChangeSet", ";", "}" ]
This function finds all files to check. @param string $filter @param string $blacklistToken @param string $whitelistToken @param string|false $targetBranch @return GitChangeSet
[ "This", "function", "finds", "all", "files", "to", "check", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/FileFinders/AllCheckableFileFinder.php#L46-L58
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/Environment.php
Environment.guessParentBranchAsCommitHash
public function guessParentBranchAsCommitHash(string $branchName = 'HEAD') : string { $initialNumberOfContainingBranches = $this->getCountOfContainingBranches($branchName); while ($this->isParentCommitishACommit($branchName)) { $branchName .= '^'; $numberOfContainingBranches = $this->getCountOfContainingBranches($branchName); if ($numberOfContainingBranches !== $initialNumberOfContainingBranches) { break; } } $gitCommitHash = $this->processRunner->runAsProcess('git', 'rev-parse', $branchName); return $gitCommitHash; }
php
public function guessParentBranchAsCommitHash(string $branchName = 'HEAD') : string { $initialNumberOfContainingBranches = $this->getCountOfContainingBranches($branchName); while ($this->isParentCommitishACommit($branchName)) { $branchName .= '^'; $numberOfContainingBranches = $this->getCountOfContainingBranches($branchName); if ($numberOfContainingBranches !== $initialNumberOfContainingBranches) { break; } } $gitCommitHash = $this->processRunner->runAsProcess('git', 'rev-parse', $branchName); return $gitCommitHash; }
[ "public", "function", "guessParentBranchAsCommitHash", "(", "string", "$", "branchName", "=", "'HEAD'", ")", ":", "string", "{", "$", "initialNumberOfContainingBranches", "=", "$", "this", "->", "getCountOfContainingBranches", "(", "$", "branchName", ")", ";", "while", "(", "$", "this", "->", "isParentCommitishACommit", "(", "$", "branchName", ")", ")", "{", "$", "branchName", ".=", "'^'", ";", "$", "numberOfContainingBranches", "=", "$", "this", "->", "getCountOfContainingBranches", "(", "$", "branchName", ")", ";", "if", "(", "$", "numberOfContainingBranches", "!==", "$", "initialNumberOfContainingBranches", ")", "{", "break", ";", "}", "}", "$", "gitCommitHash", "=", "$", "this", "->", "processRunner", "->", "runAsProcess", "(", "'git'", ",", "'rev-parse'", ",", "$", "branchName", ")", ";", "return", "$", "gitCommitHash", ";", "}" ]
This method searches the first parent commit which is part of another branch and returns this commit as merge base with parent branch. @param string $branchName @return string
[ "This", "method", "searches", "the", "first", "parent", "commit", "which", "is", "part", "of", "another", "branch", "and", "returns", "this", "commit", "as", "merge", "base", "with", "parent", "branch", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/Environment.php#L88-L102
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/Environment.php
Environment.getCountOfContainingBranches
private function getCountOfContainingBranches(string $targetCommit) : int { $numberOfContainingBranches = substr_count( $this->processRunner->runAsProcess( 'git', 'branch', '-a', '--contains', $targetCommit ), PHP_EOL ); return $numberOfContainingBranches; }
php
private function getCountOfContainingBranches(string $targetCommit) : int { $numberOfContainingBranches = substr_count( $this->processRunner->runAsProcess( 'git', 'branch', '-a', '--contains', $targetCommit ), PHP_EOL ); return $numberOfContainingBranches; }
[ "private", "function", "getCountOfContainingBranches", "(", "string", "$", "targetCommit", ")", ":", "int", "{", "$", "numberOfContainingBranches", "=", "substr_count", "(", "$", "this", "->", "processRunner", "->", "runAsProcess", "(", "'git'", ",", "'branch'", ",", "'-a'", ",", "'--contains'", ",", "$", "targetCommit", ")", ",", "PHP_EOL", ")", ";", "return", "$", "numberOfContainingBranches", ";", "}" ]
Calls git to retriev the count of branches this commit is part of. @param string $targetCommit @return int
[ "Calls", "git", "to", "retriev", "the", "count", "of", "branches", "this", "commit", "is", "part", "of", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/Environment.php#L111-L125
train
ZooRoyal/coding-standard
src/main/php/CommandLine/FileFinders/ParentByFileFinder.php
ParentByFileFinder.findParentByFile
public function findParentByFile($fileName, $directory = null) { if (empty($fileName)) { throw new InvalidArgumentException('$fileName (value was ' . $fileName . ') must be set.', 1525785151); } $directory = $directory ?? getcwd(); $hit = null; while ($directory !== $this->environment->getRootDirectory() && $directory !== '' && $directory !== '.' && $directory !== '/' ) { if ($this->filesystem->exists($directory . '/' . $fileName)) { $hit = $directory; break; } $directory = dirname($directory); } return $hit; }
php
public function findParentByFile($fileName, $directory = null) { if (empty($fileName)) { throw new InvalidArgumentException('$fileName (value was ' . $fileName . ') must be set.', 1525785151); } $directory = $directory ?? getcwd(); $hit = null; while ($directory !== $this->environment->getRootDirectory() && $directory !== '' && $directory !== '.' && $directory !== '/' ) { if ($this->filesystem->exists($directory . '/' . $fileName)) { $hit = $directory; break; } $directory = dirname($directory); } return $hit; }
[ "public", "function", "findParentByFile", "(", "$", "fileName", ",", "$", "directory", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "fileName", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'$fileName (value was '", ".", "$", "fileName", ".", "') must be set.'", ",", "1525785151", ")", ";", "}", "$", "directory", "=", "$", "directory", "??", "getcwd", "(", ")", ";", "$", "hit", "=", "null", ";", "while", "(", "$", "directory", "!==", "$", "this", "->", "environment", "->", "getRootDirectory", "(", ")", "&&", "$", "directory", "!==", "''", "&&", "$", "directory", "!==", "'.'", "&&", "$", "directory", "!==", "'/'", ")", "{", "if", "(", "$", "this", "->", "filesystem", "->", "exists", "(", "$", "directory", ".", "'/'", ".", "$", "fileName", ")", ")", "{", "$", "hit", "=", "$", "directory", ";", "break", ";", "}", "$", "directory", "=", "dirname", "(", "$", "directory", ")", ";", "}", "return", "$", "hit", ";", "}" ]
This method finds the closest parent directory containing a file identified by name. @param string $fileName @param string $directory @return null|string @throws InvalidArgumentException
[ "This", "method", "finds", "the", "closest", "parent", "directory", "containing", "a", "file", "identified", "by", "name", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/FileFinders/ParentByFileFinder.php#L31-L53
train
ZooRoyal/coding-standard
src/main/php/CommandLine/Library/FinderToPathsConverter.php
FinderToPathsConverter.finderToArrayOfPaths
public function finderToArrayOfPaths(Finder $finder) : array { $result = array_map( function ($value) { /** @var SplFileInfo $value */ return $value->getRelativePathname(); }, iterator_to_array($finder) ); return array_values($result); }
php
public function finderToArrayOfPaths(Finder $finder) : array { $result = array_map( function ($value) { /** @var SplFileInfo $value */ return $value->getRelativePathname(); }, iterator_to_array($finder) ); return array_values($result); }
[ "public", "function", "finderToArrayOfPaths", "(", "Finder", "$", "finder", ")", ":", "array", "{", "$", "result", "=", "array_map", "(", "function", "(", "$", "value", ")", "{", "/** @var SplFileInfo $value */", "return", "$", "value", "->", "getRelativePathname", "(", ")", ";", "}", ",", "iterator_to_array", "(", "$", "finder", ")", ")", ";", "return", "array_values", "(", "$", "result", ")", ";", "}" ]
Converts Finder objects to Arrays of their relative paths. @param Finder $finder @return string[]
[ "Converts", "Finder", "objects", "to", "Arrays", "of", "their", "relative", "paths", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/Library/FinderToPathsConverter.php#L17-L28
train
ZooRoyal/coding-standard
src/main/php/CommandLine/ToolAdapters/AbstractBlackAndWhitelistAdapter.php
AbstractBlackAndWhitelistAdapter.runTool
protected function runTool( $targetBranch, bool $processIsolation, string $fullMessage, string $tool, string $diffMessage ) { if ($targetBranch === false || $this->environment->isLocalBranchEqualTo($targetBranch)) { $this->output->writeln($fullMessage, OutputInterface::VERBOSITY_NORMAL); $template = $this->commands[$tool . 'BL']; $exitCode = $this->genericCommandRunner->runBlacklistCommand( $template, $this->blacklistToken, $this->blacklistPrefix, $this->blacklistGlue, $this->escape ); } else { $this->output->writeln($diffMessage, OutputInterface::VERBOSITY_NORMAL); $template = $this->commands[$tool . 'WL']; $exitCode = $this->genericCommandRunner->runWhitelistCommand( $template, $targetBranch, $this->blacklistToken, $this->filter, $processIsolation, $this->whitelistGlue ); } return $exitCode; }
php
protected function runTool( $targetBranch, bool $processIsolation, string $fullMessage, string $tool, string $diffMessage ) { if ($targetBranch === false || $this->environment->isLocalBranchEqualTo($targetBranch)) { $this->output->writeln($fullMessage, OutputInterface::VERBOSITY_NORMAL); $template = $this->commands[$tool . 'BL']; $exitCode = $this->genericCommandRunner->runBlacklistCommand( $template, $this->blacklistToken, $this->blacklistPrefix, $this->blacklistGlue, $this->escape ); } else { $this->output->writeln($diffMessage, OutputInterface::VERBOSITY_NORMAL); $template = $this->commands[$tool . 'WL']; $exitCode = $this->genericCommandRunner->runWhitelistCommand( $template, $targetBranch, $this->blacklistToken, $this->filter, $processIsolation, $this->whitelistGlue ); } return $exitCode; }
[ "protected", "function", "runTool", "(", "$", "targetBranch", ",", "bool", "$", "processIsolation", ",", "string", "$", "fullMessage", ",", "string", "$", "tool", ",", "string", "$", "diffMessage", ")", "{", "if", "(", "$", "targetBranch", "===", "false", "||", "$", "this", "->", "environment", "->", "isLocalBranchEqualTo", "(", "$", "targetBranch", ")", ")", "{", "$", "this", "->", "output", "->", "writeln", "(", "$", "fullMessage", ",", "OutputInterface", "::", "VERBOSITY_NORMAL", ")", ";", "$", "template", "=", "$", "this", "->", "commands", "[", "$", "tool", ".", "'BL'", "]", ";", "$", "exitCode", "=", "$", "this", "->", "genericCommandRunner", "->", "runBlacklistCommand", "(", "$", "template", ",", "$", "this", "->", "blacklistToken", ",", "$", "this", "->", "blacklistPrefix", ",", "$", "this", "->", "blacklistGlue", ",", "$", "this", "->", "escape", ")", ";", "}", "else", "{", "$", "this", "->", "output", "->", "writeln", "(", "$", "diffMessage", ",", "OutputInterface", "::", "VERBOSITY_NORMAL", ")", ";", "$", "template", "=", "$", "this", "->", "commands", "[", "$", "tool", ".", "'WL'", "]", ";", "$", "exitCode", "=", "$", "this", "->", "genericCommandRunner", "->", "runWhitelistCommand", "(", "$", "template", ",", "$", "targetBranch", ",", "$", "this", "->", "blacklistToken", ",", "$", "this", "->", "filter", ",", "$", "processIsolation", ",", "$", "this", "->", "whitelistGlue", ")", ";", "}", "return", "$", "exitCode", ";", "}" ]
Runs ESLint in normal or fix mode according to settings. @param string|false|null $targetBranch @param bool $processIsolation @param string $fullMessage @param string $tool @param string $diffMessage @return int|null
[ "Runs", "ESLint", "in", "normal", "or", "fix", "mode", "according", "to", "settings", "." ]
0d36062c33e25f15690f2c86651623255fc19362
https://github.com/ZooRoyal/coding-standard/blob/0d36062c33e25f15690f2c86651623255fc19362/src/main/php/CommandLine/ToolAdapters/AbstractBlackAndWhitelistAdapter.php#L44-L75
train
postcode-nl/PostcodeNl_Api_RestClient
library/PostcodeNl/Api/RestClient.php
PostcodeNl_Api_RestClient.setDebugEnabled
public function setDebugEnabled($debugEnabled = true) { $this->_debugEnabled = (boolean)$debugEnabled; if (!$this->_debugEnabled) $this->_debugData = null; }
php
public function setDebugEnabled($debugEnabled = true) { $this->_debugEnabled = (boolean)$debugEnabled; if (!$this->_debugEnabled) $this->_debugData = null; }
[ "public", "function", "setDebugEnabled", "(", "$", "debugEnabled", "=", "true", ")", "{", "$", "this", "->", "_debugEnabled", "=", "(", "boolean", ")", "$", "debugEnabled", ";", "if", "(", "!", "$", "this", "->", "_debugEnabled", ")", "$", "this", "->", "_debugData", "=", "null", ";", "}" ]
Toggle debug option. @param bool $debugEnabled
[ "Toggle", "debug", "option", "." ]
8eb69b44bfd2c4665f8d6a9dcd41c4fae874150b
https://github.com/postcode-nl/PostcodeNl_Api_RestClient/blob/8eb69b44bfd2c4665f8d6a9dcd41c4fae874150b/library/PostcodeNl/Api/RestClient.php#L135-L140
train
postcode-nl/PostcodeNl_Api_RestClient
library/PostcodeNl/Api/RestClient.php
PostcodeNl_Api_RestClient._doRestCall
protected function _doRestCall($url, array $data = []) { // Connect using cURL $ch = curl_init(); // Set the HTTP request type curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); // Set URL to connect to curl_setopt($ch, CURLOPT_URL, $url); // We want the response returned to us. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Maximum number of seconds allowed to set up the connection. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::CONNECTTIMEOUT); // Maximum number of seconds allowed to receive the response. curl_setopt($ch, CURLOPT_TIMEOUT, self::TIMEOUT); // The Postcode.nl API uses HTTP BASIC authentication (https://en.wikipedia.org/wiki/Basic_access_authentication) curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // Use key as 'username' and secret as 'password' curl_setopt($ch, CURLOPT_USERPWD, $this->_appKey .':'. $this->_appSecret); // Identify this client with a User Agent curl_setopt($ch, CURLOPT_USERAGENT, 'PostcodeNl_Api_RestClient/' . self::VERSION .' PHP/'. phpversion()); // Various debug options if ($this->_debugEnabled) { curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_HEADER, true); } // Do the request $response = curl_exec($ch); // Remember the HTTP status code we receive $responseStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $responseStatusCodeClass = floor($responseStatusCode/100)*100; // Any errors? Remember them now. $curlError = curl_error($ch); $curlErrorNr = curl_errno($ch); if ($this->_debugEnabled) { $this->_debugData['request'] = curl_getinfo($ch, CURLINFO_HEADER_OUT); $this->_debugData['response'] = $response; // Strip off header that was added for debug purposes. $response = substr($response, strpos($response, "\r\n\r\n") + 4); } // And close the cURL handle curl_close($ch); if ($curlError) { // We could not connect, cURL has the reason. (we hope) throw new PostcodeNl_Api_RestClient_ClientException('Connection error `'. $curlErrorNr .'`: `'. $curlError .'`', $curlErrorNr); } // Parse the response as JSON, will be null if not parsable JSON. $jsonResponse = json_decode($response, true); $this->_lastResponseData = $jsonResponse; return [ 'statusCode' => $responseStatusCode, 'statusCodeClass' => $responseStatusCodeClass, 'data' => $jsonResponse, ]; }
php
protected function _doRestCall($url, array $data = []) { // Connect using cURL $ch = curl_init(); // Set the HTTP request type curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); // Set URL to connect to curl_setopt($ch, CURLOPT_URL, $url); // We want the response returned to us. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Maximum number of seconds allowed to set up the connection. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::CONNECTTIMEOUT); // Maximum number of seconds allowed to receive the response. curl_setopt($ch, CURLOPT_TIMEOUT, self::TIMEOUT); // The Postcode.nl API uses HTTP BASIC authentication (https://en.wikipedia.org/wiki/Basic_access_authentication) curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // Use key as 'username' and secret as 'password' curl_setopt($ch, CURLOPT_USERPWD, $this->_appKey .':'. $this->_appSecret); // Identify this client with a User Agent curl_setopt($ch, CURLOPT_USERAGENT, 'PostcodeNl_Api_RestClient/' . self::VERSION .' PHP/'. phpversion()); // Various debug options if ($this->_debugEnabled) { curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_HEADER, true); } // Do the request $response = curl_exec($ch); // Remember the HTTP status code we receive $responseStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $responseStatusCodeClass = floor($responseStatusCode/100)*100; // Any errors? Remember them now. $curlError = curl_error($ch); $curlErrorNr = curl_errno($ch); if ($this->_debugEnabled) { $this->_debugData['request'] = curl_getinfo($ch, CURLINFO_HEADER_OUT); $this->_debugData['response'] = $response; // Strip off header that was added for debug purposes. $response = substr($response, strpos($response, "\r\n\r\n") + 4); } // And close the cURL handle curl_close($ch); if ($curlError) { // We could not connect, cURL has the reason. (we hope) throw new PostcodeNl_Api_RestClient_ClientException('Connection error `'. $curlErrorNr .'`: `'. $curlError .'`', $curlErrorNr); } // Parse the response as JSON, will be null if not parsable JSON. $jsonResponse = json_decode($response, true); $this->_lastResponseData = $jsonResponse; return [ 'statusCode' => $responseStatusCode, 'statusCodeClass' => $responseStatusCodeClass, 'data' => $jsonResponse, ]; }
[ "protected", "function", "_doRestCall", "(", "$", "url", ",", "array", "$", "data", "=", "[", "]", ")", "{", "// Connect using cURL", "$", "ch", "=", "curl_init", "(", ")", ";", "// Set the HTTP request type", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CUSTOMREQUEST", ",", "'GET'", ")", ";", "// Set URL to connect to", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_URL", ",", "$", "url", ")", ";", "// We want the response returned to us.", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_RETURNTRANSFER", ",", "true", ")", ";", "// Maximum number of seconds allowed to set up the connection.", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_CONNECTTIMEOUT", ",", "self", "::", "CONNECTTIMEOUT", ")", ";", "// Maximum number of seconds allowed to receive the response.", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_TIMEOUT", ",", "self", "::", "TIMEOUT", ")", ";", "// The Postcode.nl API uses HTTP BASIC authentication (https://en.wikipedia.org/wiki/Basic_access_authentication)", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HTTPAUTH", ",", "CURLAUTH_BASIC", ")", ";", "// Use key as 'username' and secret as 'password'", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERPWD", ",", "$", "this", "->", "_appKey", ".", "':'", ".", "$", "this", "->", "_appSecret", ")", ";", "// Identify this client with a User Agent", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "'PostcodeNl_Api_RestClient/'", ".", "self", "::", "VERSION", ".", "' PHP/'", ".", "phpversion", "(", ")", ")", ";", "// Various debug options", "if", "(", "$", "this", "->", "_debugEnabled", ")", "{", "curl_setopt", "(", "$", "ch", ",", "CURLINFO_HEADER_OUT", ",", "true", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_HEADER", ",", "true", ")", ";", "}", "// Do the request", "$", "response", "=", "curl_exec", "(", "$", "ch", ")", ";", "// Remember the HTTP status code we receive", "$", "responseStatusCode", "=", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_HTTP_CODE", ")", ";", "$", "responseStatusCodeClass", "=", "floor", "(", "$", "responseStatusCode", "/", "100", ")", "*", "100", ";", "// Any errors? Remember them now.", "$", "curlError", "=", "curl_error", "(", "$", "ch", ")", ";", "$", "curlErrorNr", "=", "curl_errno", "(", "$", "ch", ")", ";", "if", "(", "$", "this", "->", "_debugEnabled", ")", "{", "$", "this", "->", "_debugData", "[", "'request'", "]", "=", "curl_getinfo", "(", "$", "ch", ",", "CURLINFO_HEADER_OUT", ")", ";", "$", "this", "->", "_debugData", "[", "'response'", "]", "=", "$", "response", ";", "// Strip off header that was added for debug purposes.", "$", "response", "=", "substr", "(", "$", "response", ",", "strpos", "(", "$", "response", ",", "\"\\r\\n\\r\\n\"", ")", "+", "4", ")", ";", "}", "// And close the cURL handle", "curl_close", "(", "$", "ch", ")", ";", "if", "(", "$", "curlError", ")", "{", "// We could not connect, cURL has the reason. (we hope)", "throw", "new", "PostcodeNl_Api_RestClient_ClientException", "(", "'Connection error `'", ".", "$", "curlErrorNr", ".", "'`: `'", ".", "$", "curlError", ".", "'`'", ",", "$", "curlErrorNr", ")", ";", "}", "// Parse the response as JSON, will be null if not parsable JSON.", "$", "jsonResponse", "=", "json_decode", "(", "$", "response", ",", "true", ")", ";", "$", "this", "->", "_lastResponseData", "=", "$", "jsonResponse", ";", "return", "[", "'statusCode'", "=>", "$", "responseStatusCode", ",", "'statusCodeClass'", "=>", "$", "responseStatusCodeClass", ",", "'data'", "=>", "$", "jsonResponse", ",", "]", ";", "}" ]
Perform a REST call to the Postcode.nl API @param string $url @param array $data @return array @throws PostcodeNl_Api_RestClient_ClientException
[ "Perform", "a", "REST", "call", "to", "the", "Postcode", ".", "nl", "API" ]
8eb69b44bfd2c4665f8d6a9dcd41c4fae874150b
https://github.com/postcode-nl/PostcodeNl_Api_RestClient/blob/8eb69b44bfd2c4665f8d6a9dcd41c4fae874150b/library/PostcodeNl/Api/RestClient.php#L162-L228
train
postcode-nl/PostcodeNl_Api_RestClient
library/PostcodeNl/Api/RestClient.php
PostcodeNl_Api_RestClient._checkResponse
protected function _checkResponse(array $response) { // Data present and status code class is 200-299: all is ok if (is_array($response['data']) && $response['statusCodeClass'] == 200) return; // No valid exception message was returned in the JSON (or no JSON at all) // Make our own messages based on the HTTP status code if (!is_array($response['data']) || !isset($response['data']['exceptionId'])) { if ($response['statusCode'] == 503) { throw new PostcodeNl_Api_RestClient_ServiceException('Postcode.nl API returned no valid JSON data. HTTP status code `'. $response['statusCode'] .'`: Service Unavailable. You might be rate-limited if you are sending too many requests.'); } throw new PostcodeNl_Api_RestClient_ServiceException('Postcode.nl API returned no valid JSON data. HTTP status code `'. $response['statusCode'] .'`.'); } // Some specific exceptionIds we clarify within the context of our client. if ($response['statusCode'] == 401) { if ($response['data']['exceptionId'] === 'PostcodeNl_Controller_Plugin_HttpBasicAuthentication_PasswordNotCorrectException') throw new PostcodeNl_Api_RestClient_AuthenticationException('`Secret` specified in HTTP authentication password is incorrect. ("'. $response['data']['exception'] .'")', $response['data']['exceptionId']); if ($response['data']['exceptionId'] === 'PostcodeNl_Controller_Plugin_HttpBasicAuthentication_NotAuthorizedException') throw new PostcodeNl_Api_RestClient_AuthenticationException('`Key` specified in HTTP authentication is incorrect. ("'. $response['data']['exception'] .'")', $response['data']['exceptionId']); } // Specific exception for the Address API when input is correct, but no address is found if ($response['statusCode'] == 404) { if ($response['data']['exceptionId'] === 'PostcodeNl_Service_PostcodeAddress_AddressNotFoundException') throw new PostcodeNl_Api_RestClient_AddressNotFoundException($response['data']['exception'], $response['data']['exceptionId']); } // Our exception types are based on the HTTP status of the response if ($response['statusCode'] == 401 || $response['statusCode'] == 403) { throw new PostcodeNl_Api_RestClient_AuthenticationException($response['data']['exception'], $response['data']['exceptionId']); } else if ($response['statusCodeClass'] == 400) { throw new PostcodeNl_Api_RestClient_InputInvalidException($response['data']['exception'], $response['data']['exceptionId']); } throw new PostcodeNl_Api_RestClient_ServiceException($response['data']['exception'], $response['data']['exceptionId']); }
php
protected function _checkResponse(array $response) { // Data present and status code class is 200-299: all is ok if (is_array($response['data']) && $response['statusCodeClass'] == 200) return; // No valid exception message was returned in the JSON (or no JSON at all) // Make our own messages based on the HTTP status code if (!is_array($response['data']) || !isset($response['data']['exceptionId'])) { if ($response['statusCode'] == 503) { throw new PostcodeNl_Api_RestClient_ServiceException('Postcode.nl API returned no valid JSON data. HTTP status code `'. $response['statusCode'] .'`: Service Unavailable. You might be rate-limited if you are sending too many requests.'); } throw new PostcodeNl_Api_RestClient_ServiceException('Postcode.nl API returned no valid JSON data. HTTP status code `'. $response['statusCode'] .'`.'); } // Some specific exceptionIds we clarify within the context of our client. if ($response['statusCode'] == 401) { if ($response['data']['exceptionId'] === 'PostcodeNl_Controller_Plugin_HttpBasicAuthentication_PasswordNotCorrectException') throw new PostcodeNl_Api_RestClient_AuthenticationException('`Secret` specified in HTTP authentication password is incorrect. ("'. $response['data']['exception'] .'")', $response['data']['exceptionId']); if ($response['data']['exceptionId'] === 'PostcodeNl_Controller_Plugin_HttpBasicAuthentication_NotAuthorizedException') throw new PostcodeNl_Api_RestClient_AuthenticationException('`Key` specified in HTTP authentication is incorrect. ("'. $response['data']['exception'] .'")', $response['data']['exceptionId']); } // Specific exception for the Address API when input is correct, but no address is found if ($response['statusCode'] == 404) { if ($response['data']['exceptionId'] === 'PostcodeNl_Service_PostcodeAddress_AddressNotFoundException') throw new PostcodeNl_Api_RestClient_AddressNotFoundException($response['data']['exception'], $response['data']['exceptionId']); } // Our exception types are based on the HTTP status of the response if ($response['statusCode'] == 401 || $response['statusCode'] == 403) { throw new PostcodeNl_Api_RestClient_AuthenticationException($response['data']['exception'], $response['data']['exceptionId']); } else if ($response['statusCodeClass'] == 400) { throw new PostcodeNl_Api_RestClient_InputInvalidException($response['data']['exception'], $response['data']['exceptionId']); } throw new PostcodeNl_Api_RestClient_ServiceException($response['data']['exception'], $response['data']['exceptionId']); }
[ "protected", "function", "_checkResponse", "(", "array", "$", "response", ")", "{", "// Data present and status code class is 200-299: all is ok", "if", "(", "is_array", "(", "$", "response", "[", "'data'", "]", ")", "&&", "$", "response", "[", "'statusCodeClass'", "]", "==", "200", ")", "return", ";", "// No valid exception message was returned in the JSON (or no JSON at all)", "// Make our own messages based on the HTTP status code", "if", "(", "!", "is_array", "(", "$", "response", "[", "'data'", "]", ")", "||", "!", "isset", "(", "$", "response", "[", "'data'", "]", "[", "'exceptionId'", "]", ")", ")", "{", "if", "(", "$", "response", "[", "'statusCode'", "]", "==", "503", ")", "{", "throw", "new", "PostcodeNl_Api_RestClient_ServiceException", "(", "'Postcode.nl API returned no valid JSON data. HTTP status code `'", ".", "$", "response", "[", "'statusCode'", "]", ".", "'`: Service Unavailable. You might be rate-limited if you are sending too many requests.'", ")", ";", "}", "throw", "new", "PostcodeNl_Api_RestClient_ServiceException", "(", "'Postcode.nl API returned no valid JSON data. HTTP status code `'", ".", "$", "response", "[", "'statusCode'", "]", ".", "'`.'", ")", ";", "}", "// Some specific exceptionIds we clarify within the context of our client.", "if", "(", "$", "response", "[", "'statusCode'", "]", "==", "401", ")", "{", "if", "(", "$", "response", "[", "'data'", "]", "[", "'exceptionId'", "]", "===", "'PostcodeNl_Controller_Plugin_HttpBasicAuthentication_PasswordNotCorrectException'", ")", "throw", "new", "PostcodeNl_Api_RestClient_AuthenticationException", "(", "'`Secret` specified in HTTP authentication password is incorrect. (\"'", ".", "$", "response", "[", "'data'", "]", "[", "'exception'", "]", ".", "'\")'", ",", "$", "response", "[", "'data'", "]", "[", "'exceptionId'", "]", ")", ";", "if", "(", "$", "response", "[", "'data'", "]", "[", "'exceptionId'", "]", "===", "'PostcodeNl_Controller_Plugin_HttpBasicAuthentication_NotAuthorizedException'", ")", "throw", "new", "PostcodeNl_Api_RestClient_AuthenticationException", "(", "'`Key` specified in HTTP authentication is incorrect. (\"'", ".", "$", "response", "[", "'data'", "]", "[", "'exception'", "]", ".", "'\")'", ",", "$", "response", "[", "'data'", "]", "[", "'exceptionId'", "]", ")", ";", "}", "// Specific exception for the Address API when input is correct, but no address is found", "if", "(", "$", "response", "[", "'statusCode'", "]", "==", "404", ")", "{", "if", "(", "$", "response", "[", "'data'", "]", "[", "'exceptionId'", "]", "===", "'PostcodeNl_Service_PostcodeAddress_AddressNotFoundException'", ")", "throw", "new", "PostcodeNl_Api_RestClient_AddressNotFoundException", "(", "$", "response", "[", "'data'", "]", "[", "'exception'", "]", ",", "$", "response", "[", "'data'", "]", "[", "'exceptionId'", "]", ")", ";", "}", "// Our exception types are based on the HTTP status of the response", "if", "(", "$", "response", "[", "'statusCode'", "]", "==", "401", "||", "$", "response", "[", "'statusCode'", "]", "==", "403", ")", "{", "throw", "new", "PostcodeNl_Api_RestClient_AuthenticationException", "(", "$", "response", "[", "'data'", "]", "[", "'exception'", "]", ",", "$", "response", "[", "'data'", "]", "[", "'exceptionId'", "]", ")", ";", "}", "else", "if", "(", "$", "response", "[", "'statusCodeClass'", "]", "==", "400", ")", "{", "throw", "new", "PostcodeNl_Api_RestClient_InputInvalidException", "(", "$", "response", "[", "'data'", "]", "[", "'exception'", "]", ",", "$", "response", "[", "'data'", "]", "[", "'exceptionId'", "]", ")", ";", "}", "throw", "new", "PostcodeNl_Api_RestClient_ServiceException", "(", "$", "response", "[", "'data'", "]", "[", "'exception'", "]", ",", "$", "response", "[", "'data'", "]", "[", "'exceptionId'", "]", ")", ";", "}" ]
Check the JSON response of the Address API result data. Will throw an exception if there is an exception or other not expected response. @param array $response Response data @throws PostcodeNl_Api_RestClient_AddressNotFoundException @throws PostcodeNl_Api_RestClient_AuthenticationException @throws PostcodeNl_Api_RestClient_InputInvalidException @throws PostcodeNl_Api_RestClient_ServiceException
[ "Check", "the", "JSON", "response", "of", "the", "Address", "API", "result", "data", ".", "Will", "throw", "an", "exception", "if", "there", "is", "an", "exception", "or", "other", "not", "expected", "response", "." ]
8eb69b44bfd2c4665f8d6a9dcd41c4fae874150b
https://github.com/postcode-nl/PostcodeNl_Api_RestClient/blob/8eb69b44bfd2c4665f8d6a9dcd41c4fae874150b/library/PostcodeNl/Api/RestClient.php#L241-L286
train
postcode-nl/PostcodeNl_Api_RestClient
library/PostcodeNl/Api/RestClient.php
PostcodeNl_Api_RestClient.lookupAddress
public function lookupAddress($postcode, $houseNumber, $houseNumberAddition = '', $validateHouseNumberAddition = false) { // Remove spaces in postcode ('1234 AB' should be '1234AB') $postcode = str_replace(' ', '', trim($postcode)); $houseNumber = trim($houseNumber); $houseNumberAddition = trim($houseNumberAddition); if ($houseNumberAddition == '') { // If people put the housenumber addition in the housenumber field - split this. list($houseNumber, $houseNumberAddition) = $this->splitHouseNumber($houseNumber); } // Test postcode format if (!$this->isValidPostcodeFormat($postcode)) throw new PostcodeNl_Api_RestClient_InputInvalidException('Postcode `'. $postcode .'` needs to be in the 1234AB format.'); // Test housenumber format if (!ctype_digit($houseNumber)) throw new PostcodeNl_Api_RestClient_InputInvalidException('House number `'. $houseNumber .'` must contain digits only.'); // Use the regular validation function $url = $this->_restApiUrl .'/addresses/postcode/' . rawurlencode($postcode). '/'. rawurlencode($houseNumber) . '/'. rawurlencode($houseNumberAddition); $response = $this->_doRestCall($url); $this->_checkResponse($response); // Strictly enforce housenumber addition validity if ($validateHouseNumberAddition) { if ($response['data']['houseNumberAddition'] === null) throw new PostcodeNl_Api_RestClient_InputInvalidException('Housenumber addition `'. $houseNumberAddition .'` is not known for this address, valid additions are: `'. implode('`, `', $response['data']['houseNumberAdditions']) .'`.'); } // Successful response! return $response['data']; }
php
public function lookupAddress($postcode, $houseNumber, $houseNumberAddition = '', $validateHouseNumberAddition = false) { // Remove spaces in postcode ('1234 AB' should be '1234AB') $postcode = str_replace(' ', '', trim($postcode)); $houseNumber = trim($houseNumber); $houseNumberAddition = trim($houseNumberAddition); if ($houseNumberAddition == '') { // If people put the housenumber addition in the housenumber field - split this. list($houseNumber, $houseNumberAddition) = $this->splitHouseNumber($houseNumber); } // Test postcode format if (!$this->isValidPostcodeFormat($postcode)) throw new PostcodeNl_Api_RestClient_InputInvalidException('Postcode `'. $postcode .'` needs to be in the 1234AB format.'); // Test housenumber format if (!ctype_digit($houseNumber)) throw new PostcodeNl_Api_RestClient_InputInvalidException('House number `'. $houseNumber .'` must contain digits only.'); // Use the regular validation function $url = $this->_restApiUrl .'/addresses/postcode/' . rawurlencode($postcode). '/'. rawurlencode($houseNumber) . '/'. rawurlencode($houseNumberAddition); $response = $this->_doRestCall($url); $this->_checkResponse($response); // Strictly enforce housenumber addition validity if ($validateHouseNumberAddition) { if ($response['data']['houseNumberAddition'] === null) throw new PostcodeNl_Api_RestClient_InputInvalidException('Housenumber addition `'. $houseNumberAddition .'` is not known for this address, valid additions are: `'. implode('`, `', $response['data']['houseNumberAdditions']) .'`.'); } // Successful response! return $response['data']; }
[ "public", "function", "lookupAddress", "(", "$", "postcode", ",", "$", "houseNumber", ",", "$", "houseNumberAddition", "=", "''", ",", "$", "validateHouseNumberAddition", "=", "false", ")", "{", "// Remove spaces in postcode ('1234 AB' should be '1234AB')", "$", "postcode", "=", "str_replace", "(", "' '", ",", "''", ",", "trim", "(", "$", "postcode", ")", ")", ";", "$", "houseNumber", "=", "trim", "(", "$", "houseNumber", ")", ";", "$", "houseNumberAddition", "=", "trim", "(", "$", "houseNumberAddition", ")", ";", "if", "(", "$", "houseNumberAddition", "==", "''", ")", "{", "// If people put the housenumber addition in the housenumber field - split this.", "list", "(", "$", "houseNumber", ",", "$", "houseNumberAddition", ")", "=", "$", "this", "->", "splitHouseNumber", "(", "$", "houseNumber", ")", ";", "}", "// Test postcode format", "if", "(", "!", "$", "this", "->", "isValidPostcodeFormat", "(", "$", "postcode", ")", ")", "throw", "new", "PostcodeNl_Api_RestClient_InputInvalidException", "(", "'Postcode `'", ".", "$", "postcode", ".", "'` needs to be in the 1234AB format.'", ")", ";", "// Test housenumber format", "if", "(", "!", "ctype_digit", "(", "$", "houseNumber", ")", ")", "throw", "new", "PostcodeNl_Api_RestClient_InputInvalidException", "(", "'House number `'", ".", "$", "houseNumber", ".", "'` must contain digits only.'", ")", ";", "// Use the regular validation function", "$", "url", "=", "$", "this", "->", "_restApiUrl", ".", "'/addresses/postcode/'", ".", "rawurlencode", "(", "$", "postcode", ")", ".", "'/'", ".", "rawurlencode", "(", "$", "houseNumber", ")", ".", "'/'", ".", "rawurlencode", "(", "$", "houseNumberAddition", ")", ";", "$", "response", "=", "$", "this", "->", "_doRestCall", "(", "$", "url", ")", ";", "$", "this", "->", "_checkResponse", "(", "$", "response", ")", ";", "// Strictly enforce housenumber addition validity", "if", "(", "$", "validateHouseNumberAddition", ")", "{", "if", "(", "$", "response", "[", "'data'", "]", "[", "'houseNumberAddition'", "]", "===", "null", ")", "throw", "new", "PostcodeNl_Api_RestClient_InputInvalidException", "(", "'Housenumber addition `'", ".", "$", "houseNumberAddition", ".", "'` is not known for this address, valid additions are: `'", ".", "implode", "(", "'`, `'", ",", "$", "response", "[", "'data'", "]", "[", "'houseNumberAdditions'", "]", ")", ".", "'`.'", ")", ";", "}", "// Successful response!", "return", "$", "response", "[", "'data'", "]", ";", "}" ]
Look up an address by postcode and house number. @param string $postcode Dutch postcode in the '1234AB' format @param int|string $houseNumber House number (may contain house number addition, will be separated automatically) @param string $houseNumberAddition House number addition @param bool $validateHouseNumberAddition Enable to validate the addition @return array @throws PostcodeNl_Api_RestClient_InputInvalidException @see https://api.postcode.nl/documentation street - (string) Street name in accordance with "BAG (Basisregistraties adressen en gebouwen)". In capital and lowercase letters, including punctuation marks and accents. This field is at most 80 characters in length. Filled with "Postbus" in case it is a range of PO boxes. streetNen - (string) Street name in NEN-5825 notation, which has a lower maximum length. In capital and lowercase letters, including punctuation marks and accents. This field is at most 24 characters in length. Filled with "Postbus" in case it is a range of PO boxes. houseNumber - (int) House number of a 'perceel'. In case of a Postbus match the house number will always be 0. Range: 0-99999 houseNumberAddition - (string|null) Addition of the house number to uniquely define a location. These additions are officially recognized by the municipality. Null if addition not found (see houseNumberAdditions result field). postcode - (string) Four number neighborhood code (first part of a postcode). Range: 1000-9999 plus two character letter combination (second part of a postcode). Range: "AA"-"ZZ" city - (string) Official city name in accordance with "BAG (Basisregistraties adressen en gebouwen)". In capital and lowercase letters, including punctuation marks and accents. This field is at most 80 characters in length. cityShort - (string) City name, shortened to fit a lower maximum length. In capital and lowercase letters, including punctuation marks and accents. This field is at most 24 characters in length. municipality - (string) Municipality name in accordance with "BAG (Basisregistraties adressen en gebouwen)". In capital and lowercase letters, including punctuation marks and accents. This field is at most 80 characters in length. Examples: "Baarle-Nassau", "'s-Gravenhage", "Haarlemmerliede en Spaarnwoude". municipalityShort - (string) Municipality name, shortened to fit a lower maximum length. In capital and lowercase letters, including punctuation marks and accents. This field is at most 24 characters in length. Examples: "Baarle-Nassau", "'s-Gravenhage", "Haarlemmerliede c.a.". province - (string) Official name of the province, correctly cased and with dashes where applicable. rdX - (int) X coordinate according to Dutch Rijksdriehoeksmeting "(EPSG) 28992 Amersfoort / RD New". Values range from 0 to 300000 meters. Null for PO Boxes. rdY - (int) Y coordinate according to Dutch Rijksdriehoeksmeting "(EPSG) 28992 Amersfoort / RD New". Values range from 300000 to 620000 meters. Null for PO Boxes. latitude - (float) Latitude of address. Null for PO Boxes. longitude - (float) Longitude of address. Null for PO Boxes. bagNumberDesignationId - (string) Dutch term used in BAG: "nummeraanduiding id". bagAddressableObjectId - (string) Dutch term used in BAG: "adresseerbaar object id". Unique identification for objects which have 'building', 'house boat site', or 'mobile home site' as addressType. addressType - (string) Type of address, see reference link purposes - (array) Array of strings, each indicating an official Dutch 'usage' category, see reference link surfaceArea - (int) Surface area of object in square meters (all floors). Null for PO Boxes. houseNumberAdditions - (array) List of all house number additions having the postcode and houseNumber which was input.
[ "Look", "up", "an", "address", "by", "postcode", "and", "house", "number", "." ]
8eb69b44bfd2c4665f8d6a9dcd41c4fae874150b
https://github.com/postcode-nl/PostcodeNl_Api_RestClient/blob/8eb69b44bfd2c4665f8d6a9dcd41c4fae874150b/library/PostcodeNl/Api/RestClient.php#L321-L357
train
postcode-nl/PostcodeNl_Api_RestClient
library/PostcodeNl/Api/RestClient.php
PostcodeNl_Api_RestClient.splitHouseNumber
public function splitHouseNumber($houseNumber) { $houseNumberAddition = ''; if (preg_match('~^(?<number>[0-9]+)(?:[^0-9a-zA-Z]+(?<addition1>[0-9a-zA-Z ]+)|(?<addition2>[a-zA-Z](?:[0-9a-zA-Z ]*)))?$~', $houseNumber, $match)) { $houseNumber = $match['number']; $houseNumberAddition = isset($match['addition2']) ? $match['addition2'] : (isset($match['addition1']) ? $match['addition1'] : ''); } return [$houseNumber, $houseNumberAddition]; }
php
public function splitHouseNumber($houseNumber) { $houseNumberAddition = ''; if (preg_match('~^(?<number>[0-9]+)(?:[^0-9a-zA-Z]+(?<addition1>[0-9a-zA-Z ]+)|(?<addition2>[a-zA-Z](?:[0-9a-zA-Z ]*)))?$~', $houseNumber, $match)) { $houseNumber = $match['number']; $houseNumberAddition = isset($match['addition2']) ? $match['addition2'] : (isset($match['addition1']) ? $match['addition1'] : ''); } return [$houseNumber, $houseNumberAddition]; }
[ "public", "function", "splitHouseNumber", "(", "$", "houseNumber", ")", "{", "$", "houseNumberAddition", "=", "''", ";", "if", "(", "preg_match", "(", "'~^(?<number>[0-9]+)(?:[^0-9a-zA-Z]+(?<addition1>[0-9a-zA-Z ]+)|(?<addition2>[a-zA-Z](?:[0-9a-zA-Z ]*)))?$~'", ",", "$", "houseNumber", ",", "$", "match", ")", ")", "{", "$", "houseNumber", "=", "$", "match", "[", "'number'", "]", ";", "$", "houseNumberAddition", "=", "isset", "(", "$", "match", "[", "'addition2'", "]", ")", "?", "$", "match", "[", "'addition2'", "]", ":", "(", "isset", "(", "$", "match", "[", "'addition1'", "]", ")", "?", "$", "match", "[", "'addition1'", "]", ":", "''", ")", ";", "}", "return", "[", "$", "houseNumber", ",", "$", "houseNumberAddition", "]", ";", "}" ]
Split a housenumber addition from a housenumber. Examples: "123 2", "123 rood", "123a", "123a4", "123-a", "123 II" (the official notation is to separate the housenumber and addition with a single space) @param string $houseNumber @return array Array with houseNumber and houseNumberAddition values
[ "Split", "a", "housenumber", "addition", "from", "a", "housenumber", "." ]
8eb69b44bfd2c4665f8d6a9dcd41c4fae874150b
https://github.com/postcode-nl/PostcodeNl_Api_RestClient/blob/8eb69b44bfd2c4665f8d6a9dcd41c4fae874150b/library/PostcodeNl/Api/RestClient.php#L381-L391
train
Nodge/yii-eauth
EOAuth2Service.php
EOAuth2Service.getTokenUrl
protected function getTokenUrl($code) { return $this->providerOptions['access_token'] . '?client_id=' . $this->client_id . '&client_secret=' . $this->client_secret . '&code=' . $code . '&redirect_uri=' . urlencode($this->getState('redirect_uri')); }
php
protected function getTokenUrl($code) { return $this->providerOptions['access_token'] . '?client_id=' . $this->client_id . '&client_secret=' . $this->client_secret . '&code=' . $code . '&redirect_uri=' . urlencode($this->getState('redirect_uri')); }
[ "protected", "function", "getTokenUrl", "(", "$", "code", ")", "{", "return", "$", "this", "->", "providerOptions", "[", "'access_token'", "]", ".", "'?client_id='", ".", "$", "this", "->", "client_id", ".", "'&client_secret='", ".", "$", "this", "->", "client_secret", ".", "'&code='", ".", "$", "code", ".", "'&redirect_uri='", ".", "urlencode", "(", "$", "this", "->", "getState", "(", "'redirect_uri'", ")", ")", ";", "}" ]
Returns the url to request to get OAuth2 access token. @param string $code @return string url to request.
[ "Returns", "the", "url", "to", "request", "to", "get", "OAuth2", "access", "token", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EOAuth2Service.php#L137-L139
train
Nodge/yii-eauth
EOAuth2Service.php
EOAuth2Service.restoreAccessToken
protected function restoreAccessToken() { if (!$this->authenticated) { if ($this->hasState('auth_token') && $this->getState('expires', 0) > time()) { $this->access_token = $this->getState('auth_token'); $this->authenticated = true; } else { $this->access_token = null; $this->authenticated = false; } } return $this->authenticated; }
php
protected function restoreAccessToken() { if (!$this->authenticated) { if ($this->hasState('auth_token') && $this->getState('expires', 0) > time()) { $this->access_token = $this->getState('auth_token'); $this->authenticated = true; } else { $this->access_token = null; $this->authenticated = false; } } return $this->authenticated; }
[ "protected", "function", "restoreAccessToken", "(", ")", "{", "if", "(", "!", "$", "this", "->", "authenticated", ")", "{", "if", "(", "$", "this", "->", "hasState", "(", "'auth_token'", ")", "&&", "$", "this", "->", "getState", "(", "'expires'", ",", "0", ")", ">", "time", "(", ")", ")", "{", "$", "this", "->", "access_token", "=", "$", "this", "->", "getState", "(", "'auth_token'", ")", ";", "$", "this", "->", "authenticated", "=", "true", ";", "}", "else", "{", "$", "this", "->", "access_token", "=", "null", ";", "$", "this", "->", "authenticated", "=", "false", ";", "}", "}", "return", "$", "this", "->", "authenticated", ";", "}" ]
Restore access token from the session. @return boolean whether the access token was successfuly restored.
[ "Restore", "access", "token", "from", "the", "session", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EOAuth2Service.php#L166-L179
train
Nodge/yii-eauth
services/GitHubOAuthService.php
GitHubOAuthService.initRequest
protected function initRequest($url, $options = array()) { $ch = parent::initRequest($url, $options); curl_setopt($ch, CURLOPT_USERAGENT, 'yii-eauth extension'); return $ch; }
php
protected function initRequest($url, $options = array()) { $ch = parent::initRequest($url, $options); curl_setopt($ch, CURLOPT_USERAGENT, 'yii-eauth extension'); return $ch; }
[ "protected", "function", "initRequest", "(", "$", "url", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "ch", "=", "parent", "::", "initRequest", "(", "$", "url", ",", "$", "options", ")", ";", "curl_setopt", "(", "$", "ch", ",", "CURLOPT_USERAGENT", ",", "'yii-eauth extension'", ")", ";", "return", "$", "ch", ";", "}" ]
Add User-Agent header @param string $url @param array $options @return cURL
[ "Add", "User", "-", "Agent", "header" ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/services/GitHubOAuthService.php#L85-L89
train
Nodge/yii-eauth
custom_services/CustomOdnoklassnikiService.php
CustomOdnoklassnikiService.getRealIdAndUrl
protected function getRealIdAndUrl() { $info = $this->makeSignedRequest('http://api.odnoklassniki.ru/fb.do', array( 'query' => array( 'method' => 'users.getInfo', 'uids' => $this->attributes['id'], 'fields' => 'url_profile', 'format' => 'JSON', 'application_key' => $this->client_public, 'client_id' => $this->client_id, ), )); preg_match('/\d+\/{0,1}$/', $info[0]->url_profile, $matches); $this->attributes['id'] = (int)$matches[0]; $this->attributes['url'] = $info[0]->url_profile; }
php
protected function getRealIdAndUrl() { $info = $this->makeSignedRequest('http://api.odnoklassniki.ru/fb.do', array( 'query' => array( 'method' => 'users.getInfo', 'uids' => $this->attributes['id'], 'fields' => 'url_profile', 'format' => 'JSON', 'application_key' => $this->client_public, 'client_id' => $this->client_id, ), )); preg_match('/\d+\/{0,1}$/', $info[0]->url_profile, $matches); $this->attributes['id'] = (int)$matches[0]; $this->attributes['url'] = $info[0]->url_profile; }
[ "protected", "function", "getRealIdAndUrl", "(", ")", "{", "$", "info", "=", "$", "this", "->", "makeSignedRequest", "(", "'http://api.odnoklassniki.ru/fb.do'", ",", "array", "(", "'query'", "=>", "array", "(", "'method'", "=>", "'users.getInfo'", ",", "'uids'", "=>", "$", "this", "->", "attributes", "[", "'id'", "]", ",", "'fields'", "=>", "'url_profile'", ",", "'format'", "=>", "'JSON'", ",", "'application_key'", "=>", "$", "this", "->", "client_public", ",", "'client_id'", "=>", "$", "this", "->", "client_id", ",", ")", ",", ")", ")", ";", "preg_match", "(", "'/\\d+\\/{0,1}$/'", ",", "$", "info", "[", "0", "]", "->", "url_profile", ",", "$", "matches", ")", ";", "$", "this", "->", "attributes", "[", "'id'", "]", "=", "(", "int", ")", "$", "matches", "[", "0", "]", ";", "$", "this", "->", "attributes", "[", "'url'", "]", "=", "$", "info", "[", "0", "]", "->", "url_profile", ";", "}" ]
Avable only if VALUABLE ACCESS is on you should ask for enable this scope for odnoklassniki administration
[ "Avable", "only", "if", "VALUABLE", "ACCESS", "is", "on", "you", "should", "ask", "for", "enable", "this", "scope", "for", "odnoklassniki", "administration" ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/custom_services/CustomOdnoklassnikiService.php#L38-L53
train
Nodge/yii-eauth
services/EveOnlineOAuthService.php
EveOnlineOAuthService.getAPIData
private function getAPIData($charId) { $url = 'https://api.eveonline.com/eve/CharacterInfo.xml.aspx?characterID='.(int)$charId; $data = file_get_contents($url); $xml = simplexml_load_string($data); return $xml->result; }
php
private function getAPIData($charId) { $url = 'https://api.eveonline.com/eve/CharacterInfo.xml.aspx?characterID='.(int)$charId; $data = file_get_contents($url); $xml = simplexml_load_string($data); return $xml->result; }
[ "private", "function", "getAPIData", "(", "$", "charId", ")", "{", "$", "url", "=", "'https://api.eveonline.com/eve/CharacterInfo.xml.aspx?characterID='", ".", "(", "int", ")", "$", "charId", ";", "$", "data", "=", "file_get_contents", "(", "$", "url", ")", ";", "$", "xml", "=", "simplexml_load_string", "(", "$", "data", ")", ";", "return", "$", "xml", "->", "result", ";", "}" ]
Get data from EVE API @param integer $charId @return SimpleXMLElement
[ "Get", "data", "from", "EVE", "API" ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/services/EveOnlineOAuthService.php#L149-L154
train
Nodge/yii-eauth
EAuthServiceBase.php
EAuthServiceBase.setState
protected function setState($key, $value, $defaultValue = null) { $session = Yii::app()->session; $key = $this->getStateKeyPrefix() . $key; if ($value === $defaultValue) { unset($session[$key]); } else { $session[$key] = $value; } }
php
protected function setState($key, $value, $defaultValue = null) { $session = Yii::app()->session; $key = $this->getStateKeyPrefix() . $key; if ($value === $defaultValue) { unset($session[$key]); } else { $session[$key] = $value; } }
[ "protected", "function", "setState", "(", "$", "key", ",", "$", "value", ",", "$", "defaultValue", "=", "null", ")", "{", "$", "session", "=", "Yii", "::", "app", "(", ")", "->", "session", ";", "$", "key", "=", "$", "this", "->", "getStateKeyPrefix", "(", ")", ".", "$", "key", ";", "if", "(", "$", "value", "===", "$", "defaultValue", ")", "{", "unset", "(", "$", "session", "[", "$", "key", "]", ")", ";", "}", "else", "{", "$", "session", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}" ]
Stores a variable in eauth session. @param string $key variable name. @param mixed $value variable value. @param mixed $defaultValue default value. If $value===$defaultValue, the variable will be removed from the session. @see getState
[ "Stores", "a", "variable", "in", "eauth", "session", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EAuthServiceBase.php#L402-L411
train
Nodge/yii-eauth
EAuthServiceBase.php
EAuthServiceBase.hasState
protected function hasState($key) { $session = Yii::app()->session; $key = $this->getStateKeyPrefix() . $key; return isset($session[$key]); }
php
protected function hasState($key) { $session = Yii::app()->session; $key = $this->getStateKeyPrefix() . $key; return isset($session[$key]); }
[ "protected", "function", "hasState", "(", "$", "key", ")", "{", "$", "session", "=", "Yii", "::", "app", "(", ")", "->", "session", ";", "$", "key", "=", "$", "this", "->", "getStateKeyPrefix", "(", ")", ".", "$", "key", ";", "return", "isset", "(", "$", "session", "[", "$", "key", "]", ")", ";", "}" ]
Returns a value indicating whether there is a state of the specified name. @param string $key state name. @return boolean whether there is a state of the specified name.
[ "Returns", "a", "value", "indicating", "whether", "there", "is", "a", "state", "of", "the", "specified", "name", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EAuthServiceBase.php#L419-L423
train
Nodge/yii-eauth
EAuthServiceBase.php
EAuthServiceBase.getState
protected function getState($key, $defaultValue = null) { $session = Yii::app()->session; $key = $this->getStateKeyPrefix() . $key; return isset($session[$key]) ? $session[$key] : $defaultValue; }
php
protected function getState($key, $defaultValue = null) { $session = Yii::app()->session; $key = $this->getStateKeyPrefix() . $key; return isset($session[$key]) ? $session[$key] : $defaultValue; }
[ "protected", "function", "getState", "(", "$", "key", ",", "$", "defaultValue", "=", "null", ")", "{", "$", "session", "=", "Yii", "::", "app", "(", ")", "->", "session", ";", "$", "key", "=", "$", "this", "->", "getStateKeyPrefix", "(", ")", ".", "$", "key", ";", "return", "isset", "(", "$", "session", "[", "$", "key", "]", ")", "?", "$", "session", "[", "$", "key", "]", ":", "$", "defaultValue", ";", "}" ]
Returns the value of a variable that is stored in eauth session. @param string $key variable name. @param mixed $defaultValue default value. @return mixed the value of the variable. If it doesn't exist in the session, the provided default value will be returned. @see setState
[ "Returns", "the", "value", "of", "a", "variable", "that", "is", "stored", "in", "eauth", "session", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EAuthServiceBase.php#L434-L438
train
Nodge/yii-eauth
EAuthServiceBase.php
EAuthServiceBase.getAttributes
public function getAttributes() { $this->_fetchAttributes(); $attributes = array(); foreach ($this->attributes as $key => $val) { $attributes[$key] = $this->getAttribute($key); } return $attributes; }
php
public function getAttributes() { $this->_fetchAttributes(); $attributes = array(); foreach ($this->attributes as $key => $val) { $attributes[$key] = $this->getAttribute($key); } return $attributes; }
[ "public", "function", "getAttributes", "(", ")", "{", "$", "this", "->", "_fetchAttributes", "(", ")", ";", "$", "attributes", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "attributes", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "attributes", "[", "$", "key", "]", "=", "$", "this", "->", "getAttribute", "(", "$", "key", ")", ";", "}", "return", "$", "attributes", ";", "}" ]
Returns the array that contains all available authorization attributes. @return array the attributes.
[ "Returns", "the", "array", "that", "contains", "all", "available", "authorization", "attributes", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EAuthServiceBase.php#L479-L486
train
Nodge/yii-eauth
EAuthServiceBase.php
EAuthServiceBase.getItem
public function getItem() { $item = new stdClass; $item->title = $this->getAttribute('name'); if (empty($this->title)) { $item->title = $this->getId(); } if ($this->hasAttribute('url')) { $item->url = $this->getAttribute('url'); } return $item; }
php
public function getItem() { $item = new stdClass; $item->title = $this->getAttribute('name'); if (empty($this->title)) { $item->title = $this->getId(); } if ($this->hasAttribute('url')) { $item->url = $this->getAttribute('url'); } return $item; }
[ "public", "function", "getItem", "(", ")", "{", "$", "item", "=", "new", "stdClass", ";", "$", "item", "->", "title", "=", "$", "this", "->", "getAttribute", "(", "'name'", ")", ";", "if", "(", "empty", "(", "$", "this", "->", "title", ")", ")", "{", "$", "item", "->", "title", "=", "$", "this", "->", "getId", "(", ")", ";", "}", "if", "(", "$", "this", "->", "hasAttribute", "(", "'url'", ")", ")", "{", "$", "item", "->", "url", "=", "$", "this", "->", "getAttribute", "(", "'url'", ")", ";", "}", "return", "$", "item", ";", "}" ]
Returns the object with a human-readable representation of the current authorization. @return stdClass the object.
[ "Returns", "the", "object", "with", "a", "human", "-", "readable", "representation", "of", "the", "current", "authorization", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EAuthServiceBase.php#L522-L532
train
Nodge/yii-eauth
services/FacebookOAuthService.php
FacebookOAuthService.saveAccessToken
protected function saveAccessToken($token) { $this->setState('auth_token', $token['access_token']); $this->setState('expires', isset($token['expires_in']) ? time() + (int)$token['expires_in'] - 60 : 0); $this->access_token = $token['access_token']; }
php
protected function saveAccessToken($token) { $this->setState('auth_token', $token['access_token']); $this->setState('expires', isset($token['expires_in']) ? time() + (int)$token['expires_in'] - 60 : 0); $this->access_token = $token['access_token']; }
[ "protected", "function", "saveAccessToken", "(", "$", "token", ")", "{", "$", "this", "->", "setState", "(", "'auth_token'", ",", "$", "token", "[", "'access_token'", "]", ")", ";", "$", "this", "->", "setState", "(", "'expires'", ",", "isset", "(", "$", "token", "[", "'expires_in'", "]", ")", "?", "time", "(", ")", "+", "(", "int", ")", "$", "token", "[", "'expires_in'", "]", "-", "60", ":", "0", ")", ";", "$", "this", "->", "access_token", "=", "$", "token", "[", "'access_token'", "]", ";", "}" ]
Save access token to the session. @param array $token access token array.
[ "Save", "access", "token", "to", "the", "session", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/services/FacebookOAuthService.php#L81-L85
train
Nodge/yii-eauth
EAuth.php
EAuth.init
public function init() { if (!Yii::getPathOfAlias('eauth')) { Yii::setPathOfAlias('eauth', dirname(__FILE__)); } Yii::import('eauth.*'); Yii::import('eauth.services.*'); Yii::import('eauth.custom_services.*'); }
php
public function init() { if (!Yii::getPathOfAlias('eauth')) { Yii::setPathOfAlias('eauth', dirname(__FILE__)); } Yii::import('eauth.*'); Yii::import('eauth.services.*'); Yii::import('eauth.custom_services.*'); }
[ "public", "function", "init", "(", ")", "{", "if", "(", "!", "Yii", "::", "getPathOfAlias", "(", "'eauth'", ")", ")", "{", "Yii", "::", "setPathOfAlias", "(", "'eauth'", ",", "dirname", "(", "__FILE__", ")", ")", ";", "}", "Yii", "::", "import", "(", "'eauth.*'", ")", ";", "Yii", "::", "import", "(", "'eauth.services.*'", ")", ";", "Yii", "::", "import", "(", "'eauth.custom_services.*'", ")", ";", "}" ]
Creates alias eauth and adds some import paths to simplify class files lookup.
[ "Creates", "alias", "eauth", "and", "adds", "some", "import", "paths", "to", "simplify", "class", "files", "lookup", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EAuth.php#L46-L54
train
Nodge/yii-eauth
EAuth.php
EAuth.getService
protected function getService($service) { $service = strtolower($service); $services = $this->getServices(); if (!isset($services[$service])) { throw new EAuthException(Yii::t('eauth', 'Undefined service name: {service}.', array('{service}' => $service)), 500); } return $services[$service]; }
php
protected function getService($service) { $service = strtolower($service); $services = $this->getServices(); if (!isset($services[$service])) { throw new EAuthException(Yii::t('eauth', 'Undefined service name: {service}.', array('{service}' => $service)), 500); } return $services[$service]; }
[ "protected", "function", "getService", "(", "$", "service", ")", "{", "$", "service", "=", "strtolower", "(", "$", "service", ")", ";", "$", "services", "=", "$", "this", "->", "getServices", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "services", "[", "$", "service", "]", ")", ")", "{", "throw", "new", "EAuthException", "(", "Yii", "::", "t", "(", "'eauth'", ",", "'Undefined service name: {service}.'", ",", "array", "(", "'{service}'", "=>", "$", "service", ")", ")", ",", "500", ")", ";", "}", "return", "$", "services", "[", "$", "service", "]", ";", "}" ]
Returns the settings of the service. @param string $service the service name. @return array the service settings.
[ "Returns", "the", "settings", "of", "the", "service", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EAuth.php#L93-L100
train
Nodge/yii-eauth
EAuthWidget.php
EAuthWidget.registerAssets
protected function registerAssets() { $cs = Yii::app()->clientScript; $cs->registerCoreScript('jquery'); $assets_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets'; $url = Yii::app()->assetManager->publish($assets_path, false, -1, Yii::app()->assetManager->linkAssets?false:YII_DEBUG); if ($this->cssFile) $cs->registerCssFile($url . '/css/auth.css'); // Open the authorization dilalog in popup window. if ($this->popup) { $cs->registerScriptFile($url . '/js/auth.js', CClientScript::POS_END); $js = ''; foreach ($this->services as $name => $service) { $args = $service->jsArguments; $args['id'] = $service->id; $js .= '$(".auth-service.' . $service->id . ' a").eauth(' . json_encode($args) . ');' . "\n"; } $cs->registerScript('eauth-services', $js, CClientScript::POS_READY); } }
php
protected function registerAssets() { $cs = Yii::app()->clientScript; $cs->registerCoreScript('jquery'); $assets_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets'; $url = Yii::app()->assetManager->publish($assets_path, false, -1, Yii::app()->assetManager->linkAssets?false:YII_DEBUG); if ($this->cssFile) $cs->registerCssFile($url . '/css/auth.css'); // Open the authorization dilalog in popup window. if ($this->popup) { $cs->registerScriptFile($url . '/js/auth.js', CClientScript::POS_END); $js = ''; foreach ($this->services as $name => $service) { $args = $service->jsArguments; $args['id'] = $service->id; $js .= '$(".auth-service.' . $service->id . ' a").eauth(' . json_encode($args) . ');' . "\n"; } $cs->registerScript('eauth-services', $js, CClientScript::POS_READY); } }
[ "protected", "function", "registerAssets", "(", ")", "{", "$", "cs", "=", "Yii", "::", "app", "(", ")", "->", "clientScript", ";", "$", "cs", "->", "registerCoreScript", "(", "'jquery'", ")", ";", "$", "assets_path", "=", "dirname", "(", "__FILE__", ")", ".", "DIRECTORY_SEPARATOR", ".", "'assets'", ";", "$", "url", "=", "Yii", "::", "app", "(", ")", "->", "assetManager", "->", "publish", "(", "$", "assets_path", ",", "false", ",", "-", "1", ",", "Yii", "::", "app", "(", ")", "->", "assetManager", "->", "linkAssets", "?", "false", ":", "YII_DEBUG", ")", ";", "if", "(", "$", "this", "->", "cssFile", ")", "$", "cs", "->", "registerCssFile", "(", "$", "url", ".", "'/css/auth.css'", ")", ";", "// Open the authorization dilalog in popup window.", "if", "(", "$", "this", "->", "popup", ")", "{", "$", "cs", "->", "registerScriptFile", "(", "$", "url", ".", "'/js/auth.js'", ",", "CClientScript", "::", "POS_END", ")", ";", "$", "js", "=", "''", ";", "foreach", "(", "$", "this", "->", "services", "as", "$", "name", "=>", "$", "service", ")", "{", "$", "args", "=", "$", "service", "->", "jsArguments", ";", "$", "args", "[", "'id'", "]", "=", "$", "service", "->", "id", ";", "$", "js", ".=", "'$(\".auth-service.'", ".", "$", "service", "->", "id", ".", "' a\").eauth('", ".", "json_encode", "(", "$", "args", ")", ".", "');'", ".", "\"\\n\"", ";", "}", "$", "cs", "->", "registerScript", "(", "'eauth-services'", ",", "$", "js", ",", "CClientScript", "::", "POS_READY", ")", ";", "}", "}" ]
Register CSS and JS files.
[ "Register", "CSS", "and", "JS", "files", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EAuthWidget.php#L104-L123
train
Nodge/yii-eauth
EOAuthService.php
EOAuthService.restoreCredentials
protected function restoreCredentials() { if (!$this->authenticated) { if ($this->hasState('auth_consumer') && $this->hasState('auth_token')) { $this->auth->getProvider()->consumer = $this->getState('auth_consumer'); $this->auth->getProvider()->token = $this->getState('auth_token'); $this->authenticated = true; } else { $this->authenticated = false; } } return $this->authenticated; }
php
protected function restoreCredentials() { if (!$this->authenticated) { if ($this->hasState('auth_consumer') && $this->hasState('auth_token')) { $this->auth->getProvider()->consumer = $this->getState('auth_consumer'); $this->auth->getProvider()->token = $this->getState('auth_token'); $this->authenticated = true; } else { $this->authenticated = false; } } return $this->authenticated; }
[ "protected", "function", "restoreCredentials", "(", ")", "{", "if", "(", "!", "$", "this", "->", "authenticated", ")", "{", "if", "(", "$", "this", "->", "hasState", "(", "'auth_consumer'", ")", "&&", "$", "this", "->", "hasState", "(", "'auth_token'", ")", ")", "{", "$", "this", "->", "auth", "->", "getProvider", "(", ")", "->", "consumer", "=", "$", "this", "->", "getState", "(", "'auth_consumer'", ")", ";", "$", "this", "->", "auth", "->", "getProvider", "(", ")", "->", "token", "=", "$", "this", "->", "getState", "(", "'auth_token'", ")", ";", "$", "this", "->", "authenticated", "=", "true", ";", "}", "else", "{", "$", "this", "->", "authenticated", "=", "false", ";", "}", "}", "return", "$", "this", "->", "authenticated", ";", "}" ]
Restore access credentials from the session. @return boolean whether the access credentials were successfully restored.
[ "Restore", "access", "credentials", "from", "the", "session", "." ]
df9be549f8d3699b3a06da30954f363beaa7d738
https://github.com/Nodge/yii-eauth/blob/df9be549f8d3699b3a06da30954f363beaa7d738/EOAuthService.php#L124-L137
train
wa0x6e/Cake-Resque
src/CakeResque.php
CakeResque.enqueue
public static function enqueue($queue, $class, $args = [], $trackStatus = null) { if ($trackStatus === null) { $trackStatus = Configure::read('CakeResque.Job.track'); } if (!is_array($args)) { $args = [$args]; } $r = call_user_func_array(self::$resqueClass . '::enqueue', array_merge([$queue], [$class], [$args], [$trackStatus])); if (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) { $caller = version_compare(PHP_VERSION, '5.4.0') >= 0 ? debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1) : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); } else { $caller = debug_backtrace(); } self::$logs[ $queue ][] = [ 'queue' => $queue, 'class' => $class, 'method' => array_shift($args), 'args' => $args, 'jobId' => $r, 'caller' => $caller, ]; return $r; }
php
public static function enqueue($queue, $class, $args = [], $trackStatus = null) { if ($trackStatus === null) { $trackStatus = Configure::read('CakeResque.Job.track'); } if (!is_array($args)) { $args = [$args]; } $r = call_user_func_array(self::$resqueClass . '::enqueue', array_merge([$queue], [$class], [$args], [$trackStatus])); if (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) { $caller = version_compare(PHP_VERSION, '5.4.0') >= 0 ? debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1) : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); } else { $caller = debug_backtrace(); } self::$logs[ $queue ][] = [ 'queue' => $queue, 'class' => $class, 'method' => array_shift($args), 'args' => $args, 'jobId' => $r, 'caller' => $caller, ]; return $r; }
[ "public", "static", "function", "enqueue", "(", "$", "queue", ",", "$", "class", ",", "$", "args", "=", "[", "]", ",", "$", "trackStatus", "=", "null", ")", "{", "if", "(", "$", "trackStatus", "===", "null", ")", "{", "$", "trackStatus", "=", "Configure", "::", "read", "(", "'CakeResque.Job.track'", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "args", ")", ")", "{", "$", "args", "=", "[", "$", "args", "]", ";", "}", "$", "r", "=", "call_user_func_array", "(", "self", "::", "$", "resqueClass", ".", "'::enqueue'", ",", "array_merge", "(", "[", "$", "queue", "]", ",", "[", "$", "class", "]", ",", "[", "$", "args", "]", ",", "[", "$", "trackStatus", "]", ")", ")", ";", "if", "(", "defined", "(", "'DEBUG_BACKTRACE_IGNORE_ARGS'", ")", ")", "{", "$", "caller", "=", "version_compare", "(", "PHP_VERSION", ",", "'5.4.0'", ")", ">=", "0", "?", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ",", "1", ")", ":", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ")", ";", "}", "else", "{", "$", "caller", "=", "debug_backtrace", "(", ")", ";", "}", "self", "::", "$", "logs", "[", "$", "queue", "]", "[", "]", "=", "[", "'queue'", "=>", "$", "queue", ",", "'class'", "=>", "$", "class", ",", "'method'", "=>", "array_shift", "(", "$", "args", ")", ",", "'args'", "=>", "$", "args", ",", "'jobId'", "=>", "$", "r", ",", "'caller'", "=>", "$", "caller", ",", "]", ";", "return", "$", "r", ";", "}" ]
Enqueue a Job and keep a log for debugging. @param string $queue Name of the queue to enqueue the job to. @param string $class Class of the job. @param array $args Arguments passed to the job. @param boolean $trackStatus Whether to track the status of the job. @return string Job Id.
[ "Enqueue", "a", "Job", "and", "keep", "a", "log", "for", "debugging", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/CakeResque.php#L145-L175
train
wa0x6e/Cake-Resque
src/CakeResque.php
CakeResque.enqueueAt
public static function enqueueAt($at, $queue, $class, $args = [], $trackStatus = null) { if (Configure::read('CakeResque.Scheduler.enabled') !== true) { return false; } if ($trackStatus === null) { $trackStatus = Configure::read('CakeResque.Job.track'); } if (!is_array($args)) { $args = [$args]; } $r = call_user_func_array(self::$resqueSchedulerClass . '::enqueueAt', array_merge([$at], [$queue], [$class], [$args], [$trackStatus])); if (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) { $caller = version_compare(PHP_VERSION, '5.4.0') >= 0 ? debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1) : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); } else { $caller = debug_backtrace(); } self::$logs[ $queue ][] = [ 'queue' => $queue, 'class' => $class, 'method' => array_shift($args), 'args' => $args, 'jobId' => $r, 'caller' => $caller, 'time' => $at instanceof DateTime ? $at->getTimestamp() : $at, ]; return $r; }
php
public static function enqueueAt($at, $queue, $class, $args = [], $trackStatus = null) { if (Configure::read('CakeResque.Scheduler.enabled') !== true) { return false; } if ($trackStatus === null) { $trackStatus = Configure::read('CakeResque.Job.track'); } if (!is_array($args)) { $args = [$args]; } $r = call_user_func_array(self::$resqueSchedulerClass . '::enqueueAt', array_merge([$at], [$queue], [$class], [$args], [$trackStatus])); if (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) { $caller = version_compare(PHP_VERSION, '5.4.0') >= 0 ? debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1) : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); } else { $caller = debug_backtrace(); } self::$logs[ $queue ][] = [ 'queue' => $queue, 'class' => $class, 'method' => array_shift($args), 'args' => $args, 'jobId' => $r, 'caller' => $caller, 'time' => $at instanceof DateTime ? $at->getTimestamp() : $at, ]; return $r; }
[ "public", "static", "function", "enqueueAt", "(", "$", "at", ",", "$", "queue", ",", "$", "class", ",", "$", "args", "=", "[", "]", ",", "$", "trackStatus", "=", "null", ")", "{", "if", "(", "Configure", "::", "read", "(", "'CakeResque.Scheduler.enabled'", ")", "!==", "true", ")", "{", "return", "false", ";", "}", "if", "(", "$", "trackStatus", "===", "null", ")", "{", "$", "trackStatus", "=", "Configure", "::", "read", "(", "'CakeResque.Job.track'", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "args", ")", ")", "{", "$", "args", "=", "[", "$", "args", "]", ";", "}", "$", "r", "=", "call_user_func_array", "(", "self", "::", "$", "resqueSchedulerClass", ".", "'::enqueueAt'", ",", "array_merge", "(", "[", "$", "at", "]", ",", "[", "$", "queue", "]", ",", "[", "$", "class", "]", ",", "[", "$", "args", "]", ",", "[", "$", "trackStatus", "]", ")", ")", ";", "if", "(", "defined", "(", "'DEBUG_BACKTRACE_IGNORE_ARGS'", ")", ")", "{", "$", "caller", "=", "version_compare", "(", "PHP_VERSION", ",", "'5.4.0'", ")", ">=", "0", "?", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ",", "1", ")", ":", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ")", ";", "}", "else", "{", "$", "caller", "=", "debug_backtrace", "(", ")", ";", "}", "self", "::", "$", "logs", "[", "$", "queue", "]", "[", "]", "=", "[", "'queue'", "=>", "$", "queue", ",", "'class'", "=>", "$", "class", ",", "'method'", "=>", "array_shift", "(", "$", "args", ")", ",", "'args'", "=>", "$", "args", ",", "'jobId'", "=>", "$", "r", ",", "'caller'", "=>", "$", "caller", ",", "'time'", "=>", "$", "at", "instanceof", "DateTime", "?", "$", "at", "->", "getTimestamp", "(", ")", ":", "$", "at", ",", "]", ";", "return", "$", "r", ";", "}" ]
Enqueue a Job at a certain time. @param int|DateTime $at Timestamp or DateTime object giving the time when the job should be enqueued. @param string $queue Name of the queue to enqueue the job to. @param string $class Class of the job. @param array $args Arguments passed to the job. @param boolean $trackStatus Whether to track the status of the job. @since 2.3.0 @return string Job Id.
[ "Enqueue", "a", "Job", "at", "a", "certain", "time", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/CakeResque.php#L188-L223
train
wa0x6e/Cake-Resque
src/CakeResque.php
CakeResque.enqueueIn
public static function enqueueIn($in, $queue, $class, $args = [], $trackStatus = null) { if (Configure::read('CakeResque.Scheduler.enabled') !== true) { return false; } if ($trackStatus === null) { $trackStatus = Configure::read('CakeResque.Job.track'); } if (!is_array($args)) { $args = [$args]; } $r = call_user_func_array(self::$resqueSchedulerClass . '::enqueueIn', array_merge([$in], [$queue], [$class], [$args], [$trackStatus])); if (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) { $caller = version_compare(PHP_VERSION, '5.4.0') >= 0 ? debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1) : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); } else { $caller = debug_backtrace(); } self::$logs[ $queue ][] = [ 'queue' => $queue, 'class' => $class, 'method' => array_shift($args), 'args' => $args, 'jobId' => $r, 'caller' => $caller, 'time' => time() + $in, ]; return $r; }
php
public static function enqueueIn($in, $queue, $class, $args = [], $trackStatus = null) { if (Configure::read('CakeResque.Scheduler.enabled') !== true) { return false; } if ($trackStatus === null) { $trackStatus = Configure::read('CakeResque.Job.track'); } if (!is_array($args)) { $args = [$args]; } $r = call_user_func_array(self::$resqueSchedulerClass . '::enqueueIn', array_merge([$in], [$queue], [$class], [$args], [$trackStatus])); if (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) { $caller = version_compare(PHP_VERSION, '5.4.0') >= 0 ? debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1) : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); } else { $caller = debug_backtrace(); } self::$logs[ $queue ][] = [ 'queue' => $queue, 'class' => $class, 'method' => array_shift($args), 'args' => $args, 'jobId' => $r, 'caller' => $caller, 'time' => time() + $in, ]; return $r; }
[ "public", "static", "function", "enqueueIn", "(", "$", "in", ",", "$", "queue", ",", "$", "class", ",", "$", "args", "=", "[", "]", ",", "$", "trackStatus", "=", "null", ")", "{", "if", "(", "Configure", "::", "read", "(", "'CakeResque.Scheduler.enabled'", ")", "!==", "true", ")", "{", "return", "false", ";", "}", "if", "(", "$", "trackStatus", "===", "null", ")", "{", "$", "trackStatus", "=", "Configure", "::", "read", "(", "'CakeResque.Job.track'", ")", ";", "}", "if", "(", "!", "is_array", "(", "$", "args", ")", ")", "{", "$", "args", "=", "[", "$", "args", "]", ";", "}", "$", "r", "=", "call_user_func_array", "(", "self", "::", "$", "resqueSchedulerClass", ".", "'::enqueueIn'", ",", "array_merge", "(", "[", "$", "in", "]", ",", "[", "$", "queue", "]", ",", "[", "$", "class", "]", ",", "[", "$", "args", "]", ",", "[", "$", "trackStatus", "]", ")", ")", ";", "if", "(", "defined", "(", "'DEBUG_BACKTRACE_IGNORE_ARGS'", ")", ")", "{", "$", "caller", "=", "version_compare", "(", "PHP_VERSION", ",", "'5.4.0'", ")", ">=", "0", "?", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ",", "1", ")", ":", "debug_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ")", ";", "}", "else", "{", "$", "caller", "=", "debug_backtrace", "(", ")", ";", "}", "self", "::", "$", "logs", "[", "$", "queue", "]", "[", "]", "=", "[", "'queue'", "=>", "$", "queue", ",", "'class'", "=>", "$", "class", ",", "'method'", "=>", "array_shift", "(", "$", "args", ")", ",", "'args'", "=>", "$", "args", ",", "'jobId'", "=>", "$", "r", ",", "'caller'", "=>", "$", "caller", ",", "'time'", "=>", "time", "(", ")", "+", "$", "in", ",", "]", ";", "return", "$", "r", ";", "}" ]
Enqueue a Job after a certain time. @param int $in Number of second to wait from now before queueing the job. @param string $queue Name of the queue to enqueue the job to. @param string $class Class of the job. @param array $args Arguments passed to the job. @param boolean $trackStatus Whether to track the status of the job. @since 2.3.0 @return string Job Id.
[ "Enqueue", "a", "Job", "after", "a", "certain", "time", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/CakeResque.php#L236-L271
train
wa0x6e/Cake-Resque
src/Resque_Job_Creator.php
Resque_Job_Creator.createJob
public static function createJob($className, $args) { list($plugin, $model) = pluginSplit($className); if (self::$rootFolder === null) { self::$rootFolder = dirname(dirname(dirname(__DIR__))) . DS; } $classpath = self::$rootFolder . (empty($plugin) ? '' : 'Plugin' . DS . $plugin . DS) . 'Shell' . DS . $model . '.php'; if (file_exists($classpath)) { require_once $classpath; } else { throw new Resque_Exception('Could not find job class ' . $className . '.'); } if (!class_exists($model)) { throw new Resque_Exception('Could not find job class ' . $className . '.'); } if (!method_exists($model, 'perform')) { throw new Resque_Exception('Job class ' . $className . ' does not contain a perform method.'); } if (!isset($args[0]) || !method_exists($model, $args[0])) { throw new Resque_Exception('Job class ' . $className . ' does not contain ' . $args[0] . ' method.'); } return new $model(); }
php
public static function createJob($className, $args) { list($plugin, $model) = pluginSplit($className); if (self::$rootFolder === null) { self::$rootFolder = dirname(dirname(dirname(__DIR__))) . DS; } $classpath = self::$rootFolder . (empty($plugin) ? '' : 'Plugin' . DS . $plugin . DS) . 'Shell' . DS . $model . '.php'; if (file_exists($classpath)) { require_once $classpath; } else { throw new Resque_Exception('Could not find job class ' . $className . '.'); } if (!class_exists($model)) { throw new Resque_Exception('Could not find job class ' . $className . '.'); } if (!method_exists($model, 'perform')) { throw new Resque_Exception('Job class ' . $className . ' does not contain a perform method.'); } if (!isset($args[0]) || !method_exists($model, $args[0])) { throw new Resque_Exception('Job class ' . $className . ' does not contain ' . $args[0] . ' method.'); } return new $model(); }
[ "public", "static", "function", "createJob", "(", "$", "className", ",", "$", "args", ")", "{", "list", "(", "$", "plugin", ",", "$", "model", ")", "=", "pluginSplit", "(", "$", "className", ")", ";", "if", "(", "self", "::", "$", "rootFolder", "===", "null", ")", "{", "self", "::", "$", "rootFolder", "=", "dirname", "(", "dirname", "(", "dirname", "(", "__DIR__", ")", ")", ")", ".", "DS", ";", "}", "$", "classpath", "=", "self", "::", "$", "rootFolder", ".", "(", "empty", "(", "$", "plugin", ")", "?", "''", ":", "'Plugin'", ".", "DS", ".", "$", "plugin", ".", "DS", ")", ".", "'Shell'", ".", "DS", ".", "$", "model", ".", "'.php'", ";", "if", "(", "file_exists", "(", "$", "classpath", ")", ")", "{", "require_once", "$", "classpath", ";", "}", "else", "{", "throw", "new", "Resque_Exception", "(", "'Could not find job class '", ".", "$", "className", ".", "'.'", ")", ";", "}", "if", "(", "!", "class_exists", "(", "$", "model", ")", ")", "{", "throw", "new", "Resque_Exception", "(", "'Could not find job class '", ".", "$", "className", ".", "'.'", ")", ";", "}", "if", "(", "!", "method_exists", "(", "$", "model", ",", "'perform'", ")", ")", "{", "throw", "new", "Resque_Exception", "(", "'Job class '", ".", "$", "className", ".", "' does not contain a perform method.'", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "args", "[", "0", "]", ")", "||", "!", "method_exists", "(", "$", "model", ",", "$", "args", "[", "0", "]", ")", ")", "{", "throw", "new", "Resque_Exception", "(", "'Job class '", ".", "$", "className", ".", "' does not contain '", ".", "$", "args", "[", "0", "]", ".", "' method.'", ")", ";", "}", "return", "new", "$", "model", "(", ")", ";", "}" ]
Create and return a job instance @param string $className className of the job to instanciate @param array $args Array of method name and arguments used to build the job @return object $args a job instance @throws Resque_Exception when the class is not found, or does not follow the job file convention
[ "Create", "and", "return", "a", "job", "instance" ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Resque_Job_Creator.php#L41-L70
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.enqueue
public function enqueue() { $this->out('<info>' . __d('cake_resque', 'Adding a job to worker') . '</info>'); if (count($this->args) !== 3) { $this->err('<error>' . __d('cake_resque', 'Wrong number of arguments') . '</error>'); $this->out(__d('cake_resque', 'Usage : enqueue <queue> <jobclass> <comma-separated-args>'), 2); return false; } $result = CakeResque::enqueue($this->args[0], $this->args[1], explode(',', $this->args[2])); $this->out('<success>' . __d('cake_resque', 'Succesfully enqueued Job #{0}', $result) . '</success>'); $this->out(''); }
php
public function enqueue() { $this->out('<info>' . __d('cake_resque', 'Adding a job to worker') . '</info>'); if (count($this->args) !== 3) { $this->err('<error>' . __d('cake_resque', 'Wrong number of arguments') . '</error>'); $this->out(__d('cake_resque', 'Usage : enqueue <queue> <jobclass> <comma-separated-args>'), 2); return false; } $result = CakeResque::enqueue($this->args[0], $this->args[1], explode(',', $this->args[2])); $this->out('<success>' . __d('cake_resque', 'Succesfully enqueued Job #{0}', $result) . '</success>'); $this->out(''); }
[ "public", "function", "enqueue", "(", ")", "{", "$", "this", "->", "out", "(", "'<info>'", ".", "__d", "(", "'cake_resque'", ",", "'Adding a job to worker'", ")", ".", "'</info>'", ")", ";", "if", "(", "count", "(", "$", "this", "->", "args", ")", "!==", "3", ")", "{", "$", "this", "->", "err", "(", "'<error>'", ".", "__d", "(", "'cake_resque'", ",", "'Wrong number of arguments'", ")", ".", "'</error>'", ")", ";", "$", "this", "->", "out", "(", "__d", "(", "'cake_resque'", ",", "'Usage : enqueue <queue> <jobclass> <comma-separated-args>'", ")", ",", "2", ")", ";", "return", "false", ";", "}", "$", "result", "=", "CakeResque", "::", "enqueue", "(", "$", "this", "->", "args", "[", "0", "]", ",", "$", "this", "->", "args", "[", "1", "]", ",", "explode", "(", "','", ",", "$", "this", "->", "args", "[", "2", "]", ")", ")", ";", "$", "this", "->", "out", "(", "'<success>'", ".", "__d", "(", "'cake_resque'", ",", "'Succesfully enqueued Job #{0}'", ",", "$", "result", ")", ".", "'</success>'", ")", ";", "$", "this", "->", "out", "(", "''", ")", ";", "}" ]
Enqueue a job via CLI. @return bool False if enqueueing fails.
[ "Enqueue", "a", "job", "via", "CLI", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L327-L342
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.enqueueIn
public function enqueueIn() { $this->out('<info>' . __d('cake_resque', 'Scheduling a job') . '</info>'); if (count($this->args) !== 4) { $this->err('<error>' . __d('cake_resque', 'Wrong number of arguments') . '</error>'); $this->out(__d('cake_resque', 'Usage : enqueueIn <seconds> <queue> <jobclass> <comma-separated-args>'), 2); return false; } $result = CakeResque::enqueueIn($this->args[0], $this->args[1], $this->args[2], explode(',', $this->args[3]), (isset($this->args[4]) ? (bool)$this->args[4] : false)); $this->out('<success>' . __d('cake_resque', 'Succesfully scheduled Job #{0}', $result) . '</success>'); $this->out(''); }
php
public function enqueueIn() { $this->out('<info>' . __d('cake_resque', 'Scheduling a job') . '</info>'); if (count($this->args) !== 4) { $this->err('<error>' . __d('cake_resque', 'Wrong number of arguments') . '</error>'); $this->out(__d('cake_resque', 'Usage : enqueueIn <seconds> <queue> <jobclass> <comma-separated-args>'), 2); return false; } $result = CakeResque::enqueueIn($this->args[0], $this->args[1], $this->args[2], explode(',', $this->args[3]), (isset($this->args[4]) ? (bool)$this->args[4] : false)); $this->out('<success>' . __d('cake_resque', 'Succesfully scheduled Job #{0}', $result) . '</success>'); $this->out(''); }
[ "public", "function", "enqueueIn", "(", ")", "{", "$", "this", "->", "out", "(", "'<info>'", ".", "__d", "(", "'cake_resque'", ",", "'Scheduling a job'", ")", ".", "'</info>'", ")", ";", "if", "(", "count", "(", "$", "this", "->", "args", ")", "!==", "4", ")", "{", "$", "this", "->", "err", "(", "'<error>'", ".", "__d", "(", "'cake_resque'", ",", "'Wrong number of arguments'", ")", ".", "'</error>'", ")", ";", "$", "this", "->", "out", "(", "__d", "(", "'cake_resque'", ",", "'Usage : enqueueIn <seconds> <queue> <jobclass> <comma-separated-args>'", ")", ",", "2", ")", ";", "return", "false", ";", "}", "$", "result", "=", "CakeResque", "::", "enqueueIn", "(", "$", "this", "->", "args", "[", "0", "]", ",", "$", "this", "->", "args", "[", "1", "]", ",", "$", "this", "->", "args", "[", "2", "]", ",", "explode", "(", "','", ",", "$", "this", "->", "args", "[", "3", "]", ")", ",", "(", "isset", "(", "$", "this", "->", "args", "[", "4", "]", ")", "?", "(", "bool", ")", "$", "this", "->", "args", "[", "4", "]", ":", "false", ")", ")", ";", "$", "this", "->", "out", "(", "'<success>'", ".", "__d", "(", "'cake_resque'", ",", "'Succesfully scheduled Job #{0}'", ",", "$", "result", ")", ".", "'</success>'", ")", ";", "$", "this", "->", "out", "(", "''", ")", ";", "}" ]
Enqueue a scheduled job via CLI. @since 2.3.0 @return bool False if enqueueing fails.
[ "Enqueue", "a", "scheduled", "job", "via", "CLI", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L350-L365
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.tail
public function tail() { $logs = []; $i = 1; $workersArgs = $this->ResqueStatus->getWorkers(); foreach ($workersArgs as $workerArgs) { if ($workerArgs['log'] != '') { $logs[] = $workerArgs['log']; } if ($workerArgs['Log']['handler'] == 'RotatingFile') { $fileInfo = pathinfo($workerArgs['Log']['target']); $pattern = $fileInfo['dirname'] . DS . $fileInfo['filename'] . '-*' . (!empty($fileInfo['extension']) ? '.' . $fileInfo['extension'] : ''); $logs = array_merge($logs, glob($pattern)); } } $logs = array_values(array_unique($logs)); $this->out('<info>' . __d('cake_resque', 'Tailing log file') . '</info>'); if (empty($logs)) { $this->out(' <error>' . __d('cake_resque', 'No log file to tail') . '</error>', 2); return false; } elseif (count($logs) == 1) { $index = 1; } else { foreach ($logs as $log) { $this->out(sprintf(' [%3d] - %s', $i++, $log)); } $index = $this->in(__d('cake_resque', 'Choose a log file to tail') . ':', range(1, $i - 1)); } $this->out('<warning>' . __d('cake_resque', 'Tailing {0}', $logs[ $index - 1 ]) . '</warning>'); $this->_tail($logs[ $index - 1 ]); }
php
public function tail() { $logs = []; $i = 1; $workersArgs = $this->ResqueStatus->getWorkers(); foreach ($workersArgs as $workerArgs) { if ($workerArgs['log'] != '') { $logs[] = $workerArgs['log']; } if ($workerArgs['Log']['handler'] == 'RotatingFile') { $fileInfo = pathinfo($workerArgs['Log']['target']); $pattern = $fileInfo['dirname'] . DS . $fileInfo['filename'] . '-*' . (!empty($fileInfo['extension']) ? '.' . $fileInfo['extension'] : ''); $logs = array_merge($logs, glob($pattern)); } } $logs = array_values(array_unique($logs)); $this->out('<info>' . __d('cake_resque', 'Tailing log file') . '</info>'); if (empty($logs)) { $this->out(' <error>' . __d('cake_resque', 'No log file to tail') . '</error>', 2); return false; } elseif (count($logs) == 1) { $index = 1; } else { foreach ($logs as $log) { $this->out(sprintf(' [%3d] - %s', $i++, $log)); } $index = $this->in(__d('cake_resque', 'Choose a log file to tail') . ':', range(1, $i - 1)); } $this->out('<warning>' . __d('cake_resque', 'Tailing {0}', $logs[ $index - 1 ]) . '</warning>'); $this->_tail($logs[ $index - 1 ]); }
[ "public", "function", "tail", "(", ")", "{", "$", "logs", "=", "[", "]", ";", "$", "i", "=", "1", ";", "$", "workersArgs", "=", "$", "this", "->", "ResqueStatus", "->", "getWorkers", "(", ")", ";", "foreach", "(", "$", "workersArgs", "as", "$", "workerArgs", ")", "{", "if", "(", "$", "workerArgs", "[", "'log'", "]", "!=", "''", ")", "{", "$", "logs", "[", "]", "=", "$", "workerArgs", "[", "'log'", "]", ";", "}", "if", "(", "$", "workerArgs", "[", "'Log'", "]", "[", "'handler'", "]", "==", "'RotatingFile'", ")", "{", "$", "fileInfo", "=", "pathinfo", "(", "$", "workerArgs", "[", "'Log'", "]", "[", "'target'", "]", ")", ";", "$", "pattern", "=", "$", "fileInfo", "[", "'dirname'", "]", ".", "DS", ".", "$", "fileInfo", "[", "'filename'", "]", ".", "'-*'", ".", "(", "!", "empty", "(", "$", "fileInfo", "[", "'extension'", "]", ")", "?", "'.'", ".", "$", "fileInfo", "[", "'extension'", "]", ":", "''", ")", ";", "$", "logs", "=", "array_merge", "(", "$", "logs", ",", "glob", "(", "$", "pattern", ")", ")", ";", "}", "}", "$", "logs", "=", "array_values", "(", "array_unique", "(", "$", "logs", ")", ")", ";", "$", "this", "->", "out", "(", "'<info>'", ".", "__d", "(", "'cake_resque'", ",", "'Tailing log file'", ")", ".", "'</info>'", ")", ";", "if", "(", "empty", "(", "$", "logs", ")", ")", "{", "$", "this", "->", "out", "(", "' <error>'", ".", "__d", "(", "'cake_resque'", ",", "'No log file to tail'", ")", ".", "'</error>'", ",", "2", ")", ";", "return", "false", ";", "}", "elseif", "(", "count", "(", "$", "logs", ")", "==", "1", ")", "{", "$", "index", "=", "1", ";", "}", "else", "{", "foreach", "(", "$", "logs", "as", "$", "log", ")", "{", "$", "this", "->", "out", "(", "sprintf", "(", "' [%3d] - %s'", ",", "$", "i", "++", ",", "$", "log", ")", ")", ";", "}", "$", "index", "=", "$", "this", "->", "in", "(", "__d", "(", "'cake_resque'", ",", "'Choose a log file to tail'", ")", ".", "':'", ",", "range", "(", "1", ",", "$", "i", "-", "1", ")", ")", ";", "}", "$", "this", "->", "out", "(", "'<warning>'", ".", "__d", "(", "'cake_resque'", ",", "'Tailing {0}'", ",", "$", "logs", "[", "$", "index", "-", "1", "]", ")", ".", "'</warning>'", ")", ";", "$", "this", "->", "_tail", "(", "$", "logs", "[", "$", "index", "-", "1", "]", ")", ";", "}" ]
Monitor the content of a log file onscreen. Ask user to choose from a list of available log file, if there's more than one, and display all new content on screen. This will only search for log file created by resque, and the RotatingFile created by log-handler. Note: The workers status is conveniently stored by ResqueStatus. @return bool False if no logs to tail. @see ResqueStatus\ResqueStatus::getWorkers()
[ "Monitor", "the", "content", "of", "a", "log", "file", "onscreen", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L401-L438
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.cleanup
public function cleanup() { $actionMessage = function ($pid) { return __d('cake_resque', 'Cleaning up {0} ... ', $pid); }; $successCallback = function ($worker) { }; return $this->_sendSignal( __d('cake_resque', 'Cleaning up workers'), CakeResque::getWorkers(), __d('cake_resque', 'There is no active workers to clean up ...'), __d('cake_resque', 'Active workers list'), __d('cake_resque', 'Clean up all workers'), __d('cake_resque', 'Worker to Cleanup'), __d('cake_resque', 'Cleaning up the Scheduler Worker ... '), $actionMessage, null, $successCallback, 'USR1' ); }
php
public function cleanup() { $actionMessage = function ($pid) { return __d('cake_resque', 'Cleaning up {0} ... ', $pid); }; $successCallback = function ($worker) { }; return $this->_sendSignal( __d('cake_resque', 'Cleaning up workers'), CakeResque::getWorkers(), __d('cake_resque', 'There is no active workers to clean up ...'), __d('cake_resque', 'Active workers list'), __d('cake_resque', 'Clean up all workers'), __d('cake_resque', 'Worker to Cleanup'), __d('cake_resque', 'Cleaning up the Scheduler Worker ... '), $actionMessage, null, $successCallback, 'USR1' ); }
[ "public", "function", "cleanup", "(", ")", "{", "$", "actionMessage", "=", "function", "(", "$", "pid", ")", "{", "return", "__d", "(", "'cake_resque'", ",", "'Cleaning up {0} ... '", ",", "$", "pid", ")", ";", "}", ";", "$", "successCallback", "=", "function", "(", "$", "worker", ")", "{", "}", ";", "return", "$", "this", "->", "_sendSignal", "(", "__d", "(", "'cake_resque'", ",", "'Cleaning up workers'", ")", ",", "CakeResque", "::", "getWorkers", "(", ")", ",", "__d", "(", "'cake_resque'", ",", "'There is no active workers to clean up ...'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Active workers list'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Clean up all workers'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Worker to Cleanup'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Cleaning up the Scheduler Worker ... '", ")", ",", "$", "actionMessage", ",", "null", ",", "$", "successCallback", ",", "'USR1'", ")", ";", "}" ]
Clean up workers. On supported system, will ask the user to choose the worker to clean up, from a list of workers, if more than one worker is running, or if --all is not passed. Clean up will immediately terminate a worker child. Job is left unfinished. @since 2.0.0 @return void @see CakeResqueShell::_sendSignal()
[ "Clean", "up", "workers", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L478-L500
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.pause
public function pause() { $ResqueStatus = $this->ResqueStatus; $actionMessage = function ($pid) { return __d('cake_resque', 'Pausing {0} ... ', $pid); }; $successCallback = function ($worker) use ($ResqueStatus) { $ResqueStatus->setPausedWorker((string)$worker); }; // Active workers $this->debug(__d('cake_resque', 'Fetching list of active workers')); $activeWorkers = CakeResque::getWorkers(); array_walk($activeWorkers, function (&$worker) { $worker = (string)$worker; }); // Paused workers $pausedWorkers = $ResqueStatus->getPausedWorker(); return $this->_sendSignal( __d('cake_resque', 'Pausing workers'), array_diff($activeWorkers, $pausedWorkers), __d('cake_resque', 'There is no active workers to pause ...'), __d('cake_resque', 'Active workers list'), __d('cake_resque', 'Pause all workers'), __d('cake_resque', 'Worker to pause'), __d('cake_resque', 'Pausing the Scheduler Worker ... '), $actionMessage, null, $successCallback, 'USR2' ); }
php
public function pause() { $ResqueStatus = $this->ResqueStatus; $actionMessage = function ($pid) { return __d('cake_resque', 'Pausing {0} ... ', $pid); }; $successCallback = function ($worker) use ($ResqueStatus) { $ResqueStatus->setPausedWorker((string)$worker); }; // Active workers $this->debug(__d('cake_resque', 'Fetching list of active workers')); $activeWorkers = CakeResque::getWorkers(); array_walk($activeWorkers, function (&$worker) { $worker = (string)$worker; }); // Paused workers $pausedWorkers = $ResqueStatus->getPausedWorker(); return $this->_sendSignal( __d('cake_resque', 'Pausing workers'), array_diff($activeWorkers, $pausedWorkers), __d('cake_resque', 'There is no active workers to pause ...'), __d('cake_resque', 'Active workers list'), __d('cake_resque', 'Pause all workers'), __d('cake_resque', 'Worker to pause'), __d('cake_resque', 'Pausing the Scheduler Worker ... '), $actionMessage, null, $successCallback, 'USR2' ); }
[ "public", "function", "pause", "(", ")", "{", "$", "ResqueStatus", "=", "$", "this", "->", "ResqueStatus", ";", "$", "actionMessage", "=", "function", "(", "$", "pid", ")", "{", "return", "__d", "(", "'cake_resque'", ",", "'Pausing {0} ... '", ",", "$", "pid", ")", ";", "}", ";", "$", "successCallback", "=", "function", "(", "$", "worker", ")", "use", "(", "$", "ResqueStatus", ")", "{", "$", "ResqueStatus", "->", "setPausedWorker", "(", "(", "string", ")", "$", "worker", ")", ";", "}", ";", "// Active workers", "$", "this", "->", "debug", "(", "__d", "(", "'cake_resque'", ",", "'Fetching list of active workers'", ")", ")", ";", "$", "activeWorkers", "=", "CakeResque", "::", "getWorkers", "(", ")", ";", "array_walk", "(", "$", "activeWorkers", ",", "function", "(", "&", "$", "worker", ")", "{", "$", "worker", "=", "(", "string", ")", "$", "worker", ";", "}", ")", ";", "// Paused workers", "$", "pausedWorkers", "=", "$", "ResqueStatus", "->", "getPausedWorker", "(", ")", ";", "return", "$", "this", "->", "_sendSignal", "(", "__d", "(", "'cake_resque'", ",", "'Pausing workers'", ")", ",", "array_diff", "(", "$", "activeWorkers", ",", "$", "pausedWorkers", ")", ",", "__d", "(", "'cake_resque'", ",", "'There is no active workers to pause ...'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Active workers list'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Pause all workers'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Worker to pause'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Pausing the Scheduler Worker ... '", ")", ",", "$", "actionMessage", ",", "null", ",", "$", "successCallback", ",", "'USR2'", ")", ";", "}" ]
Pause workers. On supported system, will ask the user to choose the worker to pause, from a list of workers, if more than one worker is running, or if --all is not passed. Note: The workers status is conveniently stored by ResqueStatus. @since 2.0.0 @return void @see CakeResqueShell::_sendSignal() @see ResqueStatus\ResqueStatus::getPausedWorker() @see ResqueStatus\ResqueStatus::setPausedWorker()
[ "Pause", "workers", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L631-L666
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.resume
public function resume() { $ResqueStatus = $this->ResqueStatus; $actionMessage = function ($pid) { return __d('cake_resque', 'Resuming {0} ... ', $pid); }; $successCallback = function ($worker) use ($ResqueStatus) { $ResqueStatus->setPausedWorker((string)$worker, false); }; return $this->_sendSignal( __d('cake_resque', 'Resuming workers'), $ResqueStatus->getPausedWorker(), __d('cake_resque', 'There is no paused workers to resume ...'), __d('cake_resque', 'Paused workers list'), __d('cake_resque', 'Resume all workers'), __d('cake_resque', 'Worker to resume'), __d('cake_resque', 'Resuming the Scheduler Worker ... '), $actionMessage, null, $successCallback, 'CONT' ); }
php
public function resume() { $ResqueStatus = $this->ResqueStatus; $actionMessage = function ($pid) { return __d('cake_resque', 'Resuming {0} ... ', $pid); }; $successCallback = function ($worker) use ($ResqueStatus) { $ResqueStatus->setPausedWorker((string)$worker, false); }; return $this->_sendSignal( __d('cake_resque', 'Resuming workers'), $ResqueStatus->getPausedWorker(), __d('cake_resque', 'There is no paused workers to resume ...'), __d('cake_resque', 'Paused workers list'), __d('cake_resque', 'Resume all workers'), __d('cake_resque', 'Worker to resume'), __d('cake_resque', 'Resuming the Scheduler Worker ... '), $actionMessage, null, $successCallback, 'CONT' ); }
[ "public", "function", "resume", "(", ")", "{", "$", "ResqueStatus", "=", "$", "this", "->", "ResqueStatus", ";", "$", "actionMessage", "=", "function", "(", "$", "pid", ")", "{", "return", "__d", "(", "'cake_resque'", ",", "'Resuming {0} ... '", ",", "$", "pid", ")", ";", "}", ";", "$", "successCallback", "=", "function", "(", "$", "worker", ")", "use", "(", "$", "ResqueStatus", ")", "{", "$", "ResqueStatus", "->", "setPausedWorker", "(", "(", "string", ")", "$", "worker", ",", "false", ")", ";", "}", ";", "return", "$", "this", "->", "_sendSignal", "(", "__d", "(", "'cake_resque'", ",", "'Resuming workers'", ")", ",", "$", "ResqueStatus", "->", "getPausedWorker", "(", ")", ",", "__d", "(", "'cake_resque'", ",", "'There is no paused workers to resume ...'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Paused workers list'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Resume all workers'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Worker to resume'", ")", ",", "__d", "(", "'cake_resque'", ",", "'Resuming the Scheduler Worker ... '", ")", ",", "$", "actionMessage", ",", "null", ",", "$", "successCallback", ",", "'CONT'", ")", ";", "}" ]
Resume paused workers. On supported system, will ask the user to choose the worker to resume, from a list of workers, if more than one worker is running, or if --all is not passed. Note: The workers status is conveniently stored by ResqueStatus. @since 2.0.0 @return void @see CakeResqueShell::_sendSignal() @see ResqueStatus\ResqueStatus::getPausedWorker() @see ResqueStatus\ResqueStatus::setPausedWorker()
[ "Resume", "paused", "workers", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L695-L720
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.load
public function load() { $this->out('<info>' . __d('cake_resque', 'Loading predefined workers') . '</info>'); $debug = isset($this->params['debug']) ? $this->params['debug'] : false; $queues = Configure::read('CakeResque.Queues'); if ($queues === null) { $this->out(' ' . __d('cake_resque', 'You have no configured workers to load.')); } else { foreach ($queues as $workerArgs) { $workerArgs['debug'] = $debug; $this->start($workerArgs); } } if (Configure::read('CakeResque.Scheduler.enabled') === true) { $this->startscheduler(['debug' => $debug]); } $this->out(''); }
php
public function load() { $this->out('<info>' . __d('cake_resque', 'Loading predefined workers') . '</info>'); $debug = isset($this->params['debug']) ? $this->params['debug'] : false; $queues = Configure::read('CakeResque.Queues'); if ($queues === null) { $this->out(' ' . __d('cake_resque', 'You have no configured workers to load.')); } else { foreach ($queues as $workerArgs) { $workerArgs['debug'] = $debug; $this->start($workerArgs); } } if (Configure::read('CakeResque.Scheduler.enabled') === true) { $this->startscheduler(['debug' => $debug]); } $this->out(''); }
[ "public", "function", "load", "(", ")", "{", "$", "this", "->", "out", "(", "'<info>'", ".", "__d", "(", "'cake_resque'", ",", "'Loading predefined workers'", ")", ".", "'</info>'", ")", ";", "$", "debug", "=", "isset", "(", "$", "this", "->", "params", "[", "'debug'", "]", ")", "?", "$", "this", "->", "params", "[", "'debug'", "]", ":", "false", ";", "$", "queues", "=", "Configure", "::", "read", "(", "'CakeResque.Queues'", ")", ";", "if", "(", "$", "queues", "===", "null", ")", "{", "$", "this", "->", "out", "(", "' '", ".", "__d", "(", "'cake_resque'", ",", "'You have no configured workers to load.'", ")", ")", ";", "}", "else", "{", "foreach", "(", "$", "queues", "as", "$", "workerArgs", ")", "{", "$", "workerArgs", "[", "'debug'", "]", "=", "$", "debug", ";", "$", "this", "->", "start", "(", "$", "workerArgs", ")", ";", "}", "}", "if", "(", "Configure", "::", "read", "(", "'CakeResque.Scheduler.enabled'", ")", "===", "true", ")", "{", "$", "this", "->", "startscheduler", "(", "[", "'debug'", "=>", "$", "debug", "]", ")", ";", "}", "$", "this", "->", "out", "(", "''", ")", ";", "}" ]
Start a list of predefined workers. Note: Each predefined queue will create a new worker. @return void @see 'CakeResque.Queues' in Config/config.php
[ "Start", "a", "list", "of", "predefined", "workers", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L730-L751
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.__getProcessOwner
private function __getProcessOwner() { if (function_exists('posix_getpwuid')) { $a = posix_getpwuid(posix_getuid()); return $a['name']; } else { $user = trim(exec('whoami', $o, $code)); if ($code === 0) { return $user; } return false; } return false; }
php
private function __getProcessOwner() { if (function_exists('posix_getpwuid')) { $a = posix_getpwuid(posix_getuid()); return $a['name']; } else { $user = trim(exec('whoami', $o, $code)); if ($code === 0) { return $user; } return false; } return false; }
[ "private", "function", "__getProcessOwner", "(", ")", "{", "if", "(", "function_exists", "(", "'posix_getpwuid'", ")", ")", "{", "$", "a", "=", "posix_getpwuid", "(", "posix_getuid", "(", ")", ")", ";", "return", "$", "a", "[", "'name'", "]", ";", "}", "else", "{", "$", "user", "=", "trim", "(", "exec", "(", "'whoami'", ",", "$", "o", ",", "$", "code", ")", ")", ";", "if", "(", "$", "code", "===", "0", ")", "{", "return", "$", "user", ";", "}", "return", "false", ";", "}", "return", "false", ";", "}" ]
Get the username of the current process owner. @since 4.0.0 @codeCoverageIgnore @return string Username of the current process owner if found, false otherwise.
[ "Get", "the", "username", "of", "the", "current", "process", "owner", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L1015-L1031
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell._getResqueBinFile
protected function _getResqueBinFile($base) { $paths = [ 'bin' . DS . 'resque', 'bin' . DS . 'resque.php', 'resque.php', ]; foreach ($paths as $path) { if (file_exists($base . DS . $path)) { return '.' . DS . $path; } } return '.' . DS . 'resque.php'; }
php
protected function _getResqueBinFile($base) { $paths = [ 'bin' . DS . 'resque', 'bin' . DS . 'resque.php', 'resque.php', ]; foreach ($paths as $path) { if (file_exists($base . DS . $path)) { return '.' . DS . $path; } } return '.' . DS . 'resque.php'; }
[ "protected", "function", "_getResqueBinFile", "(", "$", "base", ")", "{", "$", "paths", "=", "[", "'bin'", ".", "DS", ".", "'resque'", ",", "'bin'", ".", "DS", ".", "'resque.php'", ",", "'resque.php'", ",", "]", ";", "foreach", "(", "$", "paths", "as", "$", "path", ")", "{", "if", "(", "file_exists", "(", "$", "base", ".", "DS", ".", "$", "path", ")", ")", "{", "return", "'.'", ".", "DS", ".", "$", "path", ";", "}", "}", "return", "'.'", ".", "DS", ".", "'resque.php'", ";", "}" ]
Return the php-resque executable file. Maintain backward compatibility, as newer version of php-resque has that file in another location. @param string $base Folder path for php-resque. @since 3.3.2 @return string Relative path to php-resque executable file.
[ "Return", "the", "php", "-", "resque", "executable", "file", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L1043-L1058
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell._checkStartedWorker
protected function _checkStartedWorker($pidFile) { $pid = false; if (file_exists($pidFile) && false !== $pid = file_get_contents($pidFile)) { unlink($pidFile); return (int)$pid; } return false; }
php
protected function _checkStartedWorker($pidFile) { $pid = false; if (file_exists($pidFile) && false !== $pid = file_get_contents($pidFile)) { unlink($pidFile); return (int)$pid; } return false; }
[ "protected", "function", "_checkStartedWorker", "(", "$", "pidFile", ")", "{", "$", "pid", "=", "false", ";", "if", "(", "file_exists", "(", "$", "pidFile", ")", "&&", "false", "!==", "$", "pid", "=", "file_get_contents", "(", "$", "pidFile", ")", ")", "{", "unlink", "(", "$", "pidFile", ")", ";", "return", "(", "int", ")", "$", "pid", ";", "}", "return", "false", ";", "}" ]
Check if the worker has started. @param string $pidFile Path to the file containing the worker PID. @since 3.3.6 @codeCoverageIgnore @return mixed Worker PID if worker is started, false otherwise.
[ "Check", "if", "the", "worker", "has", "started", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L1068-L1078
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.restart
public function restart() { $workersArgs = $this->ResqueStatus->getWorkers(); $this->params['all'] = true; $this->stop(); $this->out('<info>' . __d('cake_resque', 'Restarting workers') . '</info>'); if (!empty($workersArgs)) { $debug = $this->params['debug']; $this->debug(__d('cake_resque', 'Found ' . count($workersArgs) . ' workers to restart')); foreach ($workersArgs as $workerArgs) { $workerArgs['debug'] = $debug; if (isset($workerArgs['type']) && $workerArgs['type'] === 'scheduler') { $this->startScheduler($workerArgs); } else { $this->start($workerArgs); } } $this->out(''); } else { $this->out('<warning>' . __d('cake_resque', 'No active workers found, will start brand new worker') . '</warning>'); $this->start(); } }
php
public function restart() { $workersArgs = $this->ResqueStatus->getWorkers(); $this->params['all'] = true; $this->stop(); $this->out('<info>' . __d('cake_resque', 'Restarting workers') . '</info>'); if (!empty($workersArgs)) { $debug = $this->params['debug']; $this->debug(__d('cake_resque', 'Found ' . count($workersArgs) . ' workers to restart')); foreach ($workersArgs as $workerArgs) { $workerArgs['debug'] = $debug; if (isset($workerArgs['type']) && $workerArgs['type'] === 'scheduler') { $this->startScheduler($workerArgs); } else { $this->start($workerArgs); } } $this->out(''); } else { $this->out('<warning>' . __d('cake_resque', 'No active workers found, will start brand new worker') . '</warning>'); $this->start(); } }
[ "public", "function", "restart", "(", ")", "{", "$", "workersArgs", "=", "$", "this", "->", "ResqueStatus", "->", "getWorkers", "(", ")", ";", "$", "this", "->", "params", "[", "'all'", "]", "=", "true", ";", "$", "this", "->", "stop", "(", ")", ";", "$", "this", "->", "out", "(", "'<info>'", ".", "__d", "(", "'cake_resque'", ",", "'Restarting workers'", ")", ".", "'</info>'", ")", ";", "if", "(", "!", "empty", "(", "$", "workersArgs", ")", ")", "{", "$", "debug", "=", "$", "this", "->", "params", "[", "'debug'", "]", ";", "$", "this", "->", "debug", "(", "__d", "(", "'cake_resque'", ",", "'Found '", ".", "count", "(", "$", "workersArgs", ")", ".", "' workers to restart'", ")", ")", ";", "foreach", "(", "$", "workersArgs", "as", "$", "workerArgs", ")", "{", "$", "workerArgs", "[", "'debug'", "]", "=", "$", "debug", ";", "if", "(", "isset", "(", "$", "workerArgs", "[", "'type'", "]", ")", "&&", "$", "workerArgs", "[", "'type'", "]", "===", "'scheduler'", ")", "{", "$", "this", "->", "startScheduler", "(", "$", "workerArgs", ")", ";", "}", "else", "{", "$", "this", "->", "start", "(", "$", "workerArgs", ")", ";", "}", "}", "$", "this", "->", "out", "(", "''", ")", ";", "}", "else", "{", "$", "this", "->", "out", "(", "'<warning>'", ".", "__d", "(", "'cake_resque'", ",", "'No active workers found, will start brand new worker'", ")", ".", "'</warning>'", ")", ";", "$", "this", "->", "start", "(", ")", ";", "}", "}" ]
Restart all workers. Note: The workers status is conveniently stored by ResqueStatus. @return void @see ResqueStatus\ResqueStatus::getWorkers()
[ "Restart", "all", "workers", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L1100-L1125
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.clear
public function clear() { $this->out('<info>' . __d('cake_resque', 'Clearing queues') . '</info>'); // List of all queues $queues = array_unique(CakeResque::getQueues()); if (empty($queues)) { $this->out(__d('cake_resque', 'There is no queues to clear')); return false; } $queueIndex = []; if (isset($this->args[0])) { if (in_array($this->args[0], $queues)) { $queueIndex[] = array_search($this->args[0], $queues) + 1; } } else { if (!$this->params['all'] && count($queues) > 1) { $this->out(__d('cake_resque', 'Queues list') . ':'); $i = 1; foreach ($queues as $queue) { $this->out(sprintf(" [%3d] - %-'.20s<bold>%'.9s</bold> jobs", $i++, $queue, number_format(CakeResque::getQueueSize($queue)))); } $options = range(1, $i - 1); if ($i > 2) { $this->out(' [all] - ' . __d('cake_resque', 'Clear all queues')); $options[] = 'all'; } $in = $this->in(__d('cake_resque', 'Queue to clear') . ': ', $options); if ($in == 'all') { $queueIndex = range(1, count($queues)); } else { $queueIndex[] = $in; } } else { $queueIndex = range(1, count($queues)); } } foreach ($queueIndex as $index) { $queue = $queues[ $index - 1 ]; $this->out(__d('cake_resque', 'Clearing {0} ... ', $queue), 0); $cleared = CakeResque::clearQueue($queue); if ($cleared) { CakeResque::removeQueue($queue); $this->out('<success>' . __d('cake_resque', 'Done') . '</success>'); } else { $this->out('<error>' . __d('cake_resque', 'Fail') . '</error>'); } } return true; }
php
public function clear() { $this->out('<info>' . __d('cake_resque', 'Clearing queues') . '</info>'); // List of all queues $queues = array_unique(CakeResque::getQueues()); if (empty($queues)) { $this->out(__d('cake_resque', 'There is no queues to clear')); return false; } $queueIndex = []; if (isset($this->args[0])) { if (in_array($this->args[0], $queues)) { $queueIndex[] = array_search($this->args[0], $queues) + 1; } } else { if (!$this->params['all'] && count($queues) > 1) { $this->out(__d('cake_resque', 'Queues list') . ':'); $i = 1; foreach ($queues as $queue) { $this->out(sprintf(" [%3d] - %-'.20s<bold>%'.9s</bold> jobs", $i++, $queue, number_format(CakeResque::getQueueSize($queue)))); } $options = range(1, $i - 1); if ($i > 2) { $this->out(' [all] - ' . __d('cake_resque', 'Clear all queues')); $options[] = 'all'; } $in = $this->in(__d('cake_resque', 'Queue to clear') . ': ', $options); if ($in == 'all') { $queueIndex = range(1, count($queues)); } else { $queueIndex[] = $in; } } else { $queueIndex = range(1, count($queues)); } } foreach ($queueIndex as $index) { $queue = $queues[ $index - 1 ]; $this->out(__d('cake_resque', 'Clearing {0} ... ', $queue), 0); $cleared = CakeResque::clearQueue($queue); if ($cleared) { CakeResque::removeQueue($queue); $this->out('<success>' . __d('cake_resque', 'Done') . '</success>'); } else { $this->out('<error>' . __d('cake_resque', 'Fail') . '</error>'); } } return true; }
[ "public", "function", "clear", "(", ")", "{", "$", "this", "->", "out", "(", "'<info>'", ".", "__d", "(", "'cake_resque'", ",", "'Clearing queues'", ")", ".", "'</info>'", ")", ";", "// List of all queues", "$", "queues", "=", "array_unique", "(", "CakeResque", "::", "getQueues", "(", ")", ")", ";", "if", "(", "empty", "(", "$", "queues", ")", ")", "{", "$", "this", "->", "out", "(", "__d", "(", "'cake_resque'", ",", "'There is no queues to clear'", ")", ")", ";", "return", "false", ";", "}", "$", "queueIndex", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "args", "[", "0", "]", ")", ")", "{", "if", "(", "in_array", "(", "$", "this", "->", "args", "[", "0", "]", ",", "$", "queues", ")", ")", "{", "$", "queueIndex", "[", "]", "=", "array_search", "(", "$", "this", "->", "args", "[", "0", "]", ",", "$", "queues", ")", "+", "1", ";", "}", "}", "else", "{", "if", "(", "!", "$", "this", "->", "params", "[", "'all'", "]", "&&", "count", "(", "$", "queues", ")", ">", "1", ")", "{", "$", "this", "->", "out", "(", "__d", "(", "'cake_resque'", ",", "'Queues list'", ")", ".", "':'", ")", ";", "$", "i", "=", "1", ";", "foreach", "(", "$", "queues", "as", "$", "queue", ")", "{", "$", "this", "->", "out", "(", "sprintf", "(", "\" [%3d] - %-'.20s<bold>%'.9s</bold> jobs\"", ",", "$", "i", "++", ",", "$", "queue", ",", "number_format", "(", "CakeResque", "::", "getQueueSize", "(", "$", "queue", ")", ")", ")", ")", ";", "}", "$", "options", "=", "range", "(", "1", ",", "$", "i", "-", "1", ")", ";", "if", "(", "$", "i", ">", "2", ")", "{", "$", "this", "->", "out", "(", "' [all] - '", ".", "__d", "(", "'cake_resque'", ",", "'Clear all queues'", ")", ")", ";", "$", "options", "[", "]", "=", "'all'", ";", "}", "$", "in", "=", "$", "this", "->", "in", "(", "__d", "(", "'cake_resque'", ",", "'Queue to clear'", ")", ".", "': '", ",", "$", "options", ")", ";", "if", "(", "$", "in", "==", "'all'", ")", "{", "$", "queueIndex", "=", "range", "(", "1", ",", "count", "(", "$", "queues", ")", ")", ";", "}", "else", "{", "$", "queueIndex", "[", "]", "=", "$", "in", ";", "}", "}", "else", "{", "$", "queueIndex", "=", "range", "(", "1", ",", "count", "(", "$", "queues", ")", ")", ";", "}", "}", "foreach", "(", "$", "queueIndex", "as", "$", "index", ")", "{", "$", "queue", "=", "$", "queues", "[", "$", "index", "-", "1", "]", ";", "$", "this", "->", "out", "(", "__d", "(", "'cake_resque'", ",", "'Clearing {0} ... '", ",", "$", "queue", ")", ",", "0", ")", ";", "$", "cleared", "=", "CakeResque", "::", "clearQueue", "(", "$", "queue", ")", ";", "if", "(", "$", "cleared", ")", "{", "CakeResque", "::", "removeQueue", "(", "$", "queue", ")", ";", "$", "this", "->", "out", "(", "'<success>'", ".", "__d", "(", "'cake_resque'", ",", "'Done'", ")", ".", "'</success>'", ")", ";", "}", "else", "{", "$", "this", "->", "out", "(", "'<error>'", ".", "__d", "(", "'cake_resque'", ",", "'Fail'", ")", ".", "'</error>'", ")", ";", "}", "}", "return", "true", ";", "}" ]
Clear a queue. Remove all jobs inside a queue. If more than one queue is present, it will prompt the user which queue to clear via a menu. If the queues are empty, they are removed from the queues list. @since 3.3.0 @return bool False is clearing the queues fails.
[ "Clear", "a", "queue", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L1380-L1440
train
wa0x6e/Cake-Resque
src/Shell/CakeResqueShell.php
CakeResqueShell.reset
public function reset() { $ResqueStatus = $this->ResqueStatus; $this->debug(__d('cake_resque', 'Emptying the worker database')); $ResqueStatus->clearWorkers(); $this->debug(__d('cake_resque', 'Unregistering the scheduler worker')); $ResqueStatus->unregisterSchedulerWorker(); $this->out('<success>' . __d('cake_resque', 'CakeResque state has been reseted') . '</success>'); }
php
public function reset() { $ResqueStatus = $this->ResqueStatus; $this->debug(__d('cake_resque', 'Emptying the worker database')); $ResqueStatus->clearWorkers(); $this->debug(__d('cake_resque', 'Unregistering the scheduler worker')); $ResqueStatus->unregisterSchedulerWorker(); $this->out('<success>' . __d('cake_resque', 'CakeResque state has been reseted') . '</success>'); }
[ "public", "function", "reset", "(", ")", "{", "$", "ResqueStatus", "=", "$", "this", "->", "ResqueStatus", ";", "$", "this", "->", "debug", "(", "__d", "(", "'cake_resque'", ",", "'Emptying the worker database'", ")", ")", ";", "$", "ResqueStatus", "->", "clearWorkers", "(", ")", ";", "$", "this", "->", "debug", "(", "__d", "(", "'cake_resque'", ",", "'Unregistering the scheduler worker'", ")", ")", ";", "$", "ResqueStatus", "->", "unregisterSchedulerWorker", "(", ")", ";", "$", "this", "->", "out", "(", "'<success>'", ".", "__d", "(", "'cake_resque'", ",", "'CakeResque state has been reseted'", ")", ".", "'</success>'", ")", ";", "}" ]
Reset workers statuses. Note: The workers status is conveniently stored by ResqueStatus. @since 3.3.7 @return void @see ResqueStatus\ResqueStatus::clearWorkers() @see ResqueStatus\ResqueStatus::unregisterSchedulerWorker()
[ "Reset", "workers", "statuses", "." ]
3ea90434e478b24629d55d9aed43a2a5a4004a1d
https://github.com/wa0x6e/Cake-Resque/blob/3ea90434e478b24629d55d9aed43a2a5a4004a1d/src/Shell/CakeResqueShell.php#L1452-L1461
train
lorenzo/cakephp-email-queue
src/Model/Table/EmailQueueTable.php
EmailQueueTable.getBatch
public function getBatch($size = 10) { return $this->getConnection()->transactional(function () use ($size) { $emails = $this->find() ->where([ $this->aliasField('sent') => false, $this->aliasField('send_tries') . ' <=' => 3, $this->aliasField('send_at') . ' <=' => new FrozenTime('now'), $this->aliasField('locked') => false, ]) ->limit($size) ->order([$this->aliasField('created') => 'ASC']); $emails ->extract('id') ->through(function (\Cake\Collection\CollectionInterface $ids) { if (!$ids->isEmpty()) { $this->updateAll(['locked' => true], ['id IN' => $ids->toList()]); } return $ids; }); return $emails->toList(); }); }
php
public function getBatch($size = 10) { return $this->getConnection()->transactional(function () use ($size) { $emails = $this->find() ->where([ $this->aliasField('sent') => false, $this->aliasField('send_tries') . ' <=' => 3, $this->aliasField('send_at') . ' <=' => new FrozenTime('now'), $this->aliasField('locked') => false, ]) ->limit($size) ->order([$this->aliasField('created') => 'ASC']); $emails ->extract('id') ->through(function (\Cake\Collection\CollectionInterface $ids) { if (!$ids->isEmpty()) { $this->updateAll(['locked' => true], ['id IN' => $ids->toList()]); } return $ids; }); return $emails->toList(); }); }
[ "public", "function", "getBatch", "(", "$", "size", "=", "10", ")", "{", "return", "$", "this", "->", "getConnection", "(", ")", "->", "transactional", "(", "function", "(", ")", "use", "(", "$", "size", ")", "{", "$", "emails", "=", "$", "this", "->", "find", "(", ")", "->", "where", "(", "[", "$", "this", "->", "aliasField", "(", "'sent'", ")", "=>", "false", ",", "$", "this", "->", "aliasField", "(", "'send_tries'", ")", ".", "' <='", "=>", "3", ",", "$", "this", "->", "aliasField", "(", "'send_at'", ")", ".", "' <='", "=>", "new", "FrozenTime", "(", "'now'", ")", ",", "$", "this", "->", "aliasField", "(", "'locked'", ")", "=>", "false", ",", "]", ")", "->", "limit", "(", "$", "size", ")", "->", "order", "(", "[", "$", "this", "->", "aliasField", "(", "'created'", ")", "=>", "'ASC'", "]", ")", ";", "$", "emails", "->", "extract", "(", "'id'", ")", "->", "through", "(", "function", "(", "\\", "Cake", "\\", "Collection", "\\", "CollectionInterface", "$", "ids", ")", "{", "if", "(", "!", "$", "ids", "->", "isEmpty", "(", ")", ")", "{", "$", "this", "->", "updateAll", "(", "[", "'locked'", "=>", "true", "]", ",", "[", "'id IN'", "=>", "$", "ids", "->", "toList", "(", ")", "]", ")", ";", "}", "return", "$", "ids", ";", "}", ")", ";", "return", "$", "emails", "->", "toList", "(", ")", ";", "}", ")", ";", "}" ]
Returns a list of queued emails that needs to be sent. @param int $size number of unset emails to return @throws \Exception any exception raised in transactional callback @return array list of unsent emails
[ "Returns", "a", "list", "of", "queued", "emails", "that", "needs", "to", "be", "sent", "." ]
eb944f4408756dad47598214265695720b35f832
https://github.com/lorenzo/cakephp-email-queue/blob/eb944f4408756dad47598214265695720b35f832/src/Model/Table/EmailQueueTable.php#L100-L125
train
lorenzo/cakephp-email-queue
src/Model/Table/EmailQueueTable.php
EmailQueueTable._initializeSchema
protected function _initializeSchema(TableSchema $schema) { $type = Configure::read('EmailQueue.serialization_type') ?: 'email_queue.serialize'; $schema->setColumnType('template_vars', $type); $schema->setColumnType('headers', $type); $schema->setColumnType('attachments', $type); return $schema; }
php
protected function _initializeSchema(TableSchema $schema) { $type = Configure::read('EmailQueue.serialization_type') ?: 'email_queue.serialize'; $schema->setColumnType('template_vars', $type); $schema->setColumnType('headers', $type); $schema->setColumnType('attachments', $type); return $schema; }
[ "protected", "function", "_initializeSchema", "(", "TableSchema", "$", "schema", ")", "{", "$", "type", "=", "Configure", "::", "read", "(", "'EmailQueue.serialization_type'", ")", "?", ":", "'email_queue.serialize'", ";", "$", "schema", "->", "setColumnType", "(", "'template_vars'", ",", "$", "type", ")", ";", "$", "schema", "->", "setColumnType", "(", "'headers'", ",", "$", "type", ")", ";", "$", "schema", "->", "setColumnType", "(", "'attachments'", ",", "$", "type", ")", ";", "return", "$", "schema", ";", "}" ]
Sets the column type for template_vars and headers to json. @param TableSchema $schema The table description @return TableSchema
[ "Sets", "the", "column", "type", "for", "template_vars", "and", "headers", "to", "json", "." ]
eb944f4408756dad47598214265695720b35f832
https://github.com/lorenzo/cakephp-email-queue/blob/eb944f4408756dad47598214265695720b35f832/src/Model/Table/EmailQueueTable.php#L186-L194
train
lorenzo/cakephp-email-queue
src/Database/Type/JsonType.php
JsonType.marshal
public function marshal($value) { if (is_array($value) || $value === null) { return $value; } return json_decode($value, true); }
php
public function marshal($value) { if (is_array($value) || $value === null) { return $value; } return json_decode($value, true); }
[ "public", "function", "marshal", "(", "$", "value", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "||", "$", "value", "===", "null", ")", "{", "return", "$", "value", ";", "}", "return", "json_decode", "(", "$", "value", ",", "true", ")", ";", "}" ]
Marshal - Decodes a JSON string @param mixed $value json string to decode @return mixed|null|string
[ "Marshal", "-", "Decodes", "a", "JSON", "string" ]
eb944f4408756dad47598214265695720b35f832
https://github.com/lorenzo/cakephp-email-queue/blob/eb944f4408756dad47598214265695720b35f832/src/Database/Type/JsonType.php#L31-L38
train
atehnix/laravel-vk-requester
src/Jobs/SendBatch.php
SendBatch.makeExecuteRequest
protected function makeExecuteRequest(Collection $requests) { $clientRequests = $requests->map(function (VkRequest $request) { return new Request($request->method, $request->parameters); }); return ExecuteRequest::make($clientRequests->all()); }
php
protected function makeExecuteRequest(Collection $requests) { $clientRequests = $requests->map(function (VkRequest $request) { return new Request($request->method, $request->parameters); }); return ExecuteRequest::make($clientRequests->all()); }
[ "protected", "function", "makeExecuteRequest", "(", "Collection", "$", "requests", ")", "{", "$", "clientRequests", "=", "$", "requests", "->", "map", "(", "function", "(", "VkRequest", "$", "request", ")", "{", "return", "new", "Request", "(", "$", "request", "->", "method", ",", "$", "request", "->", "parameters", ")", ";", "}", ")", ";", "return", "ExecuteRequest", "::", "make", "(", "$", "clientRequests", "->", "all", "(", ")", ")", ";", "}" ]
Make a new "execute" request instanse with nested requests. @param Collection $requests @return ExecuteRequest
[ "Make", "a", "new", "execute", "request", "instanse", "with", "nested", "requests", "." ]
ecb8ad87552b4403776a9035b6625d71f673ac7e
https://github.com/atehnix/laravel-vk-requester/blob/ecb8ad87552b4403776a9035b6625d71f673ac7e/src/Jobs/SendBatch.php#L109-L116
train
atehnix/laravel-vk-requester
src/Jobs/SendBatch.php
SendBatch.getResponses
protected function getResponses(array $executeResponse) { if (isset($executeResponse['error'])) { return array_fill(0, $this->requests->count(), $executeResponse['error']); } $errors = isset($executeResponse['execute_errors']) ? $executeResponse['execute_errors'] : []; return array_map(function ($response) use (&$errors) { return $response ?: array_shift($errors); }, $executeResponse['response']); }
php
protected function getResponses(array $executeResponse) { if (isset($executeResponse['error'])) { return array_fill(0, $this->requests->count(), $executeResponse['error']); } $errors = isset($executeResponse['execute_errors']) ? $executeResponse['execute_errors'] : []; return array_map(function ($response) use (&$errors) { return $response ?: array_shift($errors); }, $executeResponse['response']); }
[ "protected", "function", "getResponses", "(", "array", "$", "executeResponse", ")", "{", "if", "(", "isset", "(", "$", "executeResponse", "[", "'error'", "]", ")", ")", "{", "return", "array_fill", "(", "0", ",", "$", "this", "->", "requests", "->", "count", "(", ")", ",", "$", "executeResponse", "[", "'error'", "]", ")", ";", "}", "$", "errors", "=", "isset", "(", "$", "executeResponse", "[", "'execute_errors'", "]", ")", "?", "$", "executeResponse", "[", "'execute_errors'", "]", ":", "[", "]", ";", "return", "array_map", "(", "function", "(", "$", "response", ")", "use", "(", "&", "$", "errors", ")", "{", "return", "$", "response", "?", ":", "array_shift", "(", "$", "errors", ")", ";", "}", ",", "$", "executeResponse", "[", "'response'", "]", ")", ";", "}" ]
Get array of nested responses in "execute" response @param array $executeResponse @return array
[ "Get", "array", "of", "nested", "responses", "in", "execute", "response" ]
ecb8ad87552b4403776a9035b6625d71f673ac7e
https://github.com/atehnix/laravel-vk-requester/blob/ecb8ad87552b4403776a9035b6625d71f673ac7e/src/Jobs/SendBatch.php#L124-L135
train
atehnix/laravel-vk-requester
src/Jobs/SendBatch.php
SendBatch.fireEvents
protected function fireEvents() { array_map(function (VkRequest $request, $response) { $status = isset($response['error_code']) ? VkRequest::STATUS_FAIL : VkRequest::STATUS_SUCCESS; $event = sprintf(VkRequest::EVENT_FORMAT, $status, $request->method, $request->tag); event($event, [$request, $response]); }, $this->requests->all(), $this->responses); }
php
protected function fireEvents() { array_map(function (VkRequest $request, $response) { $status = isset($response['error_code']) ? VkRequest::STATUS_FAIL : VkRequest::STATUS_SUCCESS; $event = sprintf(VkRequest::EVENT_FORMAT, $status, $request->method, $request->tag); event($event, [$request, $response]); }, $this->requests->all(), $this->responses); }
[ "protected", "function", "fireEvents", "(", ")", "{", "array_map", "(", "function", "(", "VkRequest", "$", "request", ",", "$", "response", ")", "{", "$", "status", "=", "isset", "(", "$", "response", "[", "'error_code'", "]", ")", "?", "VkRequest", "::", "STATUS_FAIL", ":", "VkRequest", "::", "STATUS_SUCCESS", ";", "$", "event", "=", "sprintf", "(", "VkRequest", "::", "EVENT_FORMAT", ",", "$", "status", ",", "$", "request", "->", "method", ",", "$", "request", "->", "tag", ")", ";", "event", "(", "$", "event", ",", "[", "$", "request", ",", "$", "response", "]", ")", ";", "}", ",", "$", "this", "->", "requests", "->", "all", "(", ")", ",", "$", "this", "->", "responses", ")", ";", "}" ]
Fire an event for each of response
[ "Fire", "an", "event", "for", "each", "of", "response" ]
ecb8ad87552b4403776a9035b6625d71f673ac7e
https://github.com/atehnix/laravel-vk-requester/blob/ecb8ad87552b4403776a9035b6625d71f673ac7e/src/Jobs/SendBatch.php#L140-L147
train
atehnix/laravel-vk-requester
src/Contracts/Request.php
Request.parameter
public function parameter(string $key, $newValue = null) { if (func_num_args() >= 2) { $this->parameters = array_merge($this->parameters, [$key => $newValue]); } return isset($this->parameters[$key]) ? $this->parameters[$key] : null; }
php
public function parameter(string $key, $newValue = null) { if (func_num_args() >= 2) { $this->parameters = array_merge($this->parameters, [$key => $newValue]); } return isset($this->parameters[$key]) ? $this->parameters[$key] : null; }
[ "public", "function", "parameter", "(", "string", "$", "key", ",", "$", "newValue", "=", "null", ")", "{", "if", "(", "func_num_args", "(", ")", ">=", "2", ")", "{", "$", "this", "->", "parameters", "=", "array_merge", "(", "$", "this", "->", "parameters", ",", "[", "$", "key", "=>", "$", "newValue", "]", ")", ";", "}", "return", "isset", "(", "$", "this", "->", "parameters", "[", "$", "key", "]", ")", "?", "$", "this", "->", "parameters", "[", "$", "key", "]", ":", "null", ";", "}" ]
Get or set value of parameter @param string $key @param null $newValue @return mixed
[ "Get", "or", "set", "value", "of", "parameter" ]
ecb8ad87552b4403776a9035b6625d71f673ac7e
https://github.com/atehnix/laravel-vk-requester/blob/ecb8ad87552b4403776a9035b6625d71f673ac7e/src/Contracts/Request.php#L39-L46
train
atehnix/laravel-vk-requester
src/Contracts/Request.php
Request.setParametersAttribute
public function setParametersAttribute(array $parameters) { $defaultParameters = $this->getDefaultParameters(); $this->attributes['parameters'] = json_encode( array_merge($defaultParameters, $parameters) ); }
php
public function setParametersAttribute(array $parameters) { $defaultParameters = $this->getDefaultParameters(); $this->attributes['parameters'] = json_encode( array_merge($defaultParameters, $parameters) ); }
[ "public", "function", "setParametersAttribute", "(", "array", "$", "parameters", ")", "{", "$", "defaultParameters", "=", "$", "this", "->", "getDefaultParameters", "(", ")", ";", "$", "this", "->", "attributes", "[", "'parameters'", "]", "=", "json_encode", "(", "array_merge", "(", "$", "defaultParameters", ",", "$", "parameters", ")", ")", ";", "}" ]
Setter for Parameters @param array $parameters
[ "Setter", "for", "Parameters" ]
ecb8ad87552b4403776a9035b6625d71f673ac7e
https://github.com/atehnix/laravel-vk-requester/blob/ecb8ad87552b4403776a9035b6625d71f673ac7e/src/Contracts/Request.php#L53-L59
train
atehnix/laravel-vk-requester
src/Contracts/Traits/MagicApiMethod.php
MagicApiMethod.getApiMethod
protected function getApiMethod() { if (!isset($this->apiMethod)) { $words = explode('_', Str::snake(class_basename($this)), -1); $endpoint = strtolower(array_shift($words)); $action = Str::camel(implode('_', $words)) ?: '*'; $method = sprintf('%s.%s', $endpoint, $action); $this->apiMethod = $endpoint ? $method : 'undefined'; } return $this->apiMethod; }
php
protected function getApiMethod() { if (!isset($this->apiMethod)) { $words = explode('_', Str::snake(class_basename($this)), -1); $endpoint = strtolower(array_shift($words)); $action = Str::camel(implode('_', $words)) ?: '*'; $method = sprintf('%s.%s', $endpoint, $action); $this->apiMethod = $endpoint ? $method : 'undefined'; } return $this->apiMethod; }
[ "protected", "function", "getApiMethod", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "apiMethod", ")", ")", "{", "$", "words", "=", "explode", "(", "'_'", ",", "Str", "::", "snake", "(", "class_basename", "(", "$", "this", ")", ")", ",", "-", "1", ")", ";", "$", "endpoint", "=", "strtolower", "(", "array_shift", "(", "$", "words", ")", ")", ";", "$", "action", "=", "Str", "::", "camel", "(", "implode", "(", "'_'", ",", "$", "words", ")", ")", "?", ":", "'*'", ";", "$", "method", "=", "sprintf", "(", "'%s.%s'", ",", "$", "endpoint", ",", "$", "action", ")", ";", "$", "this", "->", "apiMethod", "=", "$", "endpoint", "?", "$", "method", ":", "'undefined'", ";", "}", "return", "$", "this", "->", "apiMethod", ";", "}" ]
Get API Method by class name. @return string
[ "Get", "API", "Method", "by", "class", "name", "." ]
ecb8ad87552b4403776a9035b6625d71f673ac7e
https://github.com/atehnix/laravel-vk-requester/blob/ecb8ad87552b4403776a9035b6625d71f673ac7e/src/Contracts/Traits/MagicApiMethod.php#L26-L37
train
atehnix/laravel-vk-requester
src/Jobs/Send.php
Send.fireEvent
private function fireEvent() { $status = isset($this->response['error_code']) ? VkRequest::STATUS_FAIL : VkRequest::STATUS_SUCCESS; $event = sprintf(VkRequest::EVENT_FORMAT, $status, $this->request->method, $this->request->tag); event($event, [$this->request, $this->response]); }
php
private function fireEvent() { $status = isset($this->response['error_code']) ? VkRequest::STATUS_FAIL : VkRequest::STATUS_SUCCESS; $event = sprintf(VkRequest::EVENT_FORMAT, $status, $this->request->method, $this->request->tag); event($event, [$this->request, $this->response]); }
[ "private", "function", "fireEvent", "(", ")", "{", "$", "status", "=", "isset", "(", "$", "this", "->", "response", "[", "'error_code'", "]", ")", "?", "VkRequest", "::", "STATUS_FAIL", ":", "VkRequest", "::", "STATUS_SUCCESS", ";", "$", "event", "=", "sprintf", "(", "VkRequest", "::", "EVENT_FORMAT", ",", "$", "status", ",", "$", "this", "->", "request", "->", "method", ",", "$", "this", "->", "request", "->", "tag", ")", ";", "event", "(", "$", "event", ",", "[", "$", "this", "->", "request", ",", "$", "this", "->", "response", "]", ")", ";", "}" ]
Fire an event for response
[ "Fire", "an", "event", "for", "response" ]
ecb8ad87552b4403776a9035b6625d71f673ac7e
https://github.com/atehnix/laravel-vk-requester/blob/ecb8ad87552b4403776a9035b6625d71f673ac7e/src/Jobs/Send.php#L107-L112
train
FriendsOfCake/Authenticate
src/Auth/TokenAuthenticate.php
TokenAuthenticate.unauthenticated
public function unauthenticated(Request $request, Response $response) { if ($this->_config['continue']) { return false; } if (is_string($this->_config['unauthorized'])) { // @codingStandardsIgnoreStart throw new $this->_config['unauthorized']; // @codingStandardsIgnoreEnd } $message = __d('authenticate', 'You are not authenticated.'); throw new HttpException($message, $this->_config['unauthorized']); }
php
public function unauthenticated(Request $request, Response $response) { if ($this->_config['continue']) { return false; } if (is_string($this->_config['unauthorized'])) { // @codingStandardsIgnoreStart throw new $this->_config['unauthorized']; // @codingStandardsIgnoreEnd } $message = __d('authenticate', 'You are not authenticated.'); throw new HttpException($message, $this->_config['unauthorized']); }
[ "public", "function", "unauthenticated", "(", "Request", "$", "request", ",", "Response", "$", "response", ")", "{", "if", "(", "$", "this", "->", "_config", "[", "'continue'", "]", ")", "{", "return", "false", ";", "}", "if", "(", "is_string", "(", "$", "this", "->", "_config", "[", "'unauthorized'", "]", ")", ")", "{", "// @codingStandardsIgnoreStart", "throw", "new", "$", "this", "->", "_config", "[", "'unauthorized'", "]", ";", "// @codingStandardsIgnoreEnd", "}", "$", "message", "=", "__d", "(", "'authenticate'", ",", "'You are not authenticated.'", ")", ";", "throw", "new", "HttpException", "(", "$", "message", ",", "$", "this", "->", "_config", "[", "'unauthorized'", "]", ")", ";", "}" ]
If unauthenticated, try to authenticate and respond. @param Request $request The request object. @param Response $response The response object. @return bool False on failure, user on success. @throws HttpException Or the one specified using $settings['unauthorized'].
[ "If", "unauthenticated", "try", "to", "authenticate", "and", "respond", "." ]
4c5e364a9c36221f34c4bca252346fdf46a9d0e5
https://github.com/FriendsOfCake/Authenticate/blob/4c5e364a9c36221f34c4bca252346fdf46a9d0e5/src/Auth/TokenAuthenticate.php#L103-L115
train
FriendsOfCake/Authenticate
src/Auth/TokenAuthenticate.php
TokenAuthenticate.getUser
public function getUser(Request $request) { if (!empty($this->_config['header'])) { $token = $request->header($this->_config['header']); if ($token) { return $this->_findUser($token); } } if (!empty($this->_config['parameter']) && !empty($request->query[$this->_config['parameter']]) ) { $token = $request->query[$this->_config['parameter']]; return $this->_findUser($token); } return false; }
php
public function getUser(Request $request) { if (!empty($this->_config['header'])) { $token = $request->header($this->_config['header']); if ($token) { return $this->_findUser($token); } } if (!empty($this->_config['parameter']) && !empty($request->query[$this->_config['parameter']]) ) { $token = $request->query[$this->_config['parameter']]; return $this->_findUser($token); } return false; }
[ "public", "function", "getUser", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "_config", "[", "'header'", "]", ")", ")", "{", "$", "token", "=", "$", "request", "->", "header", "(", "$", "this", "->", "_config", "[", "'header'", "]", ")", ";", "if", "(", "$", "token", ")", "{", "return", "$", "this", "->", "_findUser", "(", "$", "token", ")", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "_config", "[", "'parameter'", "]", ")", "&&", "!", "empty", "(", "$", "request", "->", "query", "[", "$", "this", "->", "_config", "[", "'parameter'", "]", "]", ")", ")", "{", "$", "token", "=", "$", "request", "->", "query", "[", "$", "this", "->", "_config", "[", "'parameter'", "]", "]", ";", "return", "$", "this", "->", "_findUser", "(", "$", "token", ")", ";", "}", "return", "false", ";", "}" ]
Get token information from the request. @param Request $request Request object. @return mixed Either false or an array of user information
[ "Get", "token", "information", "from", "the", "request", "." ]
4c5e364a9c36221f34c4bca252346fdf46a9d0e5
https://github.com/FriendsOfCake/Authenticate/blob/4c5e364a9c36221f34c4bca252346fdf46a9d0e5/src/Auth/TokenAuthenticate.php#L123-L138
train
FriendsOfCake/Authenticate
src/Auth/TokenAuthenticate.php
TokenAuthenticate._findUser
protected function _findUser($username, $password = null) { $userModel = $this->_config['userModel']; list($plugin, $model) = pluginSplit($userModel); $fields = $this->_config['fields']; $conditions = [$model . '.' . $fields['token'] => $username]; if (!empty($this->_config['scope'])) { $conditions = array_merge($conditions, $this->_config['scope']); } $table = TableRegistry::get($userModel)->find('all'); if ($this->_config['contain']) { $table = $table->contain($this->_config['contain']); } $result = $table ->where($conditions) ->hydrate(false) ->first(); if (empty($result)) { return false; } unset($result[$fields['password']]); return $result; }
php
protected function _findUser($username, $password = null) { $userModel = $this->_config['userModel']; list($plugin, $model) = pluginSplit($userModel); $fields = $this->_config['fields']; $conditions = [$model . '.' . $fields['token'] => $username]; if (!empty($this->_config['scope'])) { $conditions = array_merge($conditions, $this->_config['scope']); } $table = TableRegistry::get($userModel)->find('all'); if ($this->_config['contain']) { $table = $table->contain($this->_config['contain']); } $result = $table ->where($conditions) ->hydrate(false) ->first(); if (empty($result)) { return false; } unset($result[$fields['password']]); return $result; }
[ "protected", "function", "_findUser", "(", "$", "username", ",", "$", "password", "=", "null", ")", "{", "$", "userModel", "=", "$", "this", "->", "_config", "[", "'userModel'", "]", ";", "list", "(", "$", "plugin", ",", "$", "model", ")", "=", "pluginSplit", "(", "$", "userModel", ")", ";", "$", "fields", "=", "$", "this", "->", "_config", "[", "'fields'", "]", ";", "$", "conditions", "=", "[", "$", "model", ".", "'.'", ".", "$", "fields", "[", "'token'", "]", "=>", "$", "username", "]", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "_config", "[", "'scope'", "]", ")", ")", "{", "$", "conditions", "=", "array_merge", "(", "$", "conditions", ",", "$", "this", "->", "_config", "[", "'scope'", "]", ")", ";", "}", "$", "table", "=", "TableRegistry", "::", "get", "(", "$", "userModel", ")", "->", "find", "(", "'all'", ")", ";", "if", "(", "$", "this", "->", "_config", "[", "'contain'", "]", ")", "{", "$", "table", "=", "$", "table", "->", "contain", "(", "$", "this", "->", "_config", "[", "'contain'", "]", ")", ";", "}", "$", "result", "=", "$", "table", "->", "where", "(", "$", "conditions", ")", "->", "hydrate", "(", "false", ")", "->", "first", "(", ")", ";", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "return", "false", ";", "}", "unset", "(", "$", "result", "[", "$", "fields", "[", "'password'", "]", "]", ")", ";", "return", "$", "result", ";", "}" ]
Find a user record. @param string $username The token identifier. @param string $password Unused password. @return Mixed Either false on failure, or an array of user data.
[ "Find", "a", "user", "record", "." ]
4c5e364a9c36221f34c4bca252346fdf46a9d0e5
https://github.com/FriendsOfCake/Authenticate/blob/4c5e364a9c36221f34c4bca252346fdf46a9d0e5/src/Auth/TokenAuthenticate.php#L147-L174
train
novosga/triage-bundle
Controller/DefaultController.php
DefaultController.clientes
public function clientes(Request $request) { $envelope = new Envelope(); $documento = $request->get('q'); $clientes = $this ->getDoctrine() ->getManager() ->getRepository(Cliente::class) ->findByDocumento("{$documento}%"); $envelope->setData($clientes); return $this->json($envelope); }
php
public function clientes(Request $request) { $envelope = new Envelope(); $documento = $request->get('q'); $clientes = $this ->getDoctrine() ->getManager() ->getRepository(Cliente::class) ->findByDocumento("{$documento}%"); $envelope->setData($clientes); return $this->json($envelope); }
[ "public", "function", "clientes", "(", "Request", "$", "request", ")", "{", "$", "envelope", "=", "new", "Envelope", "(", ")", ";", "$", "documento", "=", "$", "request", "->", "get", "(", "'q'", ")", ";", "$", "clientes", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", "->", "getRepository", "(", "Cliente", "::", "class", ")", "->", "findByDocumento", "(", "\"{$documento}%\"", ")", ";", "$", "envelope", "->", "setData", "(", "$", "clientes", ")", ";", "return", "$", "this", "->", "json", "(", "$", "envelope", ")", ";", "}" ]
Busca os clientes a partir do documento. @param Request $request @return Response @Route("/clientes", name="novosga_triage_clientes", methods={"GET"})
[ "Busca", "os", "clientes", "a", "partir", "do", "documento", "." ]
7240114af1d99e1712dcb72ae2144bd0c5859c68
https://github.com/novosga/triage-bundle/blob/7240114af1d99e1712dcb72ae2144bd0c5859c68/Controller/DefaultController.php#L274-L287
train
FriendsOfCake/Authenticate
src/Auth/CookieAuthenticate.php
CookieAuthenticate.getUser
public function getUser(Request $request) { if (!isset($this->_registry->Cookie) || !$this->_registry->Cookie instanceof CookieComponent ) { throw new \RuntimeException('CookieComponent is not loaded'); } $cookieConfig = $this->_config['cookie']; $cookieName = $this->_config['cookie']['name']; unset($cookieConfig['name']); $this->_registry->Cookie->configKey($cookieName, $cookieConfig); $data = $this->_registry->Cookie->read($cookieName); if (empty($data)) { return false; } extract($this->_config['fields']); if (empty($data[$username]) || empty($data[$password])) { return false; } $user = $this->_findUser($data[$username], $data[$password]); if ($user) { $request->session()->write( $this->_registry->Auth->sessionKey, $user ); return $user; } return false; }
php
public function getUser(Request $request) { if (!isset($this->_registry->Cookie) || !$this->_registry->Cookie instanceof CookieComponent ) { throw new \RuntimeException('CookieComponent is not loaded'); } $cookieConfig = $this->_config['cookie']; $cookieName = $this->_config['cookie']['name']; unset($cookieConfig['name']); $this->_registry->Cookie->configKey($cookieName, $cookieConfig); $data = $this->_registry->Cookie->read($cookieName); if (empty($data)) { return false; } extract($this->_config['fields']); if (empty($data[$username]) || empty($data[$password])) { return false; } $user = $this->_findUser($data[$username], $data[$password]); if ($user) { $request->session()->write( $this->_registry->Auth->sessionKey, $user ); return $user; } return false; }
[ "public", "function", "getUser", "(", "Request", "$", "request", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_registry", "->", "Cookie", ")", "||", "!", "$", "this", "->", "_registry", "->", "Cookie", "instanceof", "CookieComponent", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'CookieComponent is not loaded'", ")", ";", "}", "$", "cookieConfig", "=", "$", "this", "->", "_config", "[", "'cookie'", "]", ";", "$", "cookieName", "=", "$", "this", "->", "_config", "[", "'cookie'", "]", "[", "'name'", "]", ";", "unset", "(", "$", "cookieConfig", "[", "'name'", "]", ")", ";", "$", "this", "->", "_registry", "->", "Cookie", "->", "configKey", "(", "$", "cookieName", ",", "$", "cookieConfig", ")", ";", "$", "data", "=", "$", "this", "->", "_registry", "->", "Cookie", "->", "read", "(", "$", "cookieName", ")", ";", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "return", "false", ";", "}", "extract", "(", "$", "this", "->", "_config", "[", "'fields'", "]", ")", ";", "if", "(", "empty", "(", "$", "data", "[", "$", "username", "]", ")", "||", "empty", "(", "$", "data", "[", "$", "password", "]", ")", ")", "{", "return", "false", ";", "}", "$", "user", "=", "$", "this", "->", "_findUser", "(", "$", "data", "[", "$", "username", "]", ",", "$", "data", "[", "$", "password", "]", ")", ";", "if", "(", "$", "user", ")", "{", "$", "request", "->", "session", "(", ")", "->", "write", "(", "$", "this", "->", "_registry", "->", "Auth", "->", "sessionKey", ",", "$", "user", ")", ";", "return", "$", "user", ";", "}", "return", "false", ";", "}" ]
Authenticates the identity contained in the cookie. Will use the `userModel` config, and `fields` config to find COOKIE data that is used to find a matching record in the model specified by `userModel`. Will return false if there is no cookie data, either username or password is missing, or if the scope conditions have not been met. @param Request $request The unused request object. @return mixed False on login failure. An array of User data on success. @throws \RuntimeException If CookieComponent is not loaded.
[ "Authenticates", "the", "identity", "contained", "in", "the", "cookie", ".", "Will", "use", "the", "userModel", "config", "and", "fields", "config", "to", "find", "COOKIE", "data", "that", "is", "used", "to", "find", "a", "matching", "record", "in", "the", "model", "specified", "by", "userModel", ".", "Will", "return", "false", "if", "there", "is", "no", "cookie", "data", "either", "username", "or", "password", "is", "missing", "or", "if", "the", "scope", "conditions", "have", "not", "been", "met", "." ]
4c5e364a9c36221f34c4bca252346fdf46a9d0e5
https://github.com/FriendsOfCake/Authenticate/blob/4c5e364a9c36221f34c4bca252346fdf46a9d0e5/src/Auth/CookieAuthenticate.php#L74-L107
train
cloudcreativity/json-api
src/Utils/Http.php
Http.doesRequestHaveBody
public static function doesRequestHaveBody(RequestInterface $request) { if ($request->hasHeader('Transfer-Encoding')) { return true; }; if (!$contentLength = $request->getHeader('Content-Length')) { return false; } return 0 < $contentLength[0]; }
php
public static function doesRequestHaveBody(RequestInterface $request) { if ($request->hasHeader('Transfer-Encoding')) { return true; }; if (!$contentLength = $request->getHeader('Content-Length')) { return false; } return 0 < $contentLength[0]; }
[ "public", "static", "function", "doesRequestHaveBody", "(", "RequestInterface", "$", "request", ")", "{", "if", "(", "$", "request", "->", "hasHeader", "(", "'Transfer-Encoding'", ")", ")", "{", "return", "true", ";", "}", ";", "if", "(", "!", "$", "contentLength", "=", "$", "request", "->", "getHeader", "(", "'Content-Length'", ")", ")", "{", "return", "false", ";", "}", "return", "0", "<", "$", "contentLength", "[", "0", "]", ";", "}" ]
Does the HTTP request contain body content? "The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request's message-headers." https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 However, some browsers send a Content-Length header with an empty string for e.g. GET requests without any message-body. Therefore rather than checking for the existence of a Content-Length header, we will allow an empty value to indicate that the request does not contain body. @param RequestInterface $request @return bool
[ "Does", "the", "HTTP", "request", "contain", "body", "content?" ]
7bb556c8f67b7c2a248f7d5e45899e29e1e40930
https://github.com/cloudcreativity/json-api/blob/7bb556c8f67b7c2a248f7d5e45899e29e1e40930/src/Utils/Http.php#L45-L56
train
cloudcreativity/json-api
src/Http/Middleware/ValidatesRequests.php
ValidatesRequests.validate
public function validate( InboundRequestInterface $inboundRequest, StoreInterface $store, ValidatorProviderInterface $resource, ValidatorProviderInterface $related = null ) { /** Check the JSON API query parameters */ if (!$inboundRequest->getRelationshipName()) { $this->checkQueryParameters($inboundRequest, $resource); } elseif ($related) { $this->checkQueryParameters($inboundRequest, $related); } $identifier = $inboundRequest->getResourceIdentifier(); $record = $identifier ? $store->findOrFail($identifier) : null; /** Check the JSON API document is acceptable */ $this->checkDocumentIsAcceptable($inboundRequest, $resource, $record); }
php
public function validate( InboundRequestInterface $inboundRequest, StoreInterface $store, ValidatorProviderInterface $resource, ValidatorProviderInterface $related = null ) { /** Check the JSON API query parameters */ if (!$inboundRequest->getRelationshipName()) { $this->checkQueryParameters($inboundRequest, $resource); } elseif ($related) { $this->checkQueryParameters($inboundRequest, $related); } $identifier = $inboundRequest->getResourceIdentifier(); $record = $identifier ? $store->findOrFail($identifier) : null; /** Check the JSON API document is acceptable */ $this->checkDocumentIsAcceptable($inboundRequest, $resource, $record); }
[ "public", "function", "validate", "(", "InboundRequestInterface", "$", "inboundRequest", ",", "StoreInterface", "$", "store", ",", "ValidatorProviderInterface", "$", "resource", ",", "ValidatorProviderInterface", "$", "related", "=", "null", ")", "{", "/** Check the JSON API query parameters */", "if", "(", "!", "$", "inboundRequest", "->", "getRelationshipName", "(", ")", ")", "{", "$", "this", "->", "checkQueryParameters", "(", "$", "inboundRequest", ",", "$", "resource", ")", ";", "}", "elseif", "(", "$", "related", ")", "{", "$", "this", "->", "checkQueryParameters", "(", "$", "inboundRequest", ",", "$", "related", ")", ";", "}", "$", "identifier", "=", "$", "inboundRequest", "->", "getResourceIdentifier", "(", ")", ";", "$", "record", "=", "$", "identifier", "?", "$", "store", "->", "findOrFail", "(", "$", "identifier", ")", ":", "null", ";", "/** Check the JSON API document is acceptable */", "$", "this", "->", "checkDocumentIsAcceptable", "(", "$", "inboundRequest", ",", "$", "resource", ",", "$", "record", ")", ";", "}" ]
Validate the inbound request query parameters and JSON API document. JSON API query parameters are checked using the primary resource's validators if it is not a related resource request, or against the related resource's validators if it is a relationship request. This is because the query parameters for a relationship request actually relate to the related resource that will be returned in the encoded response. So for a request to `GET /posts/1`, the `posts` validators are provided as `$resource` and the query parameters are checked using this set of validators. For a request to `GET /posts/1/comments` the query parameters are checked against the `comments` validators, which are provided as `$related`. The JSON API document is always checked against the primary resource validators (`$resource`) because the inbound document always relates to this primary resource, even if modifying a relationship. @param InboundRequestInterface $inboundRequest @param StoreInterface $store @param ValidatorProviderInterface $resource validators for the primary resource. @param ValidatorProviderInterface|null $related validators for the related resource, if the request is for a relationship. @return void @throws JsonApiException
[ "Validate", "the", "inbound", "request", "query", "parameters", "and", "JSON", "API", "document", "." ]
7bb556c8f67b7c2a248f7d5e45899e29e1e40930
https://github.com/cloudcreativity/json-api/blob/7bb556c8f67b7c2a248f7d5e45899e29e1e40930/src/Http/Middleware/ValidatesRequests.php#L65-L83
train
cloudcreativity/json-api
src/Http/Middleware/ParsesServerRequests.php
ParsesServerRequests.parseServerRequest
protected function parseServerRequest( ServerRequestInterface $serverRequest, FactoryInterface $factory, StoreInterface $store, CodecMatcherInterface $codecMatcher, $resourceType, $resourceId, $relationshipName, $relationships ) { /** If the resource id is not valid, throw a 404 exception. */ if ($resourceId && !$this->doesResourceExist($store, $resourceType, $resourceId)) { throw new JsonApiException([], 404); } /** Do content negotiation. */ $this->doContentNegotiation($factory, $serverRequest, $codecMatcher); /** Parse the server request into a JSON API inbound request object. */ $inboundRequest = $factory->createInboundRequest( $serverRequest->getMethod(), $resourceType, $resourceId, $relationshipName, $relationships, $this->decodeDocument($serverRequest), $this->parseQueryParameters($serverRequest, $factory->createQueryParametersParser()) ); /** Check that there is a JSON API document if one is required for the type of request. */ if ($this->isExpectingDocument($inboundRequest) && !$inboundRequest->getDocument()) { throw new DocumentRequiredException(); } return $inboundRequest; }
php
protected function parseServerRequest( ServerRequestInterface $serverRequest, FactoryInterface $factory, StoreInterface $store, CodecMatcherInterface $codecMatcher, $resourceType, $resourceId, $relationshipName, $relationships ) { /** If the resource id is not valid, throw a 404 exception. */ if ($resourceId && !$this->doesResourceExist($store, $resourceType, $resourceId)) { throw new JsonApiException([], 404); } /** Do content negotiation. */ $this->doContentNegotiation($factory, $serverRequest, $codecMatcher); /** Parse the server request into a JSON API inbound request object. */ $inboundRequest = $factory->createInboundRequest( $serverRequest->getMethod(), $resourceType, $resourceId, $relationshipName, $relationships, $this->decodeDocument($serverRequest), $this->parseQueryParameters($serverRequest, $factory->createQueryParametersParser()) ); /** Check that there is a JSON API document if one is required for the type of request. */ if ($this->isExpectingDocument($inboundRequest) && !$inboundRequest->getDocument()) { throw new DocumentRequiredException(); } return $inboundRequest; }
[ "protected", "function", "parseServerRequest", "(", "ServerRequestInterface", "$", "serverRequest", ",", "FactoryInterface", "$", "factory", ",", "StoreInterface", "$", "store", ",", "CodecMatcherInterface", "$", "codecMatcher", ",", "$", "resourceType", ",", "$", "resourceId", ",", "$", "relationshipName", ",", "$", "relationships", ")", "{", "/** If the resource id is not valid, throw a 404 exception. */", "if", "(", "$", "resourceId", "&&", "!", "$", "this", "->", "doesResourceExist", "(", "$", "store", ",", "$", "resourceType", ",", "$", "resourceId", ")", ")", "{", "throw", "new", "JsonApiException", "(", "[", "]", ",", "404", ")", ";", "}", "/** Do content negotiation. */", "$", "this", "->", "doContentNegotiation", "(", "$", "factory", ",", "$", "serverRequest", ",", "$", "codecMatcher", ")", ";", "/** Parse the server request into a JSON API inbound request object. */", "$", "inboundRequest", "=", "$", "factory", "->", "createInboundRequest", "(", "$", "serverRequest", "->", "getMethod", "(", ")", ",", "$", "resourceType", ",", "$", "resourceId", ",", "$", "relationshipName", ",", "$", "relationships", ",", "$", "this", "->", "decodeDocument", "(", "$", "serverRequest", ")", ",", "$", "this", "->", "parseQueryParameters", "(", "$", "serverRequest", ",", "$", "factory", "->", "createQueryParametersParser", "(", ")", ")", ")", ";", "/** Check that there is a JSON API document if one is required for the type of request. */", "if", "(", "$", "this", "->", "isExpectingDocument", "(", "$", "inboundRequest", ")", "&&", "!", "$", "inboundRequest", "->", "getDocument", "(", ")", ")", "{", "throw", "new", "DocumentRequiredException", "(", ")", ";", "}", "return", "$", "inboundRequest", ";", "}" ]
Parse a server request into a JSON API inbound request object. This method will parse a server request into an inbound JSON API request object that describes the type of JSON API request according to the spec's definitions. It will throw a JSON API exception in any of the following circumstances: - There is a resource id and the type/id combination do not exist (404). - The request fails content negotiation (406/415). - The HTTP request body content does not decode as JSON (400). - The HTTP request body does not contain a JSON API document but one is expected for the request (400). - Any of the JSON API query parameters do not comply with the spec (400). This method expects information about the URL (resource type, id, etc) to be provided as different frameworks may have access to this information separately from the URL. E.g. some frameworks allow variables to be defined on the route definition, or the variables may be available as route parameters. As such, there is no provision for parsing the server request's URL into the parameters, as it will always be more efficient to obtain these directly from the framework-specific implementation. @param ServerRequestInterface $serverRequest @param FactoryInterface $factory @param StoreInterface $store @param CodecMatcherInterface $codecMatcher @param string $resourceType @param string|null $resourceId @param string|null $relationshipName @param bool $relationships @return InboundRequestInterface @throws JsonApiException
[ "Parse", "a", "server", "request", "into", "a", "JSON", "API", "inbound", "request", "object", "." ]
7bb556c8f67b7c2a248f7d5e45899e29e1e40930
https://github.com/cloudcreativity/json-api/blob/7bb556c8f67b7c2a248f7d5e45899e29e1e40930/src/Http/Middleware/ParsesServerRequests.php#L71-L106
train
cloudcreativity/json-api
src/Http/Middleware/ParsesServerRequests.php
ParsesServerRequests.doesResourceExist
protected function doesResourceExist(StoreInterface $store, $resourceType, $resourceId) { $identifier = ResourceIdentifier::create($resourceType, $resourceId); return $store->exists($identifier); }
php
protected function doesResourceExist(StoreInterface $store, $resourceType, $resourceId) { $identifier = ResourceIdentifier::create($resourceType, $resourceId); return $store->exists($identifier); }
[ "protected", "function", "doesResourceExist", "(", "StoreInterface", "$", "store", ",", "$", "resourceType", ",", "$", "resourceId", ")", "{", "$", "identifier", "=", "ResourceIdentifier", "::", "create", "(", "$", "resourceType", ",", "$", "resourceId", ")", ";", "return", "$", "store", "->", "exists", "(", "$", "identifier", ")", ";", "}" ]
Is the supplied resource type and id valid? @param StoreInterface $store @param $resourceType @param $resourceId @return bool
[ "Is", "the", "supplied", "resource", "type", "and", "id", "valid?" ]
7bb556c8f67b7c2a248f7d5e45899e29e1e40930
https://github.com/cloudcreativity/json-api/blob/7bb556c8f67b7c2a248f7d5e45899e29e1e40930/src/Http/Middleware/ParsesServerRequests.php#L116-L121
train