repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
zbateson/mail-mime-parser
src/Container.php
Container.getMimeLiteralPartFactory
public function getMimeLiteralPartFactory() { if ($this->mimeLiteralPartFactory === null) { $this->mimeLiteralPartFactory = new MimeLiteralPartFactory($this->getCharsetConverter()); } return $this->mimeLiteralPartFactory; }
php
public function getMimeLiteralPartFactory() { if ($this->mimeLiteralPartFactory === null) { $this->mimeLiteralPartFactory = new MimeLiteralPartFactory($this->getCharsetConverter()); } return $this->mimeLiteralPartFactory; }
[ "public", "function", "getMimeLiteralPartFactory", "(", ")", "{", "if", "(", "$", "this", "->", "mimeLiteralPartFactory", "===", "null", ")", "{", "$", "this", "->", "mimeLiteralPartFactory", "=", "new", "MimeLiteralPartFactory", "(", "$", "this", "->", "getChar...
Returns the MimeLiteralPartFactory service @return \ZBateson\MailMimeParser\Header\Part\MimeLiteralPartFactory
[ "Returns", "the", "MimeLiteralPartFactory", "service" ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Container.php#L257-L263
zbateson/mail-mime-parser
src/Container.php
Container.getConsumerService
public function getConsumerService() { if ($this->consumerService === null) { $this->consumerService = new ConsumerService( $this->getHeaderPartFactory(), $this->getMimeLiteralPartFactory() ); } return $this->consumerService; }
php
public function getConsumerService() { if ($this->consumerService === null) { $this->consumerService = new ConsumerService( $this->getHeaderPartFactory(), $this->getMimeLiteralPartFactory() ); } return $this->consumerService; }
[ "public", "function", "getConsumerService", "(", ")", "{", "if", "(", "$", "this", "->", "consumerService", "===", "null", ")", "{", "$", "this", "->", "consumerService", "=", "new", "ConsumerService", "(", "$", "this", "->", "getHeaderPartFactory", "(", ")"...
Returns the header consumer service @return \ZBateson\MailMimeParser\Header\Consumer\ConsumerService
[ "Returns", "the", "header", "consumer", "service" ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Container.php#L270-L279
zbateson/mail-mime-parser
src/Header/Consumer/IdBaseConsumer.php
IdBaseConsumer.getSubConsumers
protected function getSubConsumers() { return [ $this->consumerService->getCommentConsumer(), $this->consumerService->getQuotedStringConsumer(), $this->consumerService->getIdConsumer() ]; }
php
protected function getSubConsumers() { return [ $this->consumerService->getCommentConsumer(), $this->consumerService->getQuotedStringConsumer(), $this->consumerService->getIdConsumer() ]; }
[ "protected", "function", "getSubConsumers", "(", ")", "{", "return", "[", "$", "this", "->", "consumerService", "->", "getCommentConsumer", "(", ")", ",", "$", "this", "->", "consumerService", "->", "getQuotedStringConsumer", "(", ")", ",", "$", "this", "->", ...
Returns the following as sub-consumers: - \ZBateson\MailMimeParser\Header\Consumer\CommentConsumer - \ZBateson\MailMimeParser\Header\Consumer\QuotedStringConsumer - \ZBateson\MailMimeParser\Header\Consumer\IdConsumer @return AbstractConsumer[] the sub-consumers
[ "Returns", "the", "following", "as", "sub", "-", "consumers", ":", "-", "\\", "ZBateson", "\\", "MailMimeParser", "\\", "Header", "\\", "Consumer", "\\", "CommentConsumer", "-", "\\", "ZBateson", "\\", "MailMimeParser", "\\", "Header", "\\", "Consumer", "\\", ...
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/Consumer/IdBaseConsumer.php#L30-L37
zbateson/mail-mime-parser
src/Header/Consumer/IdBaseConsumer.php
IdBaseConsumer.getPartForToken
protected function getPartForToken($token, $isLiteral) { if (preg_match('/^\s+$/', $token)) { return null; } return $this->partFactory->newLiteralPart($token); }
php
protected function getPartForToken($token, $isLiteral) { if (preg_match('/^\s+$/', $token)) { return null; } return $this->partFactory->newLiteralPart($token); }
[ "protected", "function", "getPartForToken", "(", "$", "token", ",", "$", "isLiteral", ")", "{", "if", "(", "preg_match", "(", "'/^\\s+$/'", ",", "$", "token", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "partFactory", "->", ...
Returns null for whitespace, and LiteralPart for anything else. @param string $token the token @param bool $isLiteral set to true if the token represents a literal - e.g. an escaped token @return \ZBateson\MailMimeParser\Header\Part\HeaderPart|null the constructed header part or null if the token should be ignored
[ "Returns", "null", "for", "whitespace", "and", "LiteralPart", "for", "anything", "else", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/Consumer/IdBaseConsumer.php#L83-L89
zbateson/mail-mime-parser
src/Header/Consumer/IdBaseConsumer.php
IdBaseConsumer.processParts
protected function processParts(array $parts) { return array_values(array_filter($parts, function ($part) { if (empty($part) || $part instanceof CommentPart) { return false; } return true; })); }
php
protected function processParts(array $parts) { return array_values(array_filter($parts, function ($part) { if (empty($part) || $part instanceof CommentPart) { return false; } return true; })); }
[ "protected", "function", "processParts", "(", "array", "$", "parts", ")", "{", "return", "array_values", "(", "array_filter", "(", "$", "parts", ",", "function", "(", "$", "part", ")", "{", "if", "(", "empty", "(", "$", "part", ")", "||", "$", "part", ...
Overridden to filter out any found CommentPart objects. @param \ZBateson\MailMimeParser\Header\Part\HeaderPart[] $parts @return \ZBateson\MailMimeParser\Header\Part\HeaderPart[]
[ "Overridden", "to", "filter", "out", "any", "found", "CommentPart", "objects", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/Consumer/IdBaseConsumer.php#L97-L105
zbateson/mail-mime-parser
src/Header/HeaderContainer.php
HeaderContainer.exists
public function exists($name, $offset = 0) { $s = $this->getNormalizedHeaderName($name); return isset($this->headerMap[$s][$offset]); }
php
public function exists($name, $offset = 0) { $s = $this->getNormalizedHeaderName($name); return isset($this->headerMap[$s][$offset]); }
[ "public", "function", "exists", "(", "$", "name", ",", "$", "offset", "=", "0", ")", "{", "$", "s", "=", "$", "this", "->", "getNormalizedHeaderName", "(", "$", "name", ")", ";", "return", "isset", "(", "$", "this", "->", "headerMap", "[", "$", "s"...
Returns true if the passed header exists in this collection. @param string $name @param int $offset @return boolean
[ "Returns", "true", "if", "the", "passed", "header", "exists", "in", "this", "collection", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/HeaderContainer.php#L83-L87
zbateson/mail-mime-parser
src/Header/HeaderContainer.php
HeaderContainer.get
public function get($name, $offset = 0) { $s = $this->getNormalizedHeaderName($name); if (isset($this->headerMap[$s][$offset])) { return $this->getByIndex($this->headerMap[$s][$offset]); } return null; }
php
public function get($name, $offset = 0) { $s = $this->getNormalizedHeaderName($name); if (isset($this->headerMap[$s][$offset])) { return $this->getByIndex($this->headerMap[$s][$offset]); } return null; }
[ "public", "function", "get", "(", "$", "name", ",", "$", "offset", "=", "0", ")", "{", "$", "s", "=", "$", "this", "->", "getNormalizedHeaderName", "(", "$", "name", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "headerMap", "[", "$", "s"...
Returns the AbstractHeader object for the header with the given $name and at the optional offset (defaulting to the first header in the collection where more than one header with the same name exists). Note that mime headers aren't case sensitive. @param string $name @param int $offset @return \ZBateson\MailMimeParser\Header\AbstractHeader
[ "Returns", "the", "AbstractHeader", "object", "for", "the", "header", "with", "the", "given", "$name", "and", "at", "the", "optional", "offset", "(", "defaulting", "to", "the", "first", "header", "in", "the", "collection", "where", "more", "than", "one", "he...
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/HeaderContainer.php#L100-L107
zbateson/mail-mime-parser
src/Header/HeaderContainer.php
HeaderContainer.getAll
public function getAll($name) { $s = $this->getNormalizedHeaderName($name); $ret = []; if (!empty($this->headerMap[$s])) { foreach ($this->headerMap[$s] as $index) { $ret[] = $this->getByIndex($index); } } return $ret; }
php
public function getAll($name) { $s = $this->getNormalizedHeaderName($name); $ret = []; if (!empty($this->headerMap[$s])) { foreach ($this->headerMap[$s] as $index) { $ret[] = $this->getByIndex($index); } } return $ret; }
[ "public", "function", "getAll", "(", "$", "name", ")", "{", "$", "s", "=", "$", "this", "->", "getNormalizedHeaderName", "(", "$", "name", ")", ";", "$", "ret", "=", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "headerMap", "["...
Returns all headers with the passed name. @param string $name @return \ZBateson\MailMimeParser\Header\AbstractHeader[]
[ "Returns", "all", "headers", "with", "the", "passed", "name", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/HeaderContainer.php#L115-L125
zbateson/mail-mime-parser
src/Header/HeaderContainer.php
HeaderContainer.getByIndex
private function getByIndex($index) { if (!isset($this->headers[$index])) { return null; } if ($this->headerObjects[$index] === null) { $this->headerObjects[$index] = $this->headerFactory->newInstance( $this->headers[$index][0], $this->headers[$index][1] ); } return $this->headerObjects[$index]; }
php
private function getByIndex($index) { if (!isset($this->headers[$index])) { return null; } if ($this->headerObjects[$index] === null) { $this->headerObjects[$index] = $this->headerFactory->newInstance( $this->headers[$index][0], $this->headers[$index][1] ); } return $this->headerObjects[$index]; }
[ "private", "function", "getByIndex", "(", "$", "index", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "headers", "[", "$", "index", "]", ")", ")", "{", "return", "null", ";", "}", "if", "(", "$", "this", "->", "headerObjects", "[", "...
Returns the header in the headers array at the passed 0-based integer index. @param int $index @return \ZBateson\MailMimeParser\Header\AbstractHeader
[ "Returns", "the", "header", "in", "the", "headers", "array", "at", "the", "passed", "0", "-", "based", "integer", "index", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/HeaderContainer.php#L134-L146
zbateson/mail-mime-parser
src/Header/HeaderContainer.php
HeaderContainer.remove
public function remove($name, $offset = 0) { $s = $this->getNormalizedHeaderName($name); if (isset($this->headerMap[$s][$offset])) { $index = $this->headerMap[$s][$offset]; array_splice($this->headerMap[$s], $offset, 1); unset($this->headers[$index]); unset($this->headerObjects[$index]); return true; } return false; }
php
public function remove($name, $offset = 0) { $s = $this->getNormalizedHeaderName($name); if (isset($this->headerMap[$s][$offset])) { $index = $this->headerMap[$s][$offset]; array_splice($this->headerMap[$s], $offset, 1); unset($this->headers[$index]); unset($this->headerObjects[$index]); return true; } return false; }
[ "public", "function", "remove", "(", "$", "name", ",", "$", "offset", "=", "0", ")", "{", "$", "s", "=", "$", "this", "->", "getNormalizedHeaderName", "(", "$", "name", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "headerMap", "[", "$", ...
Removes the header from the collection with the passed name. Defaults to removing the first instance of the header for a collection that contains more than one with the same passed name. @param string $name @param int $offset @return boolean
[ "Removes", "the", "header", "from", "the", "collection", "with", "the", "passed", "name", ".", "Defaults", "to", "removing", "the", "first", "instance", "of", "the", "header", "for", "a", "collection", "that", "contains", "more", "than", "one", "with", "the"...
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/HeaderContainer.php#L157-L168
zbateson/mail-mime-parser
src/Header/HeaderContainer.php
HeaderContainer.removeAll
public function removeAll($name) { $s = $this->getNormalizedHeaderName($name); if (!empty($this->headerMap[$s])) { foreach ($this->headerMap[$s] as $i) { unset($this->headers[$i]); unset($this->headerObjects[$i]); } $this->headerMap[$s] = []; return true; } return false; }
php
public function removeAll($name) { $s = $this->getNormalizedHeaderName($name); if (!empty($this->headerMap[$s])) { foreach ($this->headerMap[$s] as $i) { unset($this->headers[$i]); unset($this->headerObjects[$i]); } $this->headerMap[$s] = []; return true; } return false; }
[ "public", "function", "removeAll", "(", "$", "name", ")", "{", "$", "s", "=", "$", "this", "->", "getNormalizedHeaderName", "(", "$", "name", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "headerMap", "[", "$", "s", "]", ")", ")", "{...
Removes all headers that match the passed name. @param string $name @return boolean
[ "Removes", "all", "headers", "that", "match", "the", "passed", "name", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/HeaderContainer.php#L176-L188
zbateson/mail-mime-parser
src/Header/HeaderContainer.php
HeaderContainer.add
public function add($name, $value) { $s = $this->getNormalizedHeaderName($name); $this->headers[$this->nextIndex] = [ $name, $value ]; $this->headerObjects[$this->nextIndex] = null; if (!isset($this->headerMap[$s])) { $this->headerMap[$s] = []; } array_push($this->headerMap[$s], $this->nextIndex); $this->nextIndex++; }
php
public function add($name, $value) { $s = $this->getNormalizedHeaderName($name); $this->headers[$this->nextIndex] = [ $name, $value ]; $this->headerObjects[$this->nextIndex] = null; if (!isset($this->headerMap[$s])) { $this->headerMap[$s] = []; } array_push($this->headerMap[$s], $this->nextIndex); $this->nextIndex++; }
[ "public", "function", "add", "(", "$", "name", ",", "$", "value", ")", "{", "$", "s", "=", "$", "this", "->", "getNormalizedHeaderName", "(", "$", "name", ")", ";", "$", "this", "->", "headers", "[", "$", "this", "->", "nextIndex", "]", "=", "[", ...
Adds the header to the collection. @param string $name @param string $value
[ "Adds", "the", "header", "to", "the", "collection", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/HeaderContainer.php#L196-L206
zbateson/mail-mime-parser
src/Header/HeaderContainer.php
HeaderContainer.set
public function set($name, $value, $offset = 0) { $s = $this->getNormalizedHeaderName($name); if (!isset($this->headerMap[$s][$offset])) { $this->add($name, $value); return; } $i = $this->headerMap[$s][$offset]; $this->headers[$i] = [ $name, $value ]; $this->headerObjects[$i] = null; }
php
public function set($name, $value, $offset = 0) { $s = $this->getNormalizedHeaderName($name); if (!isset($this->headerMap[$s][$offset])) { $this->add($name, $value); return; } $i = $this->headerMap[$s][$offset]; $this->headers[$i] = [ $name, $value ]; $this->headerObjects[$i] = null; }
[ "public", "function", "set", "(", "$", "name", ",", "$", "value", ",", "$", "offset", "=", "0", ")", "{", "$", "s", "=", "$", "this", "->", "getNormalizedHeaderName", "(", "$", "name", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", ...
If a header exists with the passed name, and at the passed offset if more than one exists, its value is updated. If a header with the passed name doesn't exist at the passed offset, it is created at the next available offset (offset is ignored when adding). @param string $name @param string $value @param int $offset
[ "If", "a", "header", "exists", "with", "the", "passed", "name", "and", "at", "the", "passed", "offset", "if", "more", "than", "one", "exists", "its", "value", "is", "updated", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/HeaderContainer.php#L219-L229
zbateson/mail-mime-parser
src/Message/Part/MimePart.php
MimePart.getCharset
public function getCharset() { $charset = $this->getHeaderParameter('Content-Type', 'charset'); if ($charset === null) { $contentType = $this->getContentType(); if ($contentType === 'text/plain' || $contentType === 'text/html') { return 'ISO-8859-1'; } return null; } return trim(strtoupper($charset)); }
php
public function getCharset() { $charset = $this->getHeaderParameter('Content-Type', 'charset'); if ($charset === null) { $contentType = $this->getContentType(); if ($contentType === 'text/plain' || $contentType === 'text/html') { return 'ISO-8859-1'; } return null; } return trim(strtoupper($charset)); }
[ "public", "function", "getCharset", "(", ")", "{", "$", "charset", "=", "$", "this", "->", "getHeaderParameter", "(", "'Content-Type'", ",", "'charset'", ")", ";", "if", "(", "$", "charset", "===", "null", ")", "{", "$", "contentType", "=", "$", "this", ...
Returns the upper-cased charset of the Content-Type header's charset parameter if set, ISO-8859-1 if the Content-Type is text/plain or text/html and the charset parameter isn't set, or null otherwise. @return string
[ "Returns", "the", "upper", "-", "cased", "charset", "of", "the", "Content", "-", "Type", "header", "s", "charset", "parameter", "if", "set", "ISO", "-", "8859", "-", "1", "if", "the", "Content", "-", "Type", "is", "text", "/", "plain", "or", "text", ...
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Message/Part/MimePart.php#L97-L108
zbateson/mail-mime-parser
src/Message/Part/MimePart.php
MimePart.getContentTransferEncoding
public function getContentTransferEncoding($default = '7bit') { static $translated = [ 'x-uue' => 'x-uuencode', 'uue' => 'x-uuencode', 'uuencode' => 'x-uuencode' ]; $type = strtolower($this->getHeaderValue('Content-Transfer-Encoding', $default)); if (isset($translated[$type])) { return $translated[$type]; } return $type; }
php
public function getContentTransferEncoding($default = '7bit') { static $translated = [ 'x-uue' => 'x-uuencode', 'uue' => 'x-uuencode', 'uuencode' => 'x-uuencode' ]; $type = strtolower($this->getHeaderValue('Content-Transfer-Encoding', $default)); if (isset($translated[$type])) { return $translated[$type]; } return $type; }
[ "public", "function", "getContentTransferEncoding", "(", "$", "default", "=", "'7bit'", ")", "{", "static", "$", "translated", "=", "[", "'x-uue'", "=>", "'x-uuencode'", ",", "'uue'", "=>", "'x-uuencode'", ",", "'uuencode'", "=>", "'x-uuencode'", "]", ";", "$"...
Returns the content-transfer-encoding used for this part, defaulting to '7bit' if not set. @param string $default pass to override the default when not set. @return string
[ "Returns", "the", "content", "-", "transfer", "-", "encoding", "used", "for", "this", "part", "defaulting", "to", "7bit", "if", "not", "set", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Message/Part/MimePart.php#L129-L141
zbateson/mail-mime-parser
src/Message/Part/MimePart.php
MimePart.getPartByContentId
public function getPartByContentId($contentId) { $sanitized = preg_replace('/^\s*<|>\s*$/', '', $contentId); $filter = $this->partFilterFactory->newFilterFromArray([ 'headers' => [ PartFilter::FILTER_INCLUDE => [ 'Content-ID' => $sanitized ] ] ]); return $this->getPart(0, $filter); }
php
public function getPartByContentId($contentId) { $sanitized = preg_replace('/^\s*<|>\s*$/', '', $contentId); $filter = $this->partFilterFactory->newFilterFromArray([ 'headers' => [ PartFilter::FILTER_INCLUDE => [ 'Content-ID' => $sanitized ] ] ]); return $this->getPart(0, $filter); }
[ "public", "function", "getPartByContentId", "(", "$", "contentId", ")", "{", "$", "sanitized", "=", "preg_replace", "(", "'/^\\s*<|>\\s*$/'", ",", "''", ",", "$", "contentId", ")", ";", "$", "filter", "=", "$", "this", "->", "partFilterFactory", "->", "newFi...
Convenience method to find a part by its Content-ID header. @param string $contentId @return MessagePart
[ "Convenience", "method", "to", "find", "a", "part", "by", "its", "Content", "-", "ID", "header", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Message/Part/MimePart.php#L162-L173
zbateson/mail-mime-parser
src/Header/ReceivedHeader.php
ReceivedHeader.setParseHeaderValue
protected function setParseHeaderValue(AbstractConsumer $consumer) { parent::setParseHeaderValue($consumer); foreach ($this->parts as $part) { if ($part instanceof CommentPart) { $this->comments[] = $part->getComment(); } elseif ($part instanceof DatePart) { $this->date = $part->getDateTime(); } } }
php
protected function setParseHeaderValue(AbstractConsumer $consumer) { parent::setParseHeaderValue($consumer); foreach ($this->parts as $part) { if ($part instanceof CommentPart) { $this->comments[] = $part->getComment(); } elseif ($part instanceof DatePart) { $this->date = $part->getDateTime(); } } }
[ "protected", "function", "setParseHeaderValue", "(", "AbstractConsumer", "$", "consumer", ")", "{", "parent", "::", "setParseHeaderValue", "(", "$", "consumer", ")", ";", "foreach", "(", "$", "this", "->", "parts", "as", "$", "part", ")", "{", "if", "(", "...
Overridden to assign comments to $this->comments, and the DateTime to $this->date. @param AbstractConsumer $consumer
[ "Overridden", "to", "assign", "comments", "to", "$this", "-", ">", "comments", "and", "the", "DateTime", "to", "$this", "-", ">", "date", "." ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Header/ReceivedHeader.php#L108-L118
zbateson/mail-mime-parser
src/Message/Helper/MessageHelperService.php
MessageHelperService.getGenericHelper
public function getGenericHelper() { if ($this->genericHelper === null) { $this->genericHelper = new GenericHelper( $this->partFactoryService->getMimePartFactory(), $this->partFactoryService->getUUEncodedPartFactory(), $this->partBuilderFactory ); } return $this->genericHelper; }
php
public function getGenericHelper() { if ($this->genericHelper === null) { $this->genericHelper = new GenericHelper( $this->partFactoryService->getMimePartFactory(), $this->partFactoryService->getUUEncodedPartFactory(), $this->partBuilderFactory ); } return $this->genericHelper; }
[ "public", "function", "getGenericHelper", "(", ")", "{", "if", "(", "$", "this", "->", "genericHelper", "===", "null", ")", "{", "$", "this", "->", "genericHelper", "=", "new", "GenericHelper", "(", "$", "this", "->", "partFactoryService", "->", "getMimePart...
Returns the GenericHelper singleton @return GenericHelper
[ "Returns", "the", "GenericHelper", "singleton" ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Message/Helper/MessageHelperService.php#L70-L80
zbateson/mail-mime-parser
src/Message/Helper/MessageHelperService.php
MessageHelperService.getMultipartHelper
public function getMultipartHelper() { if ($this->multipartHelper === null) { $this->multipartHelper = new MultipartHelper( $this->partFactoryService->getMimePartFactory(), $this->partFactoryService->getUUEncodedPartFactory(), $this->partBuilderFactory, $this->getGenericHelper() ); } return $this->multipartHelper; }
php
public function getMultipartHelper() { if ($this->multipartHelper === null) { $this->multipartHelper = new MultipartHelper( $this->partFactoryService->getMimePartFactory(), $this->partFactoryService->getUUEncodedPartFactory(), $this->partBuilderFactory, $this->getGenericHelper() ); } return $this->multipartHelper; }
[ "public", "function", "getMultipartHelper", "(", ")", "{", "if", "(", "$", "this", "->", "multipartHelper", "===", "null", ")", "{", "$", "this", "->", "multipartHelper", "=", "new", "MultipartHelper", "(", "$", "this", "->", "partFactoryService", "->", "get...
Returns the MultipartHelper singleton @return MultipartHelper
[ "Returns", "the", "MultipartHelper", "singleton" ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Message/Helper/MessageHelperService.php#L87-L98
zbateson/mail-mime-parser
src/Message/Helper/MessageHelperService.php
MessageHelperService.getPrivacyHelper
public function getPrivacyHelper() { if ($this->privacyHelper === null) { $this->privacyHelper = new PrivacyHelper( $this->partFactoryService->getMimePartFactory(), $this->partFactoryService->getUUEncodedPartFactory(), $this->partBuilderFactory, $this->getGenericHelper(), $this->getMultipartHelper() ); } return $this->privacyHelper; }
php
public function getPrivacyHelper() { if ($this->privacyHelper === null) { $this->privacyHelper = new PrivacyHelper( $this->partFactoryService->getMimePartFactory(), $this->partFactoryService->getUUEncodedPartFactory(), $this->partBuilderFactory, $this->getGenericHelper(), $this->getMultipartHelper() ); } return $this->privacyHelper; }
[ "public", "function", "getPrivacyHelper", "(", ")", "{", "if", "(", "$", "this", "->", "privacyHelper", "===", "null", ")", "{", "$", "this", "->", "privacyHelper", "=", "new", "PrivacyHelper", "(", "$", "this", "->", "partFactoryService", "->", "getMimePart...
Returns the PrivacyHelper singleton @return PrivacyHelper
[ "Returns", "the", "PrivacyHelper", "singleton" ]
train
https://github.com/zbateson/mail-mime-parser/blob/63bedd7d71fb3abff2381174a14637c5a4ddaa36/src/Message/Helper/MessageHelperService.php#L105-L117
spatie/laravel-sluggable
src/SlugOptions.php
SlugOptions.generateSlugsFrom
public function generateSlugsFrom($fieldName): self { if (is_string($fieldName)) { $fieldName = [$fieldName]; } $this->generateSlugFrom = $fieldName; return $this; }
php
public function generateSlugsFrom($fieldName): self { if (is_string($fieldName)) { $fieldName = [$fieldName]; } $this->generateSlugFrom = $fieldName; return $this; }
[ "public", "function", "generateSlugsFrom", "(", "$", "fieldName", ")", ":", "self", "{", "if", "(", "is_string", "(", "$", "fieldName", ")", ")", "{", "$", "fieldName", "=", "[", "$", "fieldName", "]", ";", "}", "$", "this", "->", "generateSlugFrom", "...
@param string|array|callable $fieldName @return \Spatie\Sluggable\SlugOptions
[ "@param", "string|array|callable", "$fieldName" ]
train
https://github.com/spatie/laravel-sluggable/blob/1467323aaee9b09e1b09d5b55dfab723be06f931/src/SlugOptions.php#L41-L50
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.add
public function add($id, $name = null, $qty = null, $price = null, array $attributes = []) { $cart = $this->getCart(); $this->event->fire('shopping_cart.adding', [$attributes, $cart]); $row = $this->addRow($id, $name, $qty, $price, $attributes); $cart = $this->getCart(); $this->event->fire('shopping_cart.added', [$attributes, $cart]); return $row; }
php
public function add($id, $name = null, $qty = null, $price = null, array $attributes = []) { $cart = $this->getCart(); $this->event->fire('shopping_cart.adding', [$attributes, $cart]); $row = $this->addRow($id, $name, $qty, $price, $attributes); $cart = $this->getCart(); $this->event->fire('shopping_cart.added', [$attributes, $cart]); return $row; }
[ "public", "function", "add", "(", "$", "id", ",", "$", "name", "=", "null", ",", "$", "qty", "=", "null", ",", "$", "price", "=", "null", ",", "array", "$", "attributes", "=", "[", "]", ")", "{", "$", "cart", "=", "$", "this", "->", "getCart", ...
Add a row to the cart. @param int|string $id Unique ID of the item @param string $name Name of the item @param int $qty Item qty to add to the cart @param float $price Price of one item @param array $attributes Array of additional attributes, such as 'size' or 'color'... @return string
[ "Add", "a", "row", "to", "the", "cart", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L112-L125
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.update
public function update($rawId, $attribute) { if (!$row = $this->get($rawId)) { throw new Exception('Item not found.'); } $cart = $this->getCart(); $this->event->fire('shopping_cart.updating', [$row, $cart]); if (is_array($attribute)) { $raw = $this->updateAttribute($rawId, $attribute); } else { $raw = $this->updateQty($rawId, $attribute); } $this->event->fire('shopping_cart.updated', [$row, $cart]); return $raw; }
php
public function update($rawId, $attribute) { if (!$row = $this->get($rawId)) { throw new Exception('Item not found.'); } $cart = $this->getCart(); $this->event->fire('shopping_cart.updating', [$row, $cart]); if (is_array($attribute)) { $raw = $this->updateAttribute($rawId, $attribute); } else { $raw = $this->updateQty($rawId, $attribute); } $this->event->fire('shopping_cart.updated', [$row, $cart]); return $raw; }
[ "public", "function", "update", "(", "$", "rawId", ",", "$", "attribute", ")", "{", "if", "(", "!", "$", "row", "=", "$", "this", "->", "get", "(", "$", "rawId", ")", ")", "{", "throw", "new", "Exception", "(", "'Item not found.'", ")", ";", "}", ...
Update the quantity of one row of the cart. @param string $rawId The __raw_id of the item you want to update @param int|array $attribute New quantity of the item|Array of attributes to update @return Item|bool
[ "Update", "the", "quantity", "of", "one", "row", "of", "the", "cart", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L135-L154
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.remove
public function remove($rawId) { if (!$row = $this->get($rawId)) { return true; } $cart = $this->getCart(); $this->event->fire('shopping_cart.removing', [$row, $cart]); $cart->forget($rawId); $this->event->fire('shopping_cart.removed', [$row, $cart]); $this->save($cart); return true; }
php
public function remove($rawId) { if (!$row = $this->get($rawId)) { return true; } $cart = $this->getCart(); $this->event->fire('shopping_cart.removing', [$row, $cart]); $cart->forget($rawId); $this->event->fire('shopping_cart.removed', [$row, $cart]); $this->save($cart); return true; }
[ "public", "function", "remove", "(", "$", "rawId", ")", "{", "if", "(", "!", "$", "row", "=", "$", "this", "->", "get", "(", "$", "rawId", ")", ")", "{", "return", "true", ";", "}", "$", "cart", "=", "$", "this", "->", "getCart", "(", ")", ";...
Remove a row from the cart. @param string $rawId The __raw_id of the item @return bool
[ "Remove", "a", "row", "from", "the", "cart", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L163-L180
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.get
public function get($rawId) { $row = $this->getCart()->get($rawId); return is_null($row) ? null : new Item($row); }
php
public function get($rawId) { $row = $this->getCart()->get($rawId); return is_null($row) ? null : new Item($row); }
[ "public", "function", "get", "(", "$", "rawId", ")", "{", "$", "row", "=", "$", "this", "->", "getCart", "(", ")", "->", "get", "(", "$", "rawId", ")", ";", "return", "is_null", "(", "$", "row", ")", "?", "null", ":", "new", "Item", "(", "$", ...
Get a row of the cart by its ID. @param string $rawId The ID of the row to fetch @return Item
[ "Get", "a", "row", "of", "the", "cart", "by", "its", "ID", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L189-L194
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.destroy
public function destroy() { $cart = $this->getCart(); $this->event->fire('shopping_cart.destroying', $cart); $this->save(null); $this->event->fire('shopping_cart.destroyed', $cart); return true; }
php
public function destroy() { $cart = $this->getCart(); $this->event->fire('shopping_cart.destroying', $cart); $this->save(null); $this->event->fire('shopping_cart.destroyed', $cart); return true; }
[ "public", "function", "destroy", "(", ")", "{", "$", "cart", "=", "$", "this", "->", "getCart", "(", ")", ";", "$", "this", "->", "event", "->", "fire", "(", "'shopping_cart.destroying'", ",", "$", "cart", ")", ";", "$", "this", "->", "save", "(", ...
Clean the cart. @return bool
[ "Clean", "the", "cart", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L201-L212
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.totalPrice
public function totalPrice() { $total = 0; $cart = $this->getCart(); if ($cart->isEmpty()) { return $total; } foreach ($cart as $row) { $total += $row->qty * $row->price; } return $total; }
php
public function totalPrice() { $total = 0; $cart = $this->getCart(); if ($cart->isEmpty()) { return $total; } foreach ($cart as $row) { $total += $row->qty * $row->price; } return $total; }
[ "public", "function", "totalPrice", "(", ")", "{", "$", "total", "=", "0", ";", "$", "cart", "=", "$", "this", "->", "getCart", "(", ")", ";", "if", "(", "$", "cart", "->", "isEmpty", "(", ")", ")", "{", "return", "$", "total", ";", "}", "forea...
Return total price of cart. @return
[ "Return", "total", "price", "of", "cart", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L239-L254
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.count
public function count($totalItems = true) { $items = $this->getCart(); if (!$totalItems) { return $items->count(); } $count = 0; foreach ($items as $row) { $count += $row->qty; } return $count; }
php
public function count($totalItems = true) { $items = $this->getCart(); if (!$totalItems) { return $items->count(); } $count = 0; foreach ($items as $row) { $count += $row->qty; } return $count; }
[ "public", "function", "count", "(", "$", "totalItems", "=", "true", ")", "{", "$", "items", "=", "$", "this", "->", "getCart", "(", ")", ";", "if", "(", "!", "$", "totalItems", ")", "{", "return", "$", "items", "->", "count", "(", ")", ";", "}", ...
Get the number of items in the cart. @param bool $totalItems Get all the items (when false, will return the number of rows) @return int
[ "Get", "the", "number", "of", "items", "in", "the", "cart", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L263-L278
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.search
public function search(array $search) { $rows = new Collection(); if (empty($search)) { return $rows; } foreach ($this->getCart() as $item) { if (array_intersect_assoc($item->intersect($search)->toArray(), $search)) { $rows->put($item->__raw_id, $item); } } return $rows; }
php
public function search(array $search) { $rows = new Collection(); if (empty($search)) { return $rows; } foreach ($this->getCart() as $item) { if (array_intersect_assoc($item->intersect($search)->toArray(), $search)) { $rows->put($item->__raw_id, $item); } } return $rows; }
[ "public", "function", "search", "(", "array", "$", "search", ")", "{", "$", "rows", "=", "new", "Collection", "(", ")", ";", "if", "(", "empty", "(", "$", "search", ")", ")", "{", "return", "$", "rows", ";", "}", "foreach", "(", "$", "this", "->"...
Search if the cart has a item. @param array $search An array with the item ID and optional options @return array
[ "Search", "if", "the", "cart", "has", "a", "item", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L297-L312
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.addRow
protected function addRow($id, $name, $qty, $price, array $attributes = []) { if (!is_numeric($qty) || $qty < 1) { throw new Exception('Invalid quantity.'); } if (!is_numeric($price) || $price < 0) { throw new Exception('Invalid price.'); } $cart = $this->getCart(); $rawId = $this->generateRawId($id, $attributes); if ($row = $cart->get($rawId)) { $row = $this->updateQty($rawId, $row->qty + $qty); } else { $row = $this->insertRow($rawId, $id, $name, $qty, $price, $attributes); } return $row; }
php
protected function addRow($id, $name, $qty, $price, array $attributes = []) { if (!is_numeric($qty) || $qty < 1) { throw new Exception('Invalid quantity.'); } if (!is_numeric($price) || $price < 0) { throw new Exception('Invalid price.'); } $cart = $this->getCart(); $rawId = $this->generateRawId($id, $attributes); if ($row = $cart->get($rawId)) { $row = $this->updateQty($rawId, $row->qty + $qty); } else { $row = $this->insertRow($rawId, $id, $name, $qty, $price, $attributes); } return $row; }
[ "protected", "function", "addRow", "(", "$", "id", ",", "$", "name", ",", "$", "qty", ",", "$", "price", ",", "array", "$", "attributes", "=", "[", "]", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "qty", ")", "||", "$", "qty", "<", "1", ...
Add row to the cart. @param string $id Unique ID of the item @param string $name Name of the item @param int $qty Item qty to add to the cart @param float $price Price of one item @param array $attributes Array of additional options, such as 'size' or 'color' @return string
[ "Add", "row", "to", "the", "cart", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L355-L376
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.getCart
protected function getCart() { $cart = $this->session->get($this->name); return $cart instanceof Collection ? $cart : new Collection(); }
php
protected function getCart() { $cart = $this->session->get($this->name); return $cart instanceof Collection ? $cart : new Collection(); }
[ "protected", "function", "getCart", "(", ")", "{", "$", "cart", "=", "$", "this", "->", "session", "->", "get", "(", "$", "this", "->", "name", ")", ";", "return", "$", "cart", "instanceof", "Collection", "?", "$", "cart", ":", "new", "Collection", "...
Get the carts content. @return \Illuminate\Support\Collection
[ "Get", "the", "carts", "content", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L412-L417
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.updateRow
protected function updateRow($rawId, array $attributes) { $cart = $this->getCart(); $row = $cart->get($rawId); foreach ($attributes as $key => $value) { $row->put($key, $value); } if (count(array_intersect(array_keys($attributes), ['qty', 'price']))) { $row->put('total', $row->qty * $row->price); } $cart->put($rawId, $row); return $row; }
php
protected function updateRow($rawId, array $attributes) { $cart = $this->getCart(); $row = $cart->get($rawId); foreach ($attributes as $key => $value) { $row->put($key, $value); } if (count(array_intersect(array_keys($attributes), ['qty', 'price']))) { $row->put('total', $row->qty * $row->price); } $cart->put($rawId, $row); return $row; }
[ "protected", "function", "updateRow", "(", "$", "rawId", ",", "array", "$", "attributes", ")", "{", "$", "cart", "=", "$", "this", "->", "getCart", "(", ")", ";", "$", "row", "=", "$", "cart", "->", "get", "(", "$", "rawId", ")", ";", "foreach", ...
Update a row if the rawId already exists. @param string $rawId The ID of the row to update @param array $attributes The quantity to add to the row @return Item
[ "Update", "a", "row", "if", "the", "rawId", "already", "exists", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L427-L444
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.insertRow
protected function insertRow($rawId, $id, $name, $qty, $price, $attributes = []) { $newRow = $this->makeRow($rawId, $id, $name, $qty, $price, $attributes); $cart = $this->getCart(); $cart->put($rawId, $newRow); $this->save($cart); return $newRow; }
php
protected function insertRow($rawId, $id, $name, $qty, $price, $attributes = []) { $newRow = $this->makeRow($rawId, $id, $name, $qty, $price, $attributes); $cart = $this->getCart(); $cart->put($rawId, $newRow); $this->save($cart); return $newRow; }
[ "protected", "function", "insertRow", "(", "$", "rawId", ",", "$", "id", ",", "$", "name", ",", "$", "qty", ",", "$", "price", ",", "$", "attributes", "=", "[", "]", ")", "{", "$", "newRow", "=", "$", "this", "->", "makeRow", "(", "$", "rawId", ...
Create a new row Object. @param string $rawId The ID of the new row @param string $id Unique ID of the item @param string $name Name of the item @param int $qty Item qty to add to the cart @param float $price Price of one item @param array $attributes Array of additional options, such as 'size' or 'color' @return Item
[ "Create", "a", "new", "row", "Object", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L458-L469
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.makeRow
protected function makeRow($rawId, $id, $name, $qty, $price, array $attributes = []) { return new Item(array_merge([ '__raw_id' => $rawId, 'id' => $id, 'name' => $name, 'qty' => $qty, 'price' => $price, 'total' => $qty * $price, '__model' => $this->model, ], $attributes)); }
php
protected function makeRow($rawId, $id, $name, $qty, $price, array $attributes = []) { return new Item(array_merge([ '__raw_id' => $rawId, 'id' => $id, 'name' => $name, 'qty' => $qty, 'price' => $price, 'total' => $qty * $price, '__model' => $this->model, ], $attributes)); }
[ "protected", "function", "makeRow", "(", "$", "rawId", ",", "$", "id", ",", "$", "name", ",", "$", "qty", ",", "$", "price", ",", "array", "$", "attributes", "=", "[", "]", ")", "{", "return", "new", "Item", "(", "array_merge", "(", "[", "'__raw_id...
Make a row item. @param string $rawId raw id @param mixed $id item id @param string $name item name @param int $qty quantity @param float $price price @param array $attributes other attributes @return Item
[ "Make", "a", "row", "item", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L483-L494
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/Cart.php
Cart.updateQty
protected function updateQty($rawId, $qty) { if ($qty <= 0) { return $this->remove($rawId); } return $this->updateRow($rawId, ['qty' => $qty]); }
php
protected function updateQty($rawId, $qty) { if ($qty <= 0) { return $this->remove($rawId); } return $this->updateRow($rawId, ['qty' => $qty]); }
[ "protected", "function", "updateQty", "(", "$", "rawId", ",", "$", "qty", ")", "{", "if", "(", "$", "qty", "<=", "0", ")", "{", "return", "$", "this", "->", "remove", "(", "$", "rawId", ")", ";", "}", "return", "$", "this", "->", "updateRow", "("...
Update the quantity of a row. @param string $rawId The ID of the row @param int $qty The qty to add @return Item|bool
[ "Update", "the", "quantity", "of", "a", "row", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/Cart.php#L504-L511
overtrue/laravel-shopping-cart
src/LaravelShoppingCart/ServiceProvider.php
ServiceProvider.register
public function register() { $this->app->singleton(Cart::class, function ($app) { return new Cart($app['session'], $app['events']); }); $this->app->alias(Cart::class, 'shopping_cart'); }
php
public function register() { $this->app->singleton(Cart::class, function ($app) { return new Cart($app['session'], $app['events']); }); $this->app->alias(Cart::class, 'shopping_cart'); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "Cart", "::", "class", ",", "function", "(", "$", "app", ")", "{", "return", "new", "Cart", "(", "$", "app", "[", "'session'", "]", ",", "$", "app", ...
Register the service provider.
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/overtrue/laravel-shopping-cart/blob/4121a4c15e224bffba206dde1d10157faef77f94/src/LaravelShoppingCart/ServiceProvider.php#L36-L43
ZzAntares/ProxmoxVE
src/Proxmox.php
Proxmox.requestResource
private function requestResource($actionPath, $params = [], $method = 'GET') { $url = $this->getApiUrl() . $actionPath; $cookies = CookieJar::fromArray([ 'PVEAuthCookie' => $this->authToken->getTicket(), ], $this->credentials->getHostname()); switch ($method) { case 'GET': return $this->httpClient->get($url, [ 'verify' => false, 'exceptions' => false, 'cookies' => $cookies, 'query' => $params, ]); case 'POST': case 'PUT': case 'DELETE': $headers = [ 'CSRFPreventionToken' => $this->authToken->getCsrf(), ]; return $this->httpClient->request($method, $url, [ 'verify' => false, 'exceptions' => false, 'cookies' => $cookies, 'headers' => $headers, 'form_params' => $params, ]); default: $errorMessage = "HTTP Request method {$method} not allowed."; throw new \InvalidArgumentException($errorMessage); } }
php
private function requestResource($actionPath, $params = [], $method = 'GET') { $url = $this->getApiUrl() . $actionPath; $cookies = CookieJar::fromArray([ 'PVEAuthCookie' => $this->authToken->getTicket(), ], $this->credentials->getHostname()); switch ($method) { case 'GET': return $this->httpClient->get($url, [ 'verify' => false, 'exceptions' => false, 'cookies' => $cookies, 'query' => $params, ]); case 'POST': case 'PUT': case 'DELETE': $headers = [ 'CSRFPreventionToken' => $this->authToken->getCsrf(), ]; return $this->httpClient->request($method, $url, [ 'verify' => false, 'exceptions' => false, 'cookies' => $cookies, 'headers' => $headers, 'form_params' => $params, ]); default: $errorMessage = "HTTP Request method {$method} not allowed."; throw new \InvalidArgumentException($errorMessage); } }
[ "private", "function", "requestResource", "(", "$", "actionPath", ",", "$", "params", "=", "[", "]", ",", "$", "method", "=", "'GET'", ")", "{", "$", "url", "=", "$", "this", "->", "getApiUrl", "(", ")", ".", "$", "actionPath", ";", "$", "cookies", ...
Send a request to a given Proxmox API resource. @param string $actionPath The resource tree path you want to request, see more at http://pve.proxmox.com/pve2-api-doc/ @param array $params An associative array filled with params. @param string $method HTTP method used in the request, by default 'GET' method will be used. @return \Psr\Http\Message\ResponseInterface @throws \InvalidArgumentException If the given HTTP method is not one of 'GET', 'POST', 'PUT', 'DELETE',
[ "Send", "a", "request", "to", "a", "given", "Proxmox", "API", "resource", "." ]
train
https://github.com/ZzAntares/ProxmoxVE/blob/87265014f778c93f5e5fc9151314b7105d52049e/src/Proxmox.php#L107-L140
ZzAntares/ProxmoxVE
src/Proxmox.php
Proxmox.processHttpResponse
private function processHttpResponse($response) { if ($response === null) { return null; } switch ($this->fakeType) { case 'pngb64': $base64 = base64_encode($response->getBody()); return 'data:image/png;base64,' . $base64; case 'object': // 'object' not supported yet, we return array instead. case 'array': return json_decode($response->getBody(), true); default: return $response->getBody()->__toString(); } }
php
private function processHttpResponse($response) { if ($response === null) { return null; } switch ($this->fakeType) { case 'pngb64': $base64 = base64_encode($response->getBody()); return 'data:image/png;base64,' . $base64; case 'object': // 'object' not supported yet, we return array instead. case 'array': return json_decode($response->getBody(), true); default: return $response->getBody()->__toString(); } }
[ "private", "function", "processHttpResponse", "(", "$", "response", ")", "{", "if", "(", "$", "response", "===", "null", ")", "{", "return", "null", ";", "}", "switch", "(", "$", "this", "->", "fakeType", ")", "{", "case", "'pngb64'", ":", "$", "base64...
Parses the response to the desired return type. @param \Psr\Http\Message\ResponseInterface $response Response sent by the Proxmox server. @return mixed The parsed response, depending on the response type can be an array or a string.
[ "Parses", "the", "response", "to", "the", "desired", "return", "type", "." ]
train
https://github.com/ZzAntares/ProxmoxVE/blob/87265014f778c93f5e5fc9151314b7105d52049e/src/Proxmox.php#L151-L167
ZzAntares/ProxmoxVE
src/Proxmox.php
Proxmox.login
public function login() { $loginUrl = $this->credentials->getApiUrl() . '/json/access/ticket'; $response = $this->httpClient->post($loginUrl, [ 'verify' => false, 'exceptions' => false, 'form_params' => [ 'username' => $this->credentials->getUsername(), 'password' => $this->credentials->getPassword(), 'realm' => $this->credentials->getRealm(), ], ]); $json = json_decode($response->getBody(), true); if (!$json['data']) { $error = 'Can not login using credentials: ' . $this->credentials; throw new AuthenticationException($error); } return new AuthToken( $json['data']['CSRFPreventionToken'], $json['data']['ticket'], $json['data']['username'] ); }
php
public function login() { $loginUrl = $this->credentials->getApiUrl() . '/json/access/ticket'; $response = $this->httpClient->post($loginUrl, [ 'verify' => false, 'exceptions' => false, 'form_params' => [ 'username' => $this->credentials->getUsername(), 'password' => $this->credentials->getPassword(), 'realm' => $this->credentials->getRealm(), ], ]); $json = json_decode($response->getBody(), true); if (!$json['data']) { $error = 'Can not login using credentials: ' . $this->credentials; throw new AuthenticationException($error); } return new AuthToken( $json['data']['CSRFPreventionToken'], $json['data']['ticket'], $json['data']['username'] ); }
[ "public", "function", "login", "(", ")", "{", "$", "loginUrl", "=", "$", "this", "->", "credentials", "->", "getApiUrl", "(", ")", ".", "'/json/access/ticket'", ";", "$", "response", "=", "$", "this", "->", "httpClient", "->", "post", "(", "$", "loginUrl...
Attempts to login using set credentials, if succeeded will return the AuthToken used in all requests. @return \ProxmoxVE\AuthToken When successful login will return an instance of the AuthToken class. @throws \ProxmoxVE\Exception\AuthenticationException If login fails.
[ "Attempts", "to", "login", "using", "set", "credentials", "if", "succeeded", "will", "return", "the", "AuthToken", "used", "in", "all", "requests", "." ]
train
https://github.com/ZzAntares/ProxmoxVE/blob/87265014f778c93f5e5fc9151314b7105d52049e/src/Proxmox.php#L191-L216
ZzAntares/ProxmoxVE
src/Proxmox.php
Proxmox.setCredentials
public function setCredentials($credentials) { if (!$credentials instanceof Credentials) { $credentials = new Credentials($credentials); } $this->credentials = $credentials; $this->authToken = $this->login(); }
php
public function setCredentials($credentials) { if (!$credentials instanceof Credentials) { $credentials = new Credentials($credentials); } $this->credentials = $credentials; $this->authToken = $this->login(); }
[ "public", "function", "setCredentials", "(", "$", "credentials", ")", "{", "if", "(", "!", "$", "credentials", "instanceof", "Credentials", ")", "{", "$", "credentials", "=", "new", "Credentials", "(", "$", "credentials", ")", ";", "}", "$", "this", "->", ...
Assign the passed Credentials object to the ProxmoxVE. @param object $credentials A custom object holding credentials or a Credentials object to assign. @throws \ProxmoxVE\Exception\AuthenticationException If can not login.
[ "Assign", "the", "passed", "Credentials", "object", "to", "the", "ProxmoxVE", "." ]
train
https://github.com/ZzAntares/ProxmoxVE/blob/87265014f778c93f5e5fc9151314b7105d52049e/src/Proxmox.php#L239-L247
ZzAntares/ProxmoxVE
src/Proxmox.php
Proxmox.setResponseType
public function setResponseType($responseType = 'array') { $supportedFormats = array('json', 'html', 'extjs', 'text', 'png'); if (in_array($responseType, $supportedFormats)) { $this->fakeType = false; $this->responseType = $responseType; } else { switch ($responseType) { case 'pngb64': $this->fakeType = 'pngb64'; $this->responseType = 'png'; break; case 'object': case 'array': $this->responseType = 'json'; $this->fakeType = $responseType; break; default: $this->responseType = 'json'; $this->fakeType = 'array'; // Default format } } }
php
public function setResponseType($responseType = 'array') { $supportedFormats = array('json', 'html', 'extjs', 'text', 'png'); if (in_array($responseType, $supportedFormats)) { $this->fakeType = false; $this->responseType = $responseType; } else { switch ($responseType) { case 'pngb64': $this->fakeType = 'pngb64'; $this->responseType = 'png'; break; case 'object': case 'array': $this->responseType = 'json'; $this->fakeType = $responseType; break; default: $this->responseType = 'json'; $this->fakeType = 'array'; // Default format } } }
[ "public", "function", "setResponseType", "(", "$", "responseType", "=", "'array'", ")", "{", "$", "supportedFormats", "=", "array", "(", "'json'", ",", "'html'", ",", "'extjs'", ",", "'text'", ",", "'png'", ")", ";", "if", "(", "in_array", "(", "$", "res...
Sets the response type that is going to be returned when doing requests. @param string $responseType One of json, html, extjs, text, png.
[ "Sets", "the", "response", "type", "that", "is", "going", "to", "be", "returned", "when", "doing", "requests", "." ]
train
https://github.com/ZzAntares/ProxmoxVE/blob/87265014f778c93f5e5fc9151314b7105d52049e/src/Proxmox.php#L255-L278
ZzAntares/ProxmoxVE
src/Proxmox.php
Proxmox.get
public function get($actionPath, $params = []) { if (!is_array($params)) { $errorMessage = 'GET params should be an associative array.'; throw new \InvalidArgumentException($errorMessage); } // Check if we have a prefixed '/' on the path, if not add one. if (substr($actionPath, 0, 1) != '/') { $actionPath = '/' . $actionPath; } $response = $this->requestResource($actionPath, $params); return $this->processHttpResponse($response); }
php
public function get($actionPath, $params = []) { if (!is_array($params)) { $errorMessage = 'GET params should be an associative array.'; throw new \InvalidArgumentException($errorMessage); } // Check if we have a prefixed '/' on the path, if not add one. if (substr($actionPath, 0, 1) != '/') { $actionPath = '/' . $actionPath; } $response = $this->requestResource($actionPath, $params); return $this->processHttpResponse($response); }
[ "public", "function", "get", "(", "$", "actionPath", ",", "$", "params", "=", "[", "]", ")", "{", "if", "(", "!", "is_array", "(", "$", "params", ")", ")", "{", "$", "errorMessage", "=", "'GET params should be an associative array.'", ";", "throw", "new", ...
GET a resource defined in the pvesh tool. @param string $actionPath The resource tree path you want to ask for, see more at http://pve.proxmox.com/pve2-api-doc/ @param array $params An associative array filled with params. @return array A PHP array json_decode($response, true). @throws \InvalidArgumentException If given params are not an array.
[ "GET", "a", "resource", "defined", "in", "the", "pvesh", "tool", "." ]
train
https://github.com/ZzAntares/ProxmoxVE/blob/87265014f778c93f5e5fc9151314b7105d52049e/src/Proxmox.php#L303-L317
ZzAntares/ProxmoxVE
src/Proxmox.php
Proxmox.getStorages
public function getStorages($type = null) { if ($type === null) { return $this->get('/storage'); } $supportedTypes = array( 'lvm', 'nfs', 'dir', 'zfs', 'rbd', 'iscsi', 'sheepdog', 'glusterfs', 'iscsidirect', ); if (in_array($type, $supportedTypes)) { return $this->get('/storage', array( 'type' => $type, )); } /* If type not found returns null */ return null; }
php
public function getStorages($type = null) { if ($type === null) { return $this->get('/storage'); } $supportedTypes = array( 'lvm', 'nfs', 'dir', 'zfs', 'rbd', 'iscsi', 'sheepdog', 'glusterfs', 'iscsidirect', ); if (in_array($type, $supportedTypes)) { return $this->get('/storage', array( 'type' => $type, )); } /* If type not found returns null */ return null; }
[ "public", "function", "getStorages", "(", "$", "type", "=", "null", ")", "{", "if", "(", "$", "type", "===", "null", ")", "{", "return", "$", "this", "->", "get", "(", "'/storage'", ")", ";", "}", "$", "supportedTypes", "=", "array", "(", "'lvm'", ...
Retrieves all the storage found in the Proxmox server, or only the ones matching the storage type provided if any. @param string $type the storage type. @return mixed The processed response, can be an array, string or object.
[ "Retrieves", "all", "the", "storage", "found", "in", "the", "Proxmox", "server", "or", "only", "the", "ones", "matching", "the", "storage", "type", "provided", "if", "any", "." ]
train
https://github.com/ZzAntares/ProxmoxVE/blob/87265014f778c93f5e5fc9151314b7105d52049e/src/Proxmox.php#L488-L514
ZzAntares/ProxmoxVE
src/Proxmox.php
Proxmox.createStorage
public function createStorage($storageData) { if (!is_array($storageData)) { $errorMessage = 'Storage data needs to be array'; throw new \InvalidArgumentException($errorMessage); } /* Should we check the required keys (storage, type) in the array? */ return $this->create('/storage', $storageData); }
php
public function createStorage($storageData) { if (!is_array($storageData)) { $errorMessage = 'Storage data needs to be array'; throw new \InvalidArgumentException($errorMessage); } /* Should we check the required keys (storage, type) in the array? */ return $this->create('/storage', $storageData); }
[ "public", "function", "createStorage", "(", "$", "storageData", ")", "{", "if", "(", "!", "is_array", "(", "$", "storageData", ")", ")", "{", "$", "errorMessage", "=", "'Storage data needs to be array'", ";", "throw", "new", "\\", "InvalidArgumentException", "("...
Creates a storage resource using the passed data. @param array $storageData An associative array filled with POST params @return mixed The processed response, can be an array, string or object.
[ "Creates", "a", "storage", "resource", "using", "the", "passed", "data", "." ]
train
https://github.com/ZzAntares/ProxmoxVE/blob/87265014f778c93f5e5fc9151314b7105d52049e/src/Proxmox.php#L524-L534
ZzAntares/ProxmoxVE
src/Credentials.php
Credentials.parseCustomCredentials
public function parseCustomCredentials($credentials) { if (is_array($credentials)) { $requiredKeys = ['hostname', 'username', 'password']; $credentialsKeys = array_keys($credentials); $found = count(array_intersect($requiredKeys, $credentialsKeys)); if ($found != count($requiredKeys)) { return null; } // Set default realm and port if are not in the array. if (!isset($credentials['realm'])) { $credentials['realm'] = 'pam'; } if (!isset($credentials['port'])) { $credentials['port'] = '8006'; } return $credentials; } if (!is_object($credentials)) { return null; } // Trying to find variables $objectProperties = array_keys(get_object_vars($credentials)); $requiredProperties = ['hostname', 'username', 'password']; // Needed properties exists in the object? $found = count(array_intersect($requiredProperties, $objectProperties)); if ($found == count($requiredProperties)) { $realm = in_array('realm', $objectProperties) ? $credentials->realm : 'pam'; $port = in_array('port', $objectProperties) ? $credentials->port : '8006'; return [ 'hostname' => $credentials->hostname, 'username' => $credentials->username, 'password' => $credentials->password, 'realm' => $realm, 'port' => $port, ]; } // Trying to find getters $objectMethods = get_class_methods($credentials); $requiredMethods = ['getHostname', 'getUsername', 'getPassword']; // Needed functions exists in the object? $found = count(array_intersect($requiredMethods, $objectMethods)); if ($found == count($requiredMethods)) { $realm = method_exists($credentials, 'getRealm') ? $credentials->getRealm() : 'pam'; $port = method_exists($credentials, 'getPort') ? $credentials->getPort() : '8006'; return [ 'hostname' => $credentials->getHostname(), 'username' => $credentials->getUsername(), 'password' => $credentials->getPassword(), 'realm' => $realm, 'port' => $port, ]; } // Get properties of object using magic method __get if (in_array('__get', $objectMethods)) { $hasHostname = $credentials->hostname; $hasUsername = $credentials->username; $hasPassword = $credentials->password; if ($hasHostname and $hasUsername and $hasPassword) { return [ 'hostname' => $credentials->hostname, 'username' => $credentials->username, 'password' => $credentials->password, 'realm' => $credentials->realm ?: 'pam', 'port' => $credentials->port ?: '8006', ]; } } return null; }
php
public function parseCustomCredentials($credentials) { if (is_array($credentials)) { $requiredKeys = ['hostname', 'username', 'password']; $credentialsKeys = array_keys($credentials); $found = count(array_intersect($requiredKeys, $credentialsKeys)); if ($found != count($requiredKeys)) { return null; } // Set default realm and port if are not in the array. if (!isset($credentials['realm'])) { $credentials['realm'] = 'pam'; } if (!isset($credentials['port'])) { $credentials['port'] = '8006'; } return $credentials; } if (!is_object($credentials)) { return null; } // Trying to find variables $objectProperties = array_keys(get_object_vars($credentials)); $requiredProperties = ['hostname', 'username', 'password']; // Needed properties exists in the object? $found = count(array_intersect($requiredProperties, $objectProperties)); if ($found == count($requiredProperties)) { $realm = in_array('realm', $objectProperties) ? $credentials->realm : 'pam'; $port = in_array('port', $objectProperties) ? $credentials->port : '8006'; return [ 'hostname' => $credentials->hostname, 'username' => $credentials->username, 'password' => $credentials->password, 'realm' => $realm, 'port' => $port, ]; } // Trying to find getters $objectMethods = get_class_methods($credentials); $requiredMethods = ['getHostname', 'getUsername', 'getPassword']; // Needed functions exists in the object? $found = count(array_intersect($requiredMethods, $objectMethods)); if ($found == count($requiredMethods)) { $realm = method_exists($credentials, 'getRealm') ? $credentials->getRealm() : 'pam'; $port = method_exists($credentials, 'getPort') ? $credentials->getPort() : '8006'; return [ 'hostname' => $credentials->getHostname(), 'username' => $credentials->getUsername(), 'password' => $credentials->getPassword(), 'realm' => $realm, 'port' => $port, ]; } // Get properties of object using magic method __get if (in_array('__get', $objectMethods)) { $hasHostname = $credentials->hostname; $hasUsername = $credentials->username; $hasPassword = $credentials->password; if ($hasHostname and $hasUsername and $hasPassword) { return [ 'hostname' => $credentials->hostname, 'username' => $credentials->username, 'password' => $credentials->password, 'realm' => $credentials->realm ?: 'pam', 'port' => $credentials->port ?: '8006', ]; } } return null; }
[ "public", "function", "parseCustomCredentials", "(", "$", "credentials", ")", "{", "if", "(", "is_array", "(", "$", "credentials", ")", ")", "{", "$", "requiredKeys", "=", "[", "'hostname'", ",", "'username'", ",", "'password'", "]", ";", "$", "credentialsKe...
Given the custom credentials object it will try to find the required values to use it as the proxmox credentials, this can be an object with accesible properties, getter methods or an object that uses '__get' to access properties dinamically. @param mixed $credentials @return array|null If credentials are found they are returned as an associative array, returns null if object can not be used as a credentials provider.
[ "Given", "the", "custom", "credentials", "object", "it", "will", "try", "to", "find", "the", "required", "values", "to", "use", "it", "as", "the", "proxmox", "credentials", "this", "can", "be", "an", "object", "with", "accesible", "properties", "getter", "me...
train
https://github.com/ZzAntares/ProxmoxVE/blob/87265014f778c93f5e5fc9151314b7105d52049e/src/Credentials.php#L166-L261
sfelix-martins/passport-multiauth
src/Http/Middleware/AddCustomProvider.php
AddCustomProvider.handle
public function handle(Request $request, Closure $next) { $this->defaultApiProvider = config('auth.guards.api.provider'); $provider = $request->get('provider'); if ($this->invalidProvider($provider)) { throw OAuthServerException::invalidRequest('provider'); } config(['auth.guards.api.provider' => $provider]); return $next($request); }
php
public function handle(Request $request, Closure $next) { $this->defaultApiProvider = config('auth.guards.api.provider'); $provider = $request->get('provider'); if ($this->invalidProvider($provider)) { throw OAuthServerException::invalidRequest('provider'); } config(['auth.guards.api.provider' => $provider]); return $next($request); }
[ "public", "function", "handle", "(", "Request", "$", "request", ",", "Closure", "$", "next", ")", "{", "$", "this", "->", "defaultApiProvider", "=", "config", "(", "'auth.guards.api.provider'", ")", ";", "$", "provider", "=", "$", "request", "->", "get", "...
Handle an incoming request. Set the `provider` from `api` guard using a parameter `provider` coming from request. The provider on `apì` guard is used by Laravel Passport to get the correct model on access token creation. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed @throws OAuthServerException
[ "Handle", "an", "incoming", "request", ".", "Set", "the", "provider", "from", "api", "guard", "using", "a", "parameter", "provider", "coming", "from", "request", ".", "The", "provider", "on", "apì", "guard", "is", "used", "by", "Laravel", "Passport", "to", ...
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Http/Middleware/AddCustomProvider.php#L31-L44
sfelix-martins/passport-multiauth
src/Http/Middleware/AddCustomProvider.php
AddCustomProvider.invalidProvider
protected function invalidProvider($provider) { if (is_null($provider)) { return true; } foreach (config('auth.guards') as $guardsConfiguration) { if ($guardsConfiguration['provider'] === $provider) { return false; } } return true; }
php
protected function invalidProvider($provider) { if (is_null($provider)) { return true; } foreach (config('auth.guards') as $guardsConfiguration) { if ($guardsConfiguration['provider'] === $provider) { return false; } } return true; }
[ "protected", "function", "invalidProvider", "(", "$", "provider", ")", "{", "if", "(", "is_null", "(", "$", "provider", ")", ")", "{", "return", "true", ";", "}", "foreach", "(", "config", "(", "'auth.guards'", ")", "as", "$", "guardsConfiguration", ")", ...
Check if the given provider is not registered in the auth configuration file. @param $provider @return bool
[ "Check", "if", "the", "given", "provider", "is", "not", "registered", "in", "the", "auth", "configuration", "file", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Http/Middleware/AddCustomProvider.php#L67-L80
sfelix-martins/passport-multiauth
src/Guards/GuardChecker.php
GuardChecker.getAuthGuards
public static function getAuthGuards(Request $request) { $middlewares = $request->route()->middleware(); $guards = []; foreach ($middlewares as $middleware) { if (Str::startsWith($middleware, 'auth')) { $explodedGuards = explode(',', Str::after($middleware, ':')); $guards = array_unique(array_merge($guards, $explodedGuards)); } } return $guards; }
php
public static function getAuthGuards(Request $request) { $middlewares = $request->route()->middleware(); $guards = []; foreach ($middlewares as $middleware) { if (Str::startsWith($middleware, 'auth')) { $explodedGuards = explode(',', Str::after($middleware, ':')); $guards = array_unique(array_merge($guards, $explodedGuards)); } } return $guards; }
[ "public", "static", "function", "getAuthGuards", "(", "Request", "$", "request", ")", "{", "$", "middlewares", "=", "$", "request", "->", "route", "(", ")", "->", "middleware", "(", ")", ";", "$", "guards", "=", "[", "]", ";", "foreach", "(", "$", "m...
Get guards passed as parameters to `auth` middleware. @param \Illuminate\Http\Request $request @return array
[ "Get", "guards", "passed", "as", "parameters", "to", "auth", "middleware", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Guards/GuardChecker.php#L17-L30
sfelix-martins/passport-multiauth
src/Guards/GuardChecker.php
GuardChecker.getGuardsProviders
public static function getGuardsProviders($guards) { return collect($guards)->mapWithKeys(function ($guard) { return [GuardChecker::defaultGuardProvider($guard) => $guard]; }); }
php
public static function getGuardsProviders($guards) { return collect($guards)->mapWithKeys(function ($guard) { return [GuardChecker::defaultGuardProvider($guard) => $guard]; }); }
[ "public", "static", "function", "getGuardsProviders", "(", "$", "guards", ")", "{", "return", "collect", "(", "$", "guards", ")", "->", "mapWithKeys", "(", "function", "(", "$", "guard", ")", "{", "return", "[", "GuardChecker", "::", "defaultGuardProvider", ...
Get guards provider returning a assoc array with provider on key and guard on value. @param array $guards @return Collection
[ "Get", "guards", "provider", "returning", "a", "assoc", "array", "with", "provider", "on", "key", "and", "guard", "on", "value", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Guards/GuardChecker.php#L39-L44
sfelix-martins/passport-multiauth
src/Providers/MultiauthServiceProvider.php
MultiauthServiceProvider.boot
public function boot(ProviderRepository $providers) { if ($this->app->runningInConsole()) { $this->registerMigrations(); } $this->createAccessTokenProvider($providers); // Register the middleware as singleton to use the same middleware // instance when the handle and terminate methods are called. $this->app->singleton(\SMartins\PassportMultiauth\Http\Middleware\AddCustomProvider::class); }
php
public function boot(ProviderRepository $providers) { if ($this->app->runningInConsole()) { $this->registerMigrations(); } $this->createAccessTokenProvider($providers); // Register the middleware as singleton to use the same middleware // instance when the handle and terminate methods are called. $this->app->singleton(\SMartins\PassportMultiauth\Http\Middleware\AddCustomProvider::class); }
[ "public", "function", "boot", "(", "ProviderRepository", "$", "providers", ")", "{", "if", "(", "$", "this", "->", "app", "->", "runningInConsole", "(", ")", ")", "{", "$", "this", "->", "registerMigrations", "(", ")", ";", "}", "$", "this", "->", "cre...
Bootstrap any application services. @return void
[ "Bootstrap", "any", "application", "services", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Providers/MultiauthServiceProvider.php#L17-L28
sfelix-martins/passport-multiauth
src/Providers/MultiauthServiceProvider.php
MultiauthServiceProvider.registerMigrations
protected function registerMigrations() { $migrationsPath = __DIR__.'/../../database/migrations'; $this->loadMigrationsFrom($migrationsPath); $this->publishes( [$migrationsPath => database_path('migrations')], 'migrations' ); }
php
protected function registerMigrations() { $migrationsPath = __DIR__.'/../../database/migrations'; $this->loadMigrationsFrom($migrationsPath); $this->publishes( [$migrationsPath => database_path('migrations')], 'migrations' ); }
[ "protected", "function", "registerMigrations", "(", ")", "{", "$", "migrationsPath", "=", "__DIR__", ".", "'/../../database/migrations'", ";", "$", "this", "->", "loadMigrationsFrom", "(", "$", "migrationsPath", ")", ";", "$", "this", "->", "publishes", "(", "["...
Register migrations to work on `php artisan migrate` command. @return void
[ "Register", "migrations", "to", "work", "on", "php", "artisan", "migrate", "command", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Providers/MultiauthServiceProvider.php#L35-L45
sfelix-martins/passport-multiauth
src/Providers/MultiauthServiceProvider.php
MultiauthServiceProvider.createAccessTokenProvider
protected function createAccessTokenProvider(ProviderRepository $repository) { Event::listen(AccessTokenCreated::class, function ($event) use ($repository) { $provider = config('auth.guards.api.provider'); $repository->create($event->tokenId, $provider); }); }
php
protected function createAccessTokenProvider(ProviderRepository $repository) { Event::listen(AccessTokenCreated::class, function ($event) use ($repository) { $provider = config('auth.guards.api.provider'); $repository->create($event->tokenId, $provider); }); }
[ "protected", "function", "createAccessTokenProvider", "(", "ProviderRepository", "$", "repository", ")", "{", "Event", "::", "listen", "(", "AccessTokenCreated", "::", "class", ",", "function", "(", "$", "event", ")", "use", "(", "$", "repository", ")", "{", "...
Create access token provider when access token is created. @param ProviderRepository $repository @return void
[ "Create", "access", "token", "provider", "when", "access", "token", "is", "created", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Providers/MultiauthServiceProvider.php#L53-L60
sfelix-martins/passport-multiauth
src/ProviderRepository.php
ProviderRepository.create
public function create($token, $provider) { $provider = (new Provider)->forceFill([ 'oauth_access_token_id' => $token, 'provider' => $provider, 'created_at' => new Carbon(), 'updated_at' => new Carbon(), ]); $provider->save(); return $provider; }
php
public function create($token, $provider) { $provider = (new Provider)->forceFill([ 'oauth_access_token_id' => $token, 'provider' => $provider, 'created_at' => new Carbon(), 'updated_at' => new Carbon(), ]); $provider->save(); return $provider; }
[ "public", "function", "create", "(", "$", "token", ",", "$", "provider", ")", "{", "$", "provider", "=", "(", "new", "Provider", ")", "->", "forceFill", "(", "[", "'oauth_access_token_id'", "=>", "$", "token", ",", "'provider'", "=>", "$", "provider", ",...
Store new register on `oauth_access_token_providers` table. @param string $token @param string $provider @return \SMartins\PassportMultiauth\Provider
[ "Store", "new", "register", "on", "oauth_access_token_providers", "table", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/ProviderRepository.php#L27-L39
sfelix-martins/passport-multiauth
src/Config/AuthConfigHelper.php
AuthConfigHelper.getUserProvider
public static function getUserProvider(Authenticatable $user) { foreach (config('auth.providers') as $provider => $config) { if ($user instanceof $config['model']) { return $provider; } } throw MissingConfigException::provider($user); }
php
public static function getUserProvider(Authenticatable $user) { foreach (config('auth.providers') as $provider => $config) { if ($user instanceof $config['model']) { return $provider; } } throw MissingConfigException::provider($user); }
[ "public", "static", "function", "getUserProvider", "(", "Authenticatable", "$", "user", ")", "{", "foreach", "(", "config", "(", "'auth.providers'", ")", "as", "$", "provider", "=>", "$", "config", ")", "{", "if", "(", "$", "user", "instanceof", "$", "conf...
Get the user provider on configs. @param Authenticatable $user @return string|null @throws MissingConfigException
[ "Get", "the", "user", "provider", "on", "configs", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Config/AuthConfigHelper.php#L17-L26
sfelix-martins/passport-multiauth
src/Config/AuthConfigHelper.php
AuthConfigHelper.getProviderGuard
public static function getProviderGuard($provider, Authenticatable $user) { foreach (config('auth.guards') as $guard => $content) { if ($content['driver'] == 'passport' && $content['provider'] == $provider) { return $guard; } } throw MissingConfigException::guard($user); }
php
public static function getProviderGuard($provider, Authenticatable $user) { foreach (config('auth.guards') as $guard => $content) { if ($content['driver'] == 'passport' && $content['provider'] == $provider) { return $guard; } } throw MissingConfigException::guard($user); }
[ "public", "static", "function", "getProviderGuard", "(", "$", "provider", ",", "Authenticatable", "$", "user", ")", "{", "foreach", "(", "config", "(", "'auth.guards'", ")", "as", "$", "guard", "=>", "$", "content", ")", "{", "if", "(", "$", "content", "...
Get the guard of specific provider to `passport` driver. @param string $provider @param Authenticatable $user @return string @throws MissingConfigException
[ "Get", "the", "guard", "of", "specific", "provider", "to", "passport", "driver", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Config/AuthConfigHelper.php#L36-L45
sfelix-martins/passport-multiauth
src/Config/AuthConfigHelper.php
AuthConfigHelper.getUserGuard
public static function getUserGuard(Authenticatable $user) { $provider = self::getUserProvider($user); return self::getProviderGuard($provider, $user); }
php
public static function getUserGuard(Authenticatable $user) { $provider = self::getUserProvider($user); return self::getProviderGuard($provider, $user); }
[ "public", "static", "function", "getUserGuard", "(", "Authenticatable", "$", "user", ")", "{", "$", "provider", "=", "self", "::", "getUserProvider", "(", "$", "user", ")", ";", "return", "self", "::", "getProviderGuard", "(", "$", "provider", ",", "$", "u...
Get the user guard on provider with `passport` driver. @param Authenticatable $user @return string|null @throws MissingConfigException
[ "Get", "the", "user", "guard", "on", "provider", "with", "passport", "driver", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Config/AuthConfigHelper.php#L54-L59
sfelix-martins/passport-multiauth
src/PassportMultiauth.php
PassportMultiauth.actingAs
public static function actingAs($user, $scopes = []) { $token = Mockery::mock(Token::class)->shouldIgnoreMissing(false); foreach ($scopes as $scope) { $token->shouldReceive('can')->with($scope)->andReturn(true); } $uses = array_flip(class_uses_recursive($user)); if (! isset($uses[HasApiTokens::class])) { throw new Exception('The model ['.get_class($user).'] must uses the trait '.HasApiTokens::class); } $user->withAccessToken($token); $guard = AuthConfigHelper::getUserGuard($user); app('auth')->guard($guard)->setUser($user); app('auth')->shouldUse($guard); }
php
public static function actingAs($user, $scopes = []) { $token = Mockery::mock(Token::class)->shouldIgnoreMissing(false); foreach ($scopes as $scope) { $token->shouldReceive('can')->with($scope)->andReturn(true); } $uses = array_flip(class_uses_recursive($user)); if (! isset($uses[HasApiTokens::class])) { throw new Exception('The model ['.get_class($user).'] must uses the trait '.HasApiTokens::class); } $user->withAccessToken($token); $guard = AuthConfigHelper::getUserGuard($user); app('auth')->guard($guard)->setUser($user); app('auth')->shouldUse($guard); }
[ "public", "static", "function", "actingAs", "(", "$", "user", ",", "$", "scopes", "=", "[", "]", ")", "{", "$", "token", "=", "Mockery", "::", "mock", "(", "Token", "::", "class", ")", "->", "shouldIgnoreMissing", "(", "false", ")", ";", "foreach", "...
Set the current user for the application with the given scopes. @param \Illuminate\Contracts\Auth\Authenticatable $user @param array $scopes @return void @throws Exception
[ "Set", "the", "current", "user", "for", "the", "application", "with", "the", "given", "scopes", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/PassportMultiauth.php#L22-L43
sfelix-martins/passport-multiauth
src/HasMultiAuthApiTokens.php
HasMultiAuthApiTokens.tokens
public function tokens() { return $this->hasMany(Token::class, 'user_id') ->join('oauth_access_token_providers', function ($join) { $join->on( 'oauth_access_tokens.id', '=', 'oauth_access_token_id' )->where('oauth_access_token_providers.provider', '=', AuthConfigHelper::getUserProvider($this)); })->orderBy('created_at', 'desc') ->select('oauth_access_tokens.*') ->get(); }
php
public function tokens() { return $this->hasMany(Token::class, 'user_id') ->join('oauth_access_token_providers', function ($join) { $join->on( 'oauth_access_tokens.id', '=', 'oauth_access_token_id' )->where('oauth_access_token_providers.provider', '=', AuthConfigHelper::getUserProvider($this)); })->orderBy('created_at', 'desc') ->select('oauth_access_tokens.*') ->get(); }
[ "public", "function", "tokens", "(", ")", "{", "return", "$", "this", "->", "hasMany", "(", "Token", "::", "class", ",", "'user_id'", ")", "->", "join", "(", "'oauth_access_token_providers'", ",", "function", "(", "$", "join", ")", "{", "$", "join", "->"...
Get all of the access tokens for the user relating with Provider. @return \Illuminate\Database\Eloquent\Collection
[ "Get", "all", "of", "the", "access", "tokens", "for", "the", "user", "relating", "with", "Provider", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/HasMultiAuthApiTokens.php#L22-L32
sfelix-martins/passport-multiauth
src/HasMultiAuthApiTokens.php
HasMultiAuthApiTokens.createToken
public function createToken($name, array $scopes = []) { // Backup default provider $defaultProvider = config('auth.guards.api.provider'); $userProvider = AuthConfigHelper::getUserProvider($this); // Change config to when the token is created set the provider from model creating the token. config(['auth.guards.api.provider' => $userProvider]); $token = Container::getInstance()->make(PersonalAccessTokenFactory::class)->make( $this->getKey(), $name, $scopes ); // Reset config to defaults config(['auth.guards.api.provider' => $defaultProvider]); return $token; }
php
public function createToken($name, array $scopes = []) { // Backup default provider $defaultProvider = config('auth.guards.api.provider'); $userProvider = AuthConfigHelper::getUserProvider($this); // Change config to when the token is created set the provider from model creating the token. config(['auth.guards.api.provider' => $userProvider]); $token = Container::getInstance()->make(PersonalAccessTokenFactory::class)->make( $this->getKey(), $name, $scopes ); // Reset config to defaults config(['auth.guards.api.provider' => $defaultProvider]); return $token; }
[ "public", "function", "createToken", "(", "$", "name", ",", "array", "$", "scopes", "=", "[", "]", ")", "{", "// Backup default provider", "$", "defaultProvider", "=", "config", "(", "'auth.guards.api.provider'", ")", ";", "$", "userProvider", "=", "AuthConfigHe...
Create a new personal access token for the user and create . @param string $name @param array $scopes @return PersonalAccessTokenResult @throws MissingConfigException
[ "Create", "a", "new", "personal", "access", "token", "for", "the", "user", "and", "create", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/HasMultiAuthApiTokens.php#L42-L60
sfelix-martins/passport-multiauth
src/Http/Middleware/MultiAuthenticate.php
MultiAuthenticate.handle
public function handle($request, Closure $next, ...$guards) { // If don't has any guard follow the flow if (empty($guards)) { $this->authenticate($request, $guards); // Stop laravel from checking for a token if session is not set return $next($request); } $psrRequest = ServerRequest::createRequest($request); try { $psrRequest = $this->server->validateAuthenticatedRequest($psrRequest); if (! ($accessToken = $this->getAccessTokenFromRequest($psrRequest))) { throw new AuthenticationException('Unauthenticated', $guards); } $guard = $this->getTokenGuard($accessToken, $guards); $this->authenticate($request, $guard); } catch (OAuthServerException $e) { // If has an OAuthServerException check if has unit tests and fake // user authenticated. if (($user = PassportMultiauth::userActing()) && $this->canBeAuthenticated($user, $guards) ) { return $next($request); } // @todo Check if it's the best way to handle with OAuthServerException throw new AuthenticationException('Unauthenticated', $guards); } return $next($request); }
php
public function handle($request, Closure $next, ...$guards) { // If don't has any guard follow the flow if (empty($guards)) { $this->authenticate($request, $guards); // Stop laravel from checking for a token if session is not set return $next($request); } $psrRequest = ServerRequest::createRequest($request); try { $psrRequest = $this->server->validateAuthenticatedRequest($psrRequest); if (! ($accessToken = $this->getAccessTokenFromRequest($psrRequest))) { throw new AuthenticationException('Unauthenticated', $guards); } $guard = $this->getTokenGuard($accessToken, $guards); $this->authenticate($request, $guard); } catch (OAuthServerException $e) { // If has an OAuthServerException check if has unit tests and fake // user authenticated. if (($user = PassportMultiauth::userActing()) && $this->canBeAuthenticated($user, $guards) ) { return $next($request); } // @todo Check if it's the best way to handle with OAuthServerException throw new AuthenticationException('Unauthenticated', $guards); } return $next($request); }
[ "public", "function", "handle", "(", "$", "request", ",", "Closure", "$", "next", ",", "...", "$", "guards", ")", "{", "// If don't has any guard follow the flow", "if", "(", "empty", "(", "$", "guards", ")", ")", "{", "$", "this", "->", "authenticate", "(...
Handle an incoming request. Authenticates the guard from access token used on request. @param \Illuminate\Http\Request $request @param \Closure $next @param string[] ...$guards @return mixed @throws \Illuminate\Auth\AuthenticationException @throws \SMartins\PassportMultiauth\Exceptions\MissingConfigException
[ "Handle", "an", "incoming", "request", ".", "Authenticates", "the", "guard", "from", "access", "token", "used", "on", "request", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Http/Middleware/MultiAuthenticate.php#L62-L98
sfelix-martins/passport-multiauth
src/Http/Middleware/MultiAuthenticate.php
MultiAuthenticate.canBeAuthenticated
public function canBeAuthenticated(Authenticatable $user, $guards) { $userGuard = AuthConfigHelper::getUserGuard($user); return in_array($userGuard, $guards); }
php
public function canBeAuthenticated(Authenticatable $user, $guards) { $userGuard = AuthConfigHelper::getUserGuard($user); return in_array($userGuard, $guards); }
[ "public", "function", "canBeAuthenticated", "(", "Authenticatable", "$", "user", ",", "$", "guards", ")", "{", "$", "userGuard", "=", "AuthConfigHelper", "::", "getUserGuard", "(", "$", "user", ")", ";", "return", "in_array", "(", "$", "userGuard", ",", "$",...
Check if user acting has the required guards and scopes on request. @param Authenticatable $user @param array $guards @return bool @throws \SMartins\PassportMultiauth\Exceptions\MissingConfigException
[ "Check", "if", "user", "acting", "has", "the", "required", "guards", "and", "scopes", "on", "request", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Http/Middleware/MultiAuthenticate.php#L121-L126
sfelix-martins/passport-multiauth
src/Http/Middleware/MultiAuthenticate.php
MultiAuthenticate.getTokenGuard
public function getTokenGuard(Token $token, $guards) { $providers = GuardChecker::getGuardsProviders($guards); // use only guard associated to access token provider return $providers->has($token->provider) ? [$providers->get($token->provider)] : []; }
php
public function getTokenGuard(Token $token, $guards) { $providers = GuardChecker::getGuardsProviders($guards); // use only guard associated to access token provider return $providers->has($token->provider) ? [$providers->get($token->provider)] : []; }
[ "public", "function", "getTokenGuard", "(", "Token", "$", "token", ",", "$", "guards", ")", "{", "$", "providers", "=", "GuardChecker", "::", "getGuardsProviders", "(", "$", "guards", ")", ";", "// use only guard associated to access token provider", "return", "$", ...
Get guard related with token. @param Token $token @param $guards @return array
[ "Get", "guard", "related", "with", "token", "." ]
train
https://github.com/sfelix-martins/passport-multiauth/blob/ff59417a88a3c3431c55cbaae7fb98d7a495de4e/src/Http/Middleware/MultiAuthenticate.php#L135-L141
craftcms/contact-form
src/Mailer.php
Mailer.send
public function send(Submission $submission, bool $runValidation = true): bool { // Get the plugin settings and make sure they validate before doing anything $settings = Plugin::getInstance()->getSettings(); if (!$settings->validate()) { throw new InvalidConfigException('The Contact Form settings don’t validate.'); } if ($runValidation && !$submission->validate()) { Craft::info('Contact form submission not saved due to validation error.', __METHOD__); return false; } $mailer = Craft::$app->getMailer(); // Prep the message $fromEmail = $this->getFromEmail($mailer->from); $fromName = $this->compileFromName($submission->fromName); $subject = $this->compileSubject($submission->subject); $textBody = $this->compileTextBody($submission); $htmlBody = $this->compileHtmlBody($textBody); $message = (new Message()) ->setFrom([$fromEmail => $fromName]) ->setReplyTo([$submission->fromEmail => $submission->fromName]) ->setSubject($subject) ->setTextBody($textBody) ->setHtmlBody($htmlBody); if ($submission->attachment !== null) { foreach ($submission->attachment as $attachment) { if (!$attachment) { continue; } $message->attach($attachment->tempName, [ 'fileName' => $attachment->name, 'contentType' => FileHelper::getMimeType($attachment->tempName), ]); } } // Grab any "to" emails set in the plugin settings. $toEmails = is_string($settings->toEmail) ? StringHelper::split($settings->toEmail) : $settings->toEmail; // Fire a 'beforeSend' event $event = new SendEvent([ 'submission' => $submission, 'message' => $message, 'toEmails' => $toEmails, ]); $this->trigger(self::EVENT_BEFORE_SEND, $event); if ($event->isSpam) { Craft::info('Contact form submission suspected to be spam.', __METHOD__); return true; } foreach ($event->toEmails as $toEmail) { $message->setTo($toEmail); $mailer->send($message); } // Fire an 'afterSend' event if ($this->hasEventHandlers(self::EVENT_AFTER_SEND)) { $this->trigger(self::EVENT_AFTER_SEND, new SendEvent([ 'submission' => $submission, 'message' => $message, 'toEmails' => $event->toEmails, ])); } return true; }
php
public function send(Submission $submission, bool $runValidation = true): bool { // Get the plugin settings and make sure they validate before doing anything $settings = Plugin::getInstance()->getSettings(); if (!$settings->validate()) { throw new InvalidConfigException('The Contact Form settings don’t validate.'); } if ($runValidation && !$submission->validate()) { Craft::info('Contact form submission not saved due to validation error.', __METHOD__); return false; } $mailer = Craft::$app->getMailer(); // Prep the message $fromEmail = $this->getFromEmail($mailer->from); $fromName = $this->compileFromName($submission->fromName); $subject = $this->compileSubject($submission->subject); $textBody = $this->compileTextBody($submission); $htmlBody = $this->compileHtmlBody($textBody); $message = (new Message()) ->setFrom([$fromEmail => $fromName]) ->setReplyTo([$submission->fromEmail => $submission->fromName]) ->setSubject($subject) ->setTextBody($textBody) ->setHtmlBody($htmlBody); if ($submission->attachment !== null) { foreach ($submission->attachment as $attachment) { if (!$attachment) { continue; } $message->attach($attachment->tempName, [ 'fileName' => $attachment->name, 'contentType' => FileHelper::getMimeType($attachment->tempName), ]); } } // Grab any "to" emails set in the plugin settings. $toEmails = is_string($settings->toEmail) ? StringHelper::split($settings->toEmail) : $settings->toEmail; // Fire a 'beforeSend' event $event = new SendEvent([ 'submission' => $submission, 'message' => $message, 'toEmails' => $toEmails, ]); $this->trigger(self::EVENT_BEFORE_SEND, $event); if ($event->isSpam) { Craft::info('Contact form submission suspected to be spam.', __METHOD__); return true; } foreach ($event->toEmails as $toEmail) { $message->setTo($toEmail); $mailer->send($message); } // Fire an 'afterSend' event if ($this->hasEventHandlers(self::EVENT_AFTER_SEND)) { $this->trigger(self::EVENT_AFTER_SEND, new SendEvent([ 'submission' => $submission, 'message' => $message, 'toEmails' => $event->toEmails, ])); } return true; }
[ "public", "function", "send", "(", "Submission", "$", "submission", ",", "bool", "$", "runValidation", "=", "true", ")", ":", "bool", "{", "// Get the plugin settings and make sure they validate before doing anything", "$", "settings", "=", "Plugin", "::", "getInstance"...
Sends an email submitted through a contact form. @param Submission $submission @param bool $runValidation Whether the section should be validated @throws InvalidConfigException if the plugin settings don't validate @return bool
[ "Sends", "an", "email", "submitted", "through", "a", "contact", "form", "." ]
train
https://github.com/craftcms/contact-form/blob/44b48be5dc641f8874bb351131ef88413b49721c/src/Mailer.php#L43-L115
craftcms/contact-form
src/Mailer.php
Mailer.getFromEmail
public function getFromEmail($from): string { if (is_string($from)) { return $from; } if ($from instanceof User) { return $from->email; } if (is_array($from)) { $first = reset($from); $key = key($from); if (is_numeric($key)) { return $this->getFromEmail($first); } return $key; } throw new InvalidConfigException('Can\'t determine "From" email from email config settings.'); }
php
public function getFromEmail($from): string { if (is_string($from)) { return $from; } if ($from instanceof User) { return $from->email; } if (is_array($from)) { $first = reset($from); $key = key($from); if (is_numeric($key)) { return $this->getFromEmail($first); } return $key; } throw new InvalidConfigException('Can\'t determine "From" email from email config settings.'); }
[ "public", "function", "getFromEmail", "(", "$", "from", ")", ":", "string", "{", "if", "(", "is_string", "(", "$", "from", ")", ")", "{", "return", "$", "from", ";", "}", "if", "(", "$", "from", "instanceof", "User", ")", "{", "return", "$", "from"...
Returns the "From" email value on the given mailer $from property object. @param string|array|User|User[]|null $from @return string @throws InvalidConfigException if it can’t be determined
[ "Returns", "the", "From", "email", "value", "on", "the", "given", "mailer", "$from", "property", "object", "." ]
train
https://github.com/craftcms/contact-form/blob/44b48be5dc641f8874bb351131ef88413b49721c/src/Mailer.php#L124-L141
craftcms/contact-form
src/Mailer.php
Mailer.compileFromName
public function compileFromName(string $fromName = null): string { $settings = Plugin::getInstance()->getSettings(); return $settings->prependSender.($settings->prependSender && $fromName ? ' ' : '').$fromName; }
php
public function compileFromName(string $fromName = null): string { $settings = Plugin::getInstance()->getSettings(); return $settings->prependSender.($settings->prependSender && $fromName ? ' ' : '').$fromName; }
[ "public", "function", "compileFromName", "(", "string", "$", "fromName", "=", "null", ")", ":", "string", "{", "$", "settings", "=", "Plugin", "::", "getInstance", "(", ")", "->", "getSettings", "(", ")", ";", "return", "$", "settings", "->", "prependSende...
Compiles the "From" name value from the submitted name. @param string|null $fromName @return string
[ "Compiles", "the", "From", "name", "value", "from", "the", "submitted", "name", "." ]
train
https://github.com/craftcms/contact-form/blob/44b48be5dc641f8874bb351131ef88413b49721c/src/Mailer.php#L149-L153
craftcms/contact-form
src/Mailer.php
Mailer.compileSubject
public function compileSubject(string $subject = null): string { $settings = Plugin::getInstance()->getSettings(); return $settings->prependSubject.($settings->prependSubject && $subject ? ' - ' : '').$subject; }
php
public function compileSubject(string $subject = null): string { $settings = Plugin::getInstance()->getSettings(); return $settings->prependSubject.($settings->prependSubject && $subject ? ' - ' : '').$subject; }
[ "public", "function", "compileSubject", "(", "string", "$", "subject", "=", "null", ")", ":", "string", "{", "$", "settings", "=", "Plugin", "::", "getInstance", "(", ")", "->", "getSettings", "(", ")", ";", "return", "$", "settings", "->", "prependSubject...
Compiles the real email subject from the submitted subject. @param string|null $subject @return string
[ "Compiles", "the", "real", "email", "subject", "from", "the", "submitted", "subject", "." ]
train
https://github.com/craftcms/contact-form/blob/44b48be5dc641f8874bb351131ef88413b49721c/src/Mailer.php#L161-L165
craftcms/contact-form
src/Mailer.php
Mailer.compileTextBody
public function compileTextBody(Submission $submission): string { $fields = []; if ($submission->fromName) { $fields[Craft::t('contact-form', 'Name')] = $submission->fromName; } $fields[Craft::t('contact-form', 'Email')] = $submission->fromEmail; if (is_array($submission->message)) { $body = $submission->message['body'] ?? ''; $fields = array_merge($fields, $submission->message); unset($fields['body']); } else { $body = (string)$submission->message; } $text = ''; foreach ($fields as $key => $value) { $text .= ($text ? "\n" : '')."- **{$key}:** "; if (is_array($value)) { $text .= implode(', ', $value); } else { $text .= $value; } } if ($body !== '') { $body = preg_replace('/\R/u', "\n\n", $body); $text .= "\n\n".$body; } return $text; }
php
public function compileTextBody(Submission $submission): string { $fields = []; if ($submission->fromName) { $fields[Craft::t('contact-form', 'Name')] = $submission->fromName; } $fields[Craft::t('contact-form', 'Email')] = $submission->fromEmail; if (is_array($submission->message)) { $body = $submission->message['body'] ?? ''; $fields = array_merge($fields, $submission->message); unset($fields['body']); } else { $body = (string)$submission->message; } $text = ''; foreach ($fields as $key => $value) { $text .= ($text ? "\n" : '')."- **{$key}:** "; if (is_array($value)) { $text .= implode(', ', $value); } else { $text .= $value; } } if ($body !== '') { $body = preg_replace('/\R/u', "\n\n", $body); $text .= "\n\n".$body; } return $text; }
[ "public", "function", "compileTextBody", "(", "Submission", "$", "submission", ")", ":", "string", "{", "$", "fields", "=", "[", "]", ";", "if", "(", "$", "submission", "->", "fromName", ")", "{", "$", "fields", "[", "Craft", "::", "t", "(", "'contact-...
Compiles the real email textual body from the submitted message. @param Submission $submission @return string
[ "Compiles", "the", "real", "email", "textual", "body", "from", "the", "submitted", "message", "." ]
train
https://github.com/craftcms/contact-form/blob/44b48be5dc641f8874bb351131ef88413b49721c/src/Mailer.php#L173-L208
craftcms/contact-form
src/Mailer.php
Mailer.compileHtmlBody
public function compileHtmlBody(string $textBody): string { $html = Html::encode($textBody); $html = Markdown::process($html); return $html; }
php
public function compileHtmlBody(string $textBody): string { $html = Html::encode($textBody); $html = Markdown::process($html); return $html; }
[ "public", "function", "compileHtmlBody", "(", "string", "$", "textBody", ")", ":", "string", "{", "$", "html", "=", "Html", "::", "encode", "(", "$", "textBody", ")", ";", "$", "html", "=", "Markdown", "::", "process", "(", "$", "html", ")", ";", "re...
Compiles the real email HTML body from the compiled textual body. @param string $textBody @return string
[ "Compiles", "the", "real", "email", "HTML", "body", "from", "the", "compiled", "textual", "body", "." ]
train
https://github.com/craftcms/contact-form/blob/44b48be5dc641f8874bb351131ef88413b49721c/src/Mailer.php#L216-L222
craftcms/contact-form
src/controllers/SendController.php
SendController.actionIndex
public function actionIndex() { $this->requirePostRequest(); $request = Craft::$app->getRequest(); $plugin = Plugin::getInstance(); $settings = $plugin->getSettings(); $submission = new Submission(); $submission->fromEmail = $request->getBodyParam('fromEmail'); $submission->fromName = $request->getBodyParam('fromName'); $submission->subject = $request->getBodyParam('subject'); $message = $request->getBodyParam('message'); if (is_array($message)) { $submission->message = array_filter($message, function($value) { return $value !== ''; }); } else { $submission->message = $message; } if ($settings->allowAttachments && isset($_FILES['attachment']) && isset($_FILES['attachment']['name'])) { if (is_array($_FILES['attachment']['name'])) { $submission->attachment = UploadedFile::getInstancesByName('attachment'); } else { $submission->attachment = [UploadedFile::getInstanceByName('attachment')]; } } if (!$plugin->getMailer()->send($submission)) { if ($request->getAcceptsJson()) { return $this->asJson(['errors' => $submission->getErrors()]); } Craft::$app->getSession()->setError(Craft::t('contact-form', 'There was a problem with your submission, please check the form and try again!')); Craft::$app->getUrlManager()->setRouteParams([ 'variables' => ['message' => $submission] ]); return null; } if ($request->getAcceptsJson()) { return $this->asJson(['success' => true]); } Craft::$app->getSession()->setNotice($settings->successFlashMessage); return $this->redirectToPostedUrl($submission); }
php
public function actionIndex() { $this->requirePostRequest(); $request = Craft::$app->getRequest(); $plugin = Plugin::getInstance(); $settings = $plugin->getSettings(); $submission = new Submission(); $submission->fromEmail = $request->getBodyParam('fromEmail'); $submission->fromName = $request->getBodyParam('fromName'); $submission->subject = $request->getBodyParam('subject'); $message = $request->getBodyParam('message'); if (is_array($message)) { $submission->message = array_filter($message, function($value) { return $value !== ''; }); } else { $submission->message = $message; } if ($settings->allowAttachments && isset($_FILES['attachment']) && isset($_FILES['attachment']['name'])) { if (is_array($_FILES['attachment']['name'])) { $submission->attachment = UploadedFile::getInstancesByName('attachment'); } else { $submission->attachment = [UploadedFile::getInstanceByName('attachment')]; } } if (!$plugin->getMailer()->send($submission)) { if ($request->getAcceptsJson()) { return $this->asJson(['errors' => $submission->getErrors()]); } Craft::$app->getSession()->setError(Craft::t('contact-form', 'There was a problem with your submission, please check the form and try again!')); Craft::$app->getUrlManager()->setRouteParams([ 'variables' => ['message' => $submission] ]); return null; } if ($request->getAcceptsJson()) { return $this->asJson(['success' => true]); } Craft::$app->getSession()->setNotice($settings->successFlashMessage); return $this->redirectToPostedUrl($submission); }
[ "public", "function", "actionIndex", "(", ")", "{", "$", "this", "->", "requirePostRequest", "(", ")", ";", "$", "request", "=", "Craft", "::", "$", "app", "->", "getRequest", "(", ")", ";", "$", "plugin", "=", "Plugin", "::", "getInstance", "(", ")", ...
Sends a contact form submission. @return Response|null
[ "Sends", "a", "contact", "form", "submission", "." ]
train
https://github.com/craftcms/contact-form/blob/44b48be5dc641f8874bb351131ef88413b49721c/src/controllers/SendController.php#L30-L78
messagebird/php-rest-api
src/MessageBird/Objects/Message.php
Message.setPremiumSms
public function setPremiumSms($shortcode, $keyword, $tariff, $mid = null, $member = null) { $this->typeDetails['shortcode'] = $shortcode; $this->typeDetails['keyword'] = $keyword; $this->typeDetails['tariff'] = $tariff; if ($mid != null) { $this->typeDetails['mid'] = $mid; } if ($member != null) { $this->typeDetails['member'] = $member; } $this->type = self::TYPE_PREMIUM; }
php
public function setPremiumSms($shortcode, $keyword, $tariff, $mid = null, $member = null) { $this->typeDetails['shortcode'] = $shortcode; $this->typeDetails['keyword'] = $keyword; $this->typeDetails['tariff'] = $tariff; if ($mid != null) { $this->typeDetails['mid'] = $mid; } if ($member != null) { $this->typeDetails['member'] = $member; } $this->type = self::TYPE_PREMIUM; }
[ "public", "function", "setPremiumSms", "(", "$", "shortcode", ",", "$", "keyword", ",", "$", "tariff", ",", "$", "mid", "=", "null", ",", "$", "member", "=", "null", ")", "{", "$", "this", "->", "typeDetails", "[", "'shortcode'", "]", "=", "$", "shor...
Send a premium SMS @param $shortcode @param $keyword @param $tariff @param $mid @param $member
[ "Send", "a", "premium", "SMS" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Objects/Message.php#L151-L164
messagebird/php-rest-api
src/MessageBird/Objects/Message.php
Message.loadFromArray
public function loadFromArray ($object) { parent::loadFromArray($object); if (!empty($this->recipients->items)) { foreach($this->recipients->items AS &$item) { $Recipient = new Recipient(); $Recipient->loadFromArray($item); $item = $Recipient; } }
php
public function loadFromArray ($object) { parent::loadFromArray($object); if (!empty($this->recipients->items)) { foreach($this->recipients->items AS &$item) { $Recipient = new Recipient(); $Recipient->loadFromArray($item); $item = $Recipient; } }
[ "public", "function", "loadFromArray", "(", "$", "object", ")", "{", "parent", "::", "loadFromArray", "(", "$", "object", ")", ";", "if", "(", "!", "empty", "(", "$", "this", "->", "recipients", "->", "items", ")", ")", "{", "foreach", "(", "$", "thi...
@param $object @return $this|void
[ "@param", "$object" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Objects/Message.php#L224-L235
messagebird/php-rest-api
src/MessageBird/Resources/Voice/Legs.php
Legs.processRequest
public function processRequest($body) { $body = @json_decode($body); if ($body === null or $body === false) { throw new Exceptions\ServerException('Got an invalid JSON response from the server.'); } if (empty($body->errors)) { return $this->Object->loadFromArray($body->data[0]); } $ResponseError = new Common\ResponseError($body); throw new Exceptions\RequestException($ResponseError->getErrorString()); }
php
public function processRequest($body) { $body = @json_decode($body); if ($body === null or $body === false) { throw new Exceptions\ServerException('Got an invalid JSON response from the server.'); } if (empty($body->errors)) { return $this->Object->loadFromArray($body->data[0]); } $ResponseError = new Common\ResponseError($body); throw new Exceptions\RequestException($ResponseError->getErrorString()); }
[ "public", "function", "processRequest", "(", "$", "body", ")", "{", "$", "body", "=", "@", "json_decode", "(", "$", "body", ")", ";", "if", "(", "$", "body", "===", "null", "or", "$", "body", "===", "false", ")", "{", "throw", "new", "Exceptions", ...
@param string $body @return Objects\Voice\Leg @throws \MessageBird\Exceptions\RequestException @throws \MessageBird\Exceptions\ServerException
[ "@param", "string", "$body" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/Voice/Legs.php#L108-L122
messagebird/php-rest-api
src/MessageBird/Common/HttpClient.php
HttpClient.getRequestUrl
public function getRequestUrl($resourceName, $query) { $requestUrl = $this->endpoint . '/' . $resourceName; if ($query) { if (is_array($query)) { $query = http_build_query($query); } $requestUrl .= '?' . $query; } return $requestUrl; }
php
public function getRequestUrl($resourceName, $query) { $requestUrl = $this->endpoint . '/' . $resourceName; if ($query) { if (is_array($query)) { $query = http_build_query($query); } $requestUrl .= '?' . $query; } return $requestUrl; }
[ "public", "function", "getRequestUrl", "(", "$", "resourceName", ",", "$", "query", ")", "{", "$", "requestUrl", "=", "$", "this", "->", "endpoint", ".", "'/'", ".", "$", "resourceName", ";", "if", "(", "$", "query", ")", "{", "if", "(", "is_array", ...
@param string $resourceName @param mixed $query @return string
[ "@param", "string", "$resourceName", "@param", "mixed", "$query" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Common/HttpClient.php#L110-L121
messagebird/php-rest-api
src/MessageBird/Common/HttpClient.php
HttpClient.performHttpRequest
public function performHttpRequest($method, $resourceName, $query = null, $body = null) { $curl = curl_init(); if ($this->Authentication === null) { throw new Exceptions\AuthenticateException('Can not perform API Request without Authentication'); } $headers = array ( 'User-agent: ' . implode(' ', $this->userAgent), 'Accept: application/json', 'Content-Type: application/json', 'Accept-Charset: utf-8', sprintf('Authorization: AccessKey %s', $this->Authentication->accessKey) ); $headers = array_merge($headers, $this->headers); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_URL, $this->getRequestUrl($resourceName, $query)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->connectionTimeout); foreach ($this->httpOptions as $option => $value) { curl_setopt($curl, $option, $value); } if ($method === self::REQUEST_GET) { curl_setopt($curl, CURLOPT_HTTPGET, true); } elseif ($method === self::REQUEST_POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $body); } elseif ($method === self::REQUEST_DELETE) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, self::REQUEST_DELETE); } elseif ($method === self::REQUEST_PUT){ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, self::REQUEST_PUT); curl_setopt($curl, CURLOPT_POSTFIELDS, $body); } elseif ($method === self::REQUEST_PATCH){ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, self::REQUEST_PATCH); curl_setopt($curl, CURLOPT_POSTFIELDS, $body); } // Some servers have outdated or incorrect certificates, Use the included CA-bundle $caFile = realpath(__DIR__ . '/../ca-bundle.crt'); if (!file_exists($caFile)) { throw new Exceptions\HttpException(sprintf('Unable to find CA-bundle file "%s".', __DIR__ . '/../ca-bundle.crt')); } curl_setopt($curl, CURLOPT_CAINFO, $caFile); $response = curl_exec($curl); if ($response === false) { throw new Exceptions\HttpException(curl_error($curl), curl_errno($curl)); } $responseStatus = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE); // Split the header and body $parts = explode("\r\n\r\n", $response, 3); list($responseHeader, $responseBody) = ($parts[0] === 'HTTP/1.1 100 Continue') ? array ($parts[1], $parts[2]) : array ($parts[0], $parts[1]); curl_close($curl); return array ($responseStatus, $responseHeader, $responseBody); }
php
public function performHttpRequest($method, $resourceName, $query = null, $body = null) { $curl = curl_init(); if ($this->Authentication === null) { throw new Exceptions\AuthenticateException('Can not perform API Request without Authentication'); } $headers = array ( 'User-agent: ' . implode(' ', $this->userAgent), 'Accept: application/json', 'Content-Type: application/json', 'Accept-Charset: utf-8', sprintf('Authorization: AccessKey %s', $this->Authentication->accessKey) ); $headers = array_merge($headers, $this->headers); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_URL, $this->getRequestUrl($resourceName, $query)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->connectionTimeout); foreach ($this->httpOptions as $option => $value) { curl_setopt($curl, $option, $value); } if ($method === self::REQUEST_GET) { curl_setopt($curl, CURLOPT_HTTPGET, true); } elseif ($method === self::REQUEST_POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $body); } elseif ($method === self::REQUEST_DELETE) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, self::REQUEST_DELETE); } elseif ($method === self::REQUEST_PUT){ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, self::REQUEST_PUT); curl_setopt($curl, CURLOPT_POSTFIELDS, $body); } elseif ($method === self::REQUEST_PATCH){ curl_setopt($curl, CURLOPT_CUSTOMREQUEST, self::REQUEST_PATCH); curl_setopt($curl, CURLOPT_POSTFIELDS, $body); } // Some servers have outdated or incorrect certificates, Use the included CA-bundle $caFile = realpath(__DIR__ . '/../ca-bundle.crt'); if (!file_exists($caFile)) { throw new Exceptions\HttpException(sprintf('Unable to find CA-bundle file "%s".', __DIR__ . '/../ca-bundle.crt')); } curl_setopt($curl, CURLOPT_CAINFO, $caFile); $response = curl_exec($curl); if ($response === false) { throw new Exceptions\HttpException(curl_error($curl), curl_errno($curl)); } $responseStatus = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE); // Split the header and body $parts = explode("\r\n\r\n", $response, 3); list($responseHeader, $responseBody) = ($parts[0] === 'HTTP/1.1 100 Continue') ? array ($parts[1], $parts[2]) : array ($parts[0], $parts[1]); curl_close($curl); return array ($responseStatus, $responseHeader, $responseBody); }
[ "public", "function", "performHttpRequest", "(", "$", "method", ",", "$", "resourceName", ",", "$", "query", "=", "null", ",", "$", "body", "=", "null", ")", "{", "$", "curl", "=", "curl_init", "(", ")", ";", "if", "(", "$", "this", "->", "Authentica...
@param string $method @param string $resourceName @param mixed $query @param string|null $body @return array @throws Exceptions\AuthenticateException @throws Exceptions\HttpException
[ "@param", "string", "$method", "@param", "string", "$resourceName", "@param", "mixed", "$query", "@param", "string|null", "$body" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Common/HttpClient.php#L160-L227
messagebird/php-rest-api
src/MessageBird/Objects/Group.php
Group.loadFromArray
public function loadFromArray ($object) { parent::loadFromArray($object); if (!empty($object->items)) { foreach($object->items AS &$item) { $Contact = new Contact(); $Contact->loadFromArray($item); $item = $Contact; } }
php
public function loadFromArray ($object) { parent::loadFromArray($object); if (!empty($object->items)) { foreach($object->items AS &$item) { $Contact = new Contact(); $Contact->loadFromArray($item); $item = $Contact; } }
[ "public", "function", "loadFromArray", "(", "$", "object", ")", "{", "parent", "::", "loadFromArray", "(", "$", "object", ")", ";", "if", "(", "!", "empty", "(", "$", "object", "->", "items", ")", ")", "{", "foreach", "(", "$", "object", "->", "items...
@param $object @return $this|void
[ "@param", "$object" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Objects/Group.php#L101-L112
messagebird/php-rest-api
src/MessageBird/Resources/LookupHlr.php
LookupHlr.create
public function create($hlr, $countryCode = null) { if(empty($hlr->msisdn)) { throw new InvalidArgumentException('The phone number ($hlr->msisdn) cannot be empty.'); } $query = null; if ($countryCode != null) { $query = array("countryCode" => $countryCode); } $ResourceName = $this->resourceName . '/' . ($hlr->msisdn) . '/hlr' ; list(, , $body) = $this->HttpClient->performHttpRequest(Common\HttpClient::REQUEST_POST, $ResourceName, $query, json_encode($hlr)); return $this->processRequest($body); }
php
public function create($hlr, $countryCode = null) { if(empty($hlr->msisdn)) { throw new InvalidArgumentException('The phone number ($hlr->msisdn) cannot be empty.'); } $query = null; if ($countryCode != null) { $query = array("countryCode" => $countryCode); } $ResourceName = $this->resourceName . '/' . ($hlr->msisdn) . '/hlr' ; list(, , $body) = $this->HttpClient->performHttpRequest(Common\HttpClient::REQUEST_POST, $ResourceName, $query, json_encode($hlr)); return $this->processRequest($body); }
[ "public", "function", "create", "(", "$", "hlr", ",", "$", "countryCode", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "hlr", "->", "msisdn", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The phone number ($hlr->msisdn) cannot be em...
@param Objects\Hlr $hlr @param string|null $countryCode @return $this->Object @throws \MessageBird\Exceptions\HttpException @throws \MessageBird\Exceptions\RequestException @throws \MessageBird\Exceptions\ServerException
[ "@param", "Objects", "\\", "Hlr", "$hlr", "@param", "string|null", "$countryCode" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/LookupHlr.php#L38-L51
messagebird/php-rest-api
src/MessageBird/Resources/LookupHlr.php
LookupHlr.read
public function read($phoneNumber = null, $countryCode = null) { if(empty($phoneNumber)) { throw new InvalidArgumentException('The phone number cannot be empty.'); } $query = null; if ($countryCode != null) { $query = array("countryCode" => $countryCode); } $ResourceName = $this->resourceName . '/' . $phoneNumber . '/hlr' ; list(, , $body) = $this->HttpClient->performHttpRequest(Common\HttpClient::REQUEST_GET, $ResourceName, $query, null); return $this->processRequest($body); }
php
public function read($phoneNumber = null, $countryCode = null) { if(empty($phoneNumber)) { throw new InvalidArgumentException('The phone number cannot be empty.'); } $query = null; if ($countryCode != null) { $query = array("countryCode" => $countryCode); } $ResourceName = $this->resourceName . '/' . $phoneNumber . '/hlr' ; list(, , $body) = $this->HttpClient->performHttpRequest(Common\HttpClient::REQUEST_GET, $ResourceName, $query, null); return $this->processRequest($body); }
[ "public", "function", "read", "(", "$", "phoneNumber", "=", "null", ",", "$", "countryCode", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "phoneNumber", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'The phone number cannot be empty....
@param $phoneNumber @param string|null $countryCode @return $this->Object @throws \MessageBird\Exceptions\HttpException @throws \MessageBird\Exceptions\RequestException @throws \MessageBird\Exceptions\ServerException
[ "@param", "$phoneNumber", "@param", "string|null", "$countryCode" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/LookupHlr.php#L63-L76
messagebird/php-rest-api
src/MessageBird/RequestValidator.php
RequestValidator.verify
public function verify(SignedRequest $request) { $payload = $this->buildPayloadFromRequest($request); $calculatedSignature = \hash_hmac(self::HMAC_HASH_ALGO, $payload, $this->signingKey, true); $expectedSignature = \base64_decode($request->signature, true); return \hash_equals($expectedSignature, $calculatedSignature); }
php
public function verify(SignedRequest $request) { $payload = $this->buildPayloadFromRequest($request); $calculatedSignature = \hash_hmac(self::HMAC_HASH_ALGO, $payload, $this->signingKey, true); $expectedSignature = \base64_decode($request->signature, true); return \hash_equals($expectedSignature, $calculatedSignature); }
[ "public", "function", "verify", "(", "SignedRequest", "$", "request", ")", "{", "$", "payload", "=", "$", "this", "->", "buildPayloadFromRequest", "(", "$", "request", ")", ";", "$", "calculatedSignature", "=", "\\", "hash_hmac", "(", "self", "::", "HMAC_HAS...
Verify that the signed request was submitted from MessageBird using the known key. @param SignedRequest $request @return bool
[ "Verify", "that", "the", "signed", "request", "was", "submitted", "from", "MessageBird", "using", "the", "known", "key", "." ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/RequestValidator.php#L40-L48
messagebird/php-rest-api
src/MessageBird/Resources/Verify.php
Verify.verify
public function verify($id, $token) { $ResourceName = $this->resourceName . (($id) ? '/' . $id : null); list(, , $body) = $this->HttpClient->performHttpRequest(Common\HttpClient::REQUEST_GET, $ResourceName, array('token' => $token)); return $this->processRequest($body); }
php
public function verify($id, $token) { $ResourceName = $this->resourceName . (($id) ? '/' . $id : null); list(, , $body) = $this->HttpClient->performHttpRequest(Common\HttpClient::REQUEST_GET, $ResourceName, array('token' => $token)); return $this->processRequest($body); }
[ "public", "function", "verify", "(", "$", "id", ",", "$", "token", ")", "{", "$", "ResourceName", "=", "$", "this", "->", "resourceName", ".", "(", "(", "$", "id", ")", "?", "'/'", ".", "$", "id", ":", "null", ")", ";", "list", "(", ",", ",", ...
@param $id @param $token @return $this->Object @throws \MessageBird\Exceptions\HttpException @throws \MessageBird\Exceptions\RequestException @throws \MessageBird\Exceptions\ServerException
[ "@param", "$id", "@param", "$token" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/Verify.php#L37-L42
messagebird/php-rest-api
src/MessageBird/Objects/SignedRequest.php
SignedRequest.createFromGlobals
public static function createFromGlobals() { $body = file_get_contents('php://input'); $queryParameters = $_GET; $requestTimestamp = $_SERVER['HTTP_MESSAGEBIRD_REQUEST_TIMESTAMP']; $signature = $_SERVER['HTTP_MESSAGEBIRD_SIGNATURE']; $signedRequest = new SignedRequest(); $signedRequest->loadFromArray(compact('body', 'queryParameters', 'requestTimestamp', 'signature')); return $signedRequest; }
php
public static function createFromGlobals() { $body = file_get_contents('php://input'); $queryParameters = $_GET; $requestTimestamp = $_SERVER['HTTP_MESSAGEBIRD_REQUEST_TIMESTAMP']; $signature = $_SERVER['HTTP_MESSAGEBIRD_SIGNATURE']; $signedRequest = new SignedRequest(); $signedRequest->loadFromArray(compact('body', 'queryParameters', 'requestTimestamp', 'signature')); return $signedRequest; }
[ "public", "static", "function", "createFromGlobals", "(", ")", "{", "$", "body", "=", "file_get_contents", "(", "'php://input'", ")", ";", "$", "queryParameters", "=", "$", "_GET", ";", "$", "requestTimestamp", "=", "$", "_SERVER", "[", "'HTTP_MESSAGEBIRD_REQUES...
Create a new SignedRequest from PHP globals. @return SignedRequest @throws ValidationException when a required parameter is missing.
[ "Create", "a", "new", "SignedRequest", "from", "PHP", "globals", "." ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Objects/SignedRequest.php#L50-L61
messagebird/php-rest-api
src/MessageBird/Objects/SignedRequest.php
SignedRequest.create
public static function create($query, $signature, $requestTimestamp, $body) { if (is_string($query)) { $queryParameters = array(); parse_str($query, $queryParameters); } else { $queryParameters = $query; } $signedRequest = new SignedRequest(); $signedRequest->loadFromArray(compact('body', 'queryParameters', 'requestTimestamp', 'signature')); return $signedRequest; }
php
public static function create($query, $signature, $requestTimestamp, $body) { if (is_string($query)) { $queryParameters = array(); parse_str($query, $queryParameters); } else { $queryParameters = $query; } $signedRequest = new SignedRequest(); $signedRequest->loadFromArray(compact('body', 'queryParameters', 'requestTimestamp', 'signature')); return $signedRequest; }
[ "public", "static", "function", "create", "(", "$", "query", ",", "$", "signature", ",", "$", "requestTimestamp", ",", "$", "body", ")", "{", "if", "(", "is_string", "(", "$", "query", ")", ")", "{", "$", "queryParameters", "=", "array", "(", ")", ";...
Create a SignedRequest from the provided data. @param string|array $query The query string from the request @param string $signature The base64-encoded signature for the request @param int $requestTimestamp The UNIX timestamp for the time the request was made @param string $body The request body @return SignedRequest @throws ValidationException when a required parameter is missing.
[ "Create", "a", "SignedRequest", "from", "the", "provided", "data", "." ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Objects/SignedRequest.php#L73-L86
messagebird/php-rest-api
src/MessageBird/Objects/SignedRequest.php
SignedRequest.loadFromArray
public function loadFromArray($params) { if (!isset($params['requestTimestamp']) || !is_int($params['requestTimestamp'])) { throw new ValidationException('The "requestTimestamp" value is missing or invalid.'); } if (!isset($params['signature']) || !is_string($params['signature'])) { throw new ValidationException('The "signature" parameter is missing.'); } if (!isset($params['queryParameters']) || !is_array($params['queryParameters'])) { throw new ValidationException('The "queryParameters" parameter is missing or invalid.'); } if (!isset($params['body']) || !is_string($params['body'])) { throw new ValidationException('The "body" parameter is missing.'); } return parent::loadFromArray($params); }
php
public function loadFromArray($params) { if (!isset($params['requestTimestamp']) || !is_int($params['requestTimestamp'])) { throw new ValidationException('The "requestTimestamp" value is missing or invalid.'); } if (!isset($params['signature']) || !is_string($params['signature'])) { throw new ValidationException('The "signature" parameter is missing.'); } if (!isset($params['queryParameters']) || !is_array($params['queryParameters'])) { throw new ValidationException('The "queryParameters" parameter is missing or invalid.'); } if (!isset($params['body']) || !is_string($params['body'])) { throw new ValidationException('The "body" parameter is missing.'); } return parent::loadFromArray($params); }
[ "public", "function", "loadFromArray", "(", "$", "params", ")", "{", "if", "(", "!", "isset", "(", "$", "params", "[", "'requestTimestamp'", "]", ")", "||", "!", "is_int", "(", "$", "params", "[", "'requestTimestamp'", "]", ")", ")", "{", "throw", "new...
{@inheritdoc} @throws ValidationException when a required parameter is missing.
[ "{" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Objects/SignedRequest.php#L92-L111
messagebird/php-rest-api
src/MessageBird/Objects/Contact.php
Contact.loadFromArray
public function loadFromArray($object) { unset($this->custom1, $this->custom2, $this->custom3, $this->custom4); return parent::loadFromArray($object); }
php
public function loadFromArray($object) { unset($this->custom1, $this->custom2, $this->custom3, $this->custom4); return parent::loadFromArray($object); }
[ "public", "function", "loadFromArray", "(", "$", "object", ")", "{", "unset", "(", "$", "this", "->", "custom1", ",", "$", "this", "->", "custom2", ",", "$", "this", "->", "custom3", ",", "$", "this", "->", "custom4", ")", ";", "return", "parent", ":...
@param $object @return $this
[ "@param", "$object" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Objects/Contact.php#L165-L170
messagebird/php-rest-api
src/MessageBird/Objects/Contact.php
Contact.loadFromArrayForGroups
public function loadFromArrayForGroups($object) { parent::loadFromArray($object); if (!empty($object->items)) { foreach($object->items AS &$item) { $Group = new Group(); $Group->loadFromArray($item); $item = $Group; } }
php
public function loadFromArrayForGroups($object) { parent::loadFromArray($object); if (!empty($object->items)) { foreach($object->items AS &$item) { $Group = new Group(); $Group->loadFromArray($item); $item = $Group; } }
[ "public", "function", "loadFromArrayForGroups", "(", "$", "object", ")", "{", "parent", "::", "loadFromArray", "(", "$", "object", ")", ";", "if", "(", "!", "empty", "(", "$", "object", "->", "items", ")", ")", "{", "foreach", "(", "$", "object", "->",...
@param $object @return $this ->Object
[ "@param", "$object" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Objects/Contact.php#L177-L188
messagebird/php-rest-api
src/MessageBird/Resources/Voice/Transcriptions.php
Transcriptions.create
public function create($callId, $legId, $recordingId) { list(, , $body) = $this->HttpClient->performHttpRequest( Common\HttpClient::REQUEST_POST, "calls/$callId/legs/$legId/recordings/$recordingId/transcriptions" ); return $this->processRequest($body); }
php
public function create($callId, $legId, $recordingId) { list(, , $body) = $this->HttpClient->performHttpRequest( Common\HttpClient::REQUEST_POST, "calls/$callId/legs/$legId/recordings/$recordingId/transcriptions" ); return $this->processRequest($body); }
[ "public", "function", "create", "(", "$", "callId", ",", "$", "legId", ",", "$", "recordingId", ")", "{", "list", "(", ",", ",", "$", "body", ")", "=", "$", "this", "->", "HttpClient", "->", "performHttpRequest", "(", "Common", "\\", "HttpClient", "::"...
@param string $callId @param string $legId @param string $recordingId @return Objects\Voice\Transcription
[ "@param", "string", "$callId", "@param", "string", "$legId", "@param", "string", "$recordingId" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/Voice/Transcriptions.php#L58-L65
messagebird/php-rest-api
src/MessageBird/Resources/Voice/Transcriptions.php
Transcriptions.getList
public function getList($callId, $legId, $recordingId, $parameters = array()) { list($status, , $body) = $this->HttpClient->performHttpRequest( Common\HttpClient::REQUEST_GET, "calls/$callId/legs/$legId/recordings/$recordingId/transcriptions", $parameters ); if ($status === 200) { $body = json_decode($body); $items = $body->data; unset($body->data); $baseList = new Objects\BaseList(); $baseList->loadFromArray($body); $objectName = $this->Object; foreach ($items as $item) { $object = new $objectName($this->HttpClient); $itemObject = $object->loadFromArray($item); $baseList->items[] = $itemObject; } return $baseList; } return $this->processRequest($body); }
php
public function getList($callId, $legId, $recordingId, $parameters = array()) { list($status, , $body) = $this->HttpClient->performHttpRequest( Common\HttpClient::REQUEST_GET, "calls/$callId/legs/$legId/recordings/$recordingId/transcriptions", $parameters ); if ($status === 200) { $body = json_decode($body); $items = $body->data; unset($body->data); $baseList = new Objects\BaseList(); $baseList->loadFromArray($body); $objectName = $this->Object; foreach ($items as $item) { $object = new $objectName($this->HttpClient); $itemObject = $object->loadFromArray($item); $baseList->items[] = $itemObject; } return $baseList; } return $this->processRequest($body); }
[ "public", "function", "getList", "(", "$", "callId", ",", "$", "legId", ",", "$", "recordingId", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "list", "(", "$", "status", ",", ",", "$", "body", ")", "=", "$", "this", "->", "HttpClient",...
@param string $callId @param string $legId @param string $recordingId @param array $parameters @return Objects\Voice\Transcription
[ "@param", "string", "$callId", "@param", "string", "$legId", "@param", "string", "$recordingId", "@param", "array", "$parameters" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/Voice/Transcriptions.php#L75-L104
messagebird/php-rest-api
src/MessageBird/Resources/Voice/Transcriptions.php
Transcriptions.read
public function read($callId, $legId, $recordingId, $transcriptionId) { list(, , $body) = $this->HttpClient->performHttpRequest(Common\HttpClient::REQUEST_GET, "calls/$callId/legs/$legId/recordings/$recordingId/transcriptions/$transcriptionId"); return $this->processRequest($body); }
php
public function read($callId, $legId, $recordingId, $transcriptionId) { list(, , $body) = $this->HttpClient->performHttpRequest(Common\HttpClient::REQUEST_GET, "calls/$callId/legs/$legId/recordings/$recordingId/transcriptions/$transcriptionId"); return $this->processRequest($body); }
[ "public", "function", "read", "(", "$", "callId", ",", "$", "legId", ",", "$", "recordingId", ",", "$", "transcriptionId", ")", "{", "list", "(", ",", ",", "$", "body", ")", "=", "$", "this", "->", "HttpClient", "->", "performHttpRequest", "(", "Common...
@param string $callId string @param string $legId string @param string $recordingId @param string $transcriptionId @return $this ->Object
[ "@param", "string", "$callId", "string", "@param", "string", "$legId", "string", "@param", "string", "$recordingId", "@param", "string", "$transcriptionId" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/Voice/Transcriptions.php#L114-L120
messagebird/php-rest-api
src/MessageBird/Resources/Groups.php
Groups.update
public function update($object, $id) { $objVars = get_object_vars($object); $body = array(); foreach ($objVars as $key => $value) { if (null !== $value) { $body[$key] = $value; } } $ResourceName = $this->resourceName . ($id ? '/' . $id : null); $body = json_encode($body); list(, , $body) = $this->HttpClient->performHttpRequest( Common\HttpClient::REQUEST_PATCH, $ResourceName, false, $body ); return $this->processRequest($body); }
php
public function update($object, $id) { $objVars = get_object_vars($object); $body = array(); foreach ($objVars as $key => $value) { if (null !== $value) { $body[$key] = $value; } } $ResourceName = $this->resourceName . ($id ? '/' . $id : null); $body = json_encode($body); list(, , $body) = $this->HttpClient->performHttpRequest( Common\HttpClient::REQUEST_PATCH, $ResourceName, false, $body ); return $this->processRequest($body); }
[ "public", "function", "update", "(", "$", "object", ",", "$", "id", ")", "{", "$", "objVars", "=", "get_object_vars", "(", "$", "object", ")", ";", "$", "body", "=", "array", "(", ")", ";", "foreach", "(", "$", "objVars", "as", "$", "key", "=>", ...
@param $object @param $id @throws Exceptions\AuthenticateException @throws Exceptions\HttpException @return $this ->Object @internal param array $parameters
[ "@param", "$object", "@param", "$id" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/Groups.php#L40-L60
messagebird/php-rest-api
src/MessageBird/Resources/Groups.php
Groups.getContacts
public function getContacts($id = null, $parameters = array()) { if (is_null($id)) { throw new InvalidArgumentException('No group id provided.'); } $this->setResourceName($this->resourceName . '/' . $id . '/contacts'); return $this->getList($parameters); }
php
public function getContacts($id = null, $parameters = array()) { if (is_null($id)) { throw new InvalidArgumentException('No group id provided.'); } $this->setResourceName($this->resourceName . '/' . $id . '/contacts'); return $this->getList($parameters); }
[ "public", "function", "getContacts", "(", "$", "id", "=", "null", ",", "$", "parameters", "=", "array", "(", ")", ")", "{", "if", "(", "is_null", "(", "$", "id", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'No group id provided.'", "...
@param string $id @param array|null $parameters @throws InvalidArgumentException @return mixed
[ "@param", "string", "$id", "@param", "array|null", "$parameters" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/Groups.php#L70-L78
messagebird/php-rest-api
src/MessageBird/Resources/Groups.php
Groups.addContacts
public function addContacts($contacts, $id = null) { if (!is_array($contacts)) { throw new InvalidArgumentException('No array with contacts provided.'); } if (is_null($id)) { throw new InvalidArgumentException('No group id provided.'); } $ResourceName = $this->resourceName . ($id ? '/' . $id . '/contacts' : null); $contacts = json_encode($contacts); list($responseStatus, , $responseBody) = $this->HttpClient->performHttpRequest( Common\HttpClient::REQUEST_PUT, $ResourceName, false, $contacts ); if ($responseStatus !== Common\HttpClient::HTTP_NO_CONTENT) { return json_decode($responseBody); } }
php
public function addContacts($contacts, $id = null) { if (!is_array($contacts)) { throw new InvalidArgumentException('No array with contacts provided.'); } if (is_null($id)) { throw new InvalidArgumentException('No group id provided.'); } $ResourceName = $this->resourceName . ($id ? '/' . $id . '/contacts' : null); $contacts = json_encode($contacts); list($responseStatus, , $responseBody) = $this->HttpClient->performHttpRequest( Common\HttpClient::REQUEST_PUT, $ResourceName, false, $contacts ); if ($responseStatus !== Common\HttpClient::HTTP_NO_CONTENT) { return json_decode($responseBody); } }
[ "public", "function", "addContacts", "(", "$", "contacts", ",", "$", "id", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "contacts", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'No array with contacts provided.'", ")", ";"...
@param array $contacts @param string $id @throws Exceptions\AuthenticateException @throws Exceptions\HttpException @throws InvalidArgumentException @return mixed
[ "@param", "array", "$contacts", "@param", "string", "$id" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/Groups.php#L90-L110
messagebird/php-rest-api
src/MessageBird/Resources/Groups.php
Groups.removeContact
public function removeContact($contact_id = null, $id = null) { if (is_null($contact_id) || is_null($id)) { throw new InvalidArgumentException('Null Contact or Group id.'); } $ResourceName = $this->resourceName . ($id ? '/' . $id . '/contacts/' . $contact_id : null); list($responseStatus, , $responseBody) = $this->HttpClient->performHttpRequest( Common\HttpClient::REQUEST_DELETE, $ResourceName ); if ($responseStatus !== Common\HttpClient::HTTP_NO_CONTENT) { return json_decode($responseBody); } }
php
public function removeContact($contact_id = null, $id = null) { if (is_null($contact_id) || is_null($id)) { throw new InvalidArgumentException('Null Contact or Group id.'); } $ResourceName = $this->resourceName . ($id ? '/' . $id . '/contacts/' . $contact_id : null); list($responseStatus, , $responseBody) = $this->HttpClient->performHttpRequest( Common\HttpClient::REQUEST_DELETE, $ResourceName ); if ($responseStatus !== Common\HttpClient::HTTP_NO_CONTENT) { return json_decode($responseBody); } }
[ "public", "function", "removeContact", "(", "$", "contact_id", "=", "null", ",", "$", "id", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "contact_id", ")", "||", "is_null", "(", "$", "id", ")", ")", "{", "throw", "new", "InvalidArgumentExcept...
@param string $contact_id @param string $id @throws Exceptions\AuthenticateException @throws Exceptions\HttpException @throws InvalidArgumentException; @return mixed
[ "@param", "string", "$contact_id", "@param", "string", "$id" ]
train
https://github.com/messagebird/php-rest-api/blob/22eeccb8205ff8f79e222bd496ad6318826e533b/src/MessageBird/Resources/Groups.php#L122-L136
firegento/firegento-magesetup2
Block/Imprint/Content.php
Content.getCountry
public function getCountry() { $countryCode = $this->getImprintValue('country'); if (!$countryCode) { return ''; } try { $countryInfo = $this->countryInformationAcquirer->getCountryInfo($countryCode); $countryName = $countryInfo->getFullNameLocale(); } catch (NoSuchEntityException $e) { $countryName = ''; } return $countryName; }
php
public function getCountry() { $countryCode = $this->getImprintValue('country'); if (!$countryCode) { return ''; } try { $countryInfo = $this->countryInformationAcquirer->getCountryInfo($countryCode); $countryName = $countryInfo->getFullNameLocale(); } catch (NoSuchEntityException $e) { $countryName = ''; } return $countryName; }
[ "public", "function", "getCountry", "(", ")", "{", "$", "countryCode", "=", "$", "this", "->", "getImprintValue", "(", "'country'", ")", ";", "if", "(", "!", "$", "countryCode", ")", "{", "return", "''", ";", "}", "try", "{", "$", "countryInfo", "=", ...
Retrieve the specific country name by the selected country code @return string Country
[ "Retrieve", "the", "specific", "country", "name", "by", "the", "selected", "country", "code" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Block/Imprint/Content.php#L52-L67
firegento/firegento-magesetup2
Block/Imprint/Content.php
Content.getWeb
public function getWeb($checkForProtocol = false) { $web = $this->getImprintValue('web'); if ($checkForProtocol && strlen(trim($web))) { if (strpos($web, 'http://') === false && strpos($web, 'https://') === false ) { $web = 'http://' . $web; } } return $web; }
php
public function getWeb($checkForProtocol = false) { $web = $this->getImprintValue('web'); if ($checkForProtocol && strlen(trim($web))) { if (strpos($web, 'http://') === false && strpos($web, 'https://') === false ) { $web = 'http://' . $web; } } return $web; }
[ "public", "function", "getWeb", "(", "$", "checkForProtocol", "=", "false", ")", "{", "$", "web", "=", "$", "this", "->", "getImprintValue", "(", "'web'", ")", ";", "if", "(", "$", "checkForProtocol", "&&", "strlen", "(", "trim", "(", "$", "web", ")", ...
Retrieve the setting "website". If parameter checkForProtocol is true, check if there is a valid protocol given, otherwise add http:// manually. @param bool $checkForProtocol Flag if website url should be checked for http(s) protocol @return string Website URL
[ "Retrieve", "the", "setting", "website", ".", "If", "parameter", "checkForProtocol", "is", "true", "check", "if", "there", "is", "a", "valid", "protocol", "given", "otherwise", "add", "http", ":", "//", "manually", "." ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Block/Imprint/Content.php#L76-L88
firegento/firegento-magesetup2
Block/Imprint/Content.php
Content.getEmail
public function getEmail($antispam = false) { $email = $this->getImprintValue('email'); if (!$email) { return ''; } if (!$antispam) { return $email; } $parts = explode('@', $email); if (count($parts) != 2) { return $email; } $html = '<a href="#" onclick="toRecipient();">'; $html .= $parts[0]; $html .= '<span class="no-display">nospamplease</span>@<span class="no-display">nospamplease</span>'; $html .= $parts[1]; $html .= '</a>'; $html .= $this->getEmailJs($parts); return $html; }
php
public function getEmail($antispam = false) { $email = $this->getImprintValue('email'); if (!$email) { return ''; } if (!$antispam) { return $email; } $parts = explode('@', $email); if (count($parts) != 2) { return $email; } $html = '<a href="#" onclick="toRecipient();">'; $html .= $parts[0]; $html .= '<span class="no-display">nospamplease</span>@<span class="no-display">nospamplease</span>'; $html .= $parts[1]; $html .= '</a>'; $html .= $this->getEmailJs($parts); return $html; }
[ "public", "function", "getEmail", "(", "$", "antispam", "=", "false", ")", "{", "$", "email", "=", "$", "this", "->", "getImprintValue", "(", "'email'", ")", ";", "if", "(", "!", "$", "email", ")", "{", "return", "''", ";", "}", "if", "(", "!", "...
Try to limit spam by generating a javascript email link @param boolean true @return string
[ "Try", "to", "limit", "spam", "by", "generating", "a", "javascript", "email", "link" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Block/Imprint/Content.php#L96-L120
firegento/firegento-magesetup2
Block/Imprint/Field.php
Field._toHtml
protected function _toHtml() { if ($this->getField() == 'email') { return $this->getEmail(true); } return $this->getImprintValue($this->getField()); }
php
protected function _toHtml() { if ($this->getField() == 'email') { return $this->getEmail(true); } return $this->getImprintValue($this->getField()); }
[ "protected", "function", "_toHtml", "(", ")", "{", "if", "(", "$", "this", "->", "getField", "(", ")", "==", "'email'", ")", "{", "return", "$", "this", "->", "getEmail", "(", "true", ")", ";", "}", "return", "$", "this", "->", "getImprintValue", "("...
phpcs:ignore
[ "phpcs", ":", "ignore" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Block/Imprint/Field.php#L21-L28
firegento/firegento-magesetup2
Model/System/Config/Source/Cms/Page.php
Page.toOptionArray
public function toOptionArray() { if (null === $this->options) { $collection = $this->collectionFactory->create(); $collection->addFieldToFilter('is_active', 1); $collection->setOrder('identifier', \Magento\Framework\Data\Collection::SORT_ORDER_ASC); $options = [ [ 'value' => '', 'label' => __('-- No Page --') ] ]; foreach ($collection as $item) { /** @var \Magento\Cms\Model\Page $item */ $options[] = [ 'value' => $item->getIdentifier(), 'label' => $item->getTitle() ]; } $this->options = $options; } return $this->options; }
php
public function toOptionArray() { if (null === $this->options) { $collection = $this->collectionFactory->create(); $collection->addFieldToFilter('is_active', 1); $collection->setOrder('identifier', \Magento\Framework\Data\Collection::SORT_ORDER_ASC); $options = [ [ 'value' => '', 'label' => __('-- No Page --') ] ]; foreach ($collection as $item) { /** @var \Magento\Cms\Model\Page $item */ $options[] = [ 'value' => $item->getIdentifier(), 'label' => $item->getTitle() ]; } $this->options = $options; } return $this->options; }
[ "public", "function", "toOptionArray", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "options", ")", "{", "$", "collection", "=", "$", "this", "->", "collectionFactory", "->", "create", "(", ")", ";", "$", "collection", "->", "addFieldToFil...
To option array @return array
[ "To", "option", "array" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Model/System/Config/Source/Cms/Page.php#L40-L66
firegento/firegento-magesetup2
Plugin/Catalog/ListProductPlugin.php
ListProductPlugin.aroundGetProductDetailsHtml
public function aroundGetProductDetailsHtml( \Magento\Catalog\Block\Product\ListProduct $subject, \Closure $proceed, \Magento\Catalog\Model\Product $product ) { $result = $proceed($product); $deliveryBlock = $subject->getLayout()->getBlock('product.info.delivery'); if ($deliveryBlock) { $deliveryBlock->setProduct($product); if ((bool) $this->_scopeConfig->getValue( 'catalog/frontend/display_delivery_time', \Magento\Store\Model\ScopeInterface::SCOPE_STORE )) { $result = $deliveryBlock->toHtml() . $result; } } return $result; }
php
public function aroundGetProductDetailsHtml( \Magento\Catalog\Block\Product\ListProduct $subject, \Closure $proceed, \Magento\Catalog\Model\Product $product ) { $result = $proceed($product); $deliveryBlock = $subject->getLayout()->getBlock('product.info.delivery'); if ($deliveryBlock) { $deliveryBlock->setProduct($product); if ((bool) $this->_scopeConfig->getValue( 'catalog/frontend/display_delivery_time', \Magento\Store\Model\ScopeInterface::SCOPE_STORE )) { $result = $deliveryBlock->toHtml() . $result; } } return $result; }
[ "public", "function", "aroundGetProductDetailsHtml", "(", "\\", "Magento", "\\", "Catalog", "\\", "Block", "\\", "Product", "\\", "ListProduct", "$", "subject", ",", "\\", "Closure", "$", "proceed", ",", "\\", "Magento", "\\", "Catalog", "\\", "Model", "\\", ...
Retrieve product details html @param \Magento\Catalog\Block\Product\ListProduct @param \Closure $proceed @param \Magento\Catalog\Model\Product $product @return string
[ "Retrieve", "product", "details", "html" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Plugin/Catalog/ListProductPlugin.php#L32-L52
firegento/firegento-magesetup2
Command/SetupRunCommand.php
SetupRunCommand.configure
protected function configure() { $this->setName(self::COMMAND_NAME) ->setDescription('Run MageSetup setup') ->setDefinition($this->getInputList()); parent::configure(); }
php
protected function configure() { $this->setName(self::COMMAND_NAME) ->setDescription('Run MageSetup setup') ->setDefinition($this->getInputList()); parent::configure(); }
[ "protected", "function", "configure", "(", ")", "{", "$", "this", "->", "setName", "(", "self", "::", "COMMAND_NAME", ")", "->", "setDescription", "(", "'Run MageSetup setup'", ")", "->", "setDefinition", "(", "$", "this", "->", "getInputList", "(", ")", ")"...
{@inheritdoc}
[ "{" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Command/SetupRunCommand.php#L100-L107
firegento/firegento-magesetup2
Model/Setup/SubProcessor/CmsSubProcessor.php
CmsSubProcessor.createCmsPage
private function createCmsPage($pageData) { // Check if template filename exists $filename = $pageData['filename']; $template = $this->getTemplatePath('pages') . $filename; // phpcs:ignore if (!file_exists($template)) { return; } // Remove filename from data unset($pageData['filename']); // Fetch template content // phpcs:ignore $templateContent = @file_get_contents($template); $data = [ 'stores' => [0], 'is_active' => 1, ]; if (preg_match('/<!--@title\s*(.*?)\s*@-->/u', $templateContent, $matches)) { $data['title'] = $matches[1]; $data['content_heading'] = $matches[1]; $templateContent = str_replace($matches[0], '', $templateContent); } if (preg_match('/<!--@identifier\s*((?:.)*?)\s*@-->/us', $templateContent, $matches)) { $data['identifier'] = $matches[1]; $templateContent = str_replace($matches[0], '', $templateContent); } if (isset($pageData['page_layout']) && !empty($pageData['page_layout'])) { $data['page_layout'] = $pageData['page_layout']; } else { $data['page_layout'] = '1column'; } /** * Remove comment lines */ $content = preg_replace('#\{\*.*\*\}#suU', '', $templateContent); $content = trim($content); $data['content'] = $content; $page = $this->pageFactory->create(); $page = $page->load($data['identifier'], 'identifier'); if ($page->getId()) { $data['page_id'] = $page->getId(); } $page->addData($data); $this->pageRepository->save($page); if (isset($pageData['config_option'])) { $this->saveConfigValue($pageData['config_option'], $data['identifier'], 0); } }
php
private function createCmsPage($pageData) { // Check if template filename exists $filename = $pageData['filename']; $template = $this->getTemplatePath('pages') . $filename; // phpcs:ignore if (!file_exists($template)) { return; } // Remove filename from data unset($pageData['filename']); // Fetch template content // phpcs:ignore $templateContent = @file_get_contents($template); $data = [ 'stores' => [0], 'is_active' => 1, ]; if (preg_match('/<!--@title\s*(.*?)\s*@-->/u', $templateContent, $matches)) { $data['title'] = $matches[1]; $data['content_heading'] = $matches[1]; $templateContent = str_replace($matches[0], '', $templateContent); } if (preg_match('/<!--@identifier\s*((?:.)*?)\s*@-->/us', $templateContent, $matches)) { $data['identifier'] = $matches[1]; $templateContent = str_replace($matches[0], '', $templateContent); } if (isset($pageData['page_layout']) && !empty($pageData['page_layout'])) { $data['page_layout'] = $pageData['page_layout']; } else { $data['page_layout'] = '1column'; } /** * Remove comment lines */ $content = preg_replace('#\{\*.*\*\}#suU', '', $templateContent); $content = trim($content); $data['content'] = $content; $page = $this->pageFactory->create(); $page = $page->load($data['identifier'], 'identifier'); if ($page->getId()) { $data['page_id'] = $page->getId(); } $page->addData($data); $this->pageRepository->save($page); if (isset($pageData['config_option'])) { $this->saveConfigValue($pageData['config_option'], $data['identifier'], 0); } }
[ "private", "function", "createCmsPage", "(", "$", "pageData", ")", "{", "// Check if template filename exists", "$", "filename", "=", "$", "pageData", "[", "'filename'", "]", ";", "$", "template", "=", "$", "this", "->", "getTemplatePath", "(", "'pages'", ")", ...
Create a cms page with the given data @param array $pageData
[ "Create", "a", "cms", "page", "with", "the", "given", "data" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Model/Setup/SubProcessor/CmsSubProcessor.php#L104-L163
firegento/firegento-magesetup2
Model/Setup/SubProcessor/CmsSubProcessor.php
CmsSubProcessor.createCmsBlock
private function createCmsBlock($blockData) { // Check if template filename exists $filename = $blockData['filename']; $template = $this->getTemplatePath('blocks') . $filename; // phpcs:ignore if (!file_exists($template)) { return; } // Remove filename from data unset($blockData['filename']); // Fetch template content // phpcs:ignore $templateContent = @file_get_contents($template); $data = [ 'stores' => [0], 'is_active' => 1, ]; // Find title if (preg_match('/<!--@title\s*(.*?)\s*@-->/u', $templateContent, $matches)) { $data['title'] = $matches[1]; $templateContent = str_replace($matches[0], '', $templateContent); } // Remove comment lines $content = preg_replace('#\{\*.*\*\}#suU', '', $templateContent); $content = trim($content); $data['content'] = $content; $block = $this->blockFactory->create(); $block = $block->load($blockData['identifier'], 'identifier'); if ($block->getId()) { $data['block_id'] = $block->getId(); } $data['identifier'] = $blockData['identifier']; $block->addData($data); $this->blockRepository->save($block); }
php
private function createCmsBlock($blockData) { // Check if template filename exists $filename = $blockData['filename']; $template = $this->getTemplatePath('blocks') . $filename; // phpcs:ignore if (!file_exists($template)) { return; } // Remove filename from data unset($blockData['filename']); // Fetch template content // phpcs:ignore $templateContent = @file_get_contents($template); $data = [ 'stores' => [0], 'is_active' => 1, ]; // Find title if (preg_match('/<!--@title\s*(.*?)\s*@-->/u', $templateContent, $matches)) { $data['title'] = $matches[1]; $templateContent = str_replace($matches[0], '', $templateContent); } // Remove comment lines $content = preg_replace('#\{\*.*\*\}#suU', '', $templateContent); $content = trim($content); $data['content'] = $content; $block = $this->blockFactory->create(); $block = $block->load($blockData['identifier'], 'identifier'); if ($block->getId()) { $data['block_id'] = $block->getId(); } $data['identifier'] = $blockData['identifier']; $block->addData($data); $this->blockRepository->save($block); }
[ "private", "function", "createCmsBlock", "(", "$", "blockData", ")", "{", "// Check if template filename exists", "$", "filename", "=", "$", "blockData", "[", "'filename'", "]", ";", "$", "template", "=", "$", "this", "->", "getTemplatePath", "(", "'blocks'", ")...
Create a cms block with the given data @param array $blockData
[ "Create", "a", "cms", "block", "with", "the", "given", "data" ]
train
https://github.com/firegento/firegento-magesetup2/blob/d1727b581dd703f72babecab125b600446be06de/Model/Setup/SubProcessor/CmsSubProcessor.php#L170-L213