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
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
OpenConext-Attic/OpenConext-engineblock-metadata
src/MetadataRepository/CompositeMetadataRepository.php
CompositeMetadataRepository.fetchServiceProviderArp
public function fetchServiceProviderArp(ServiceProvider $serviceProvider) { foreach ($this->orderedRepositories as $repository) { if (!$repository->findServiceProviderByEntityId($serviceProvider->entityId)) { continue; } return $repository->fetchServiceProviderArp($serviceProvider); } throw new \RuntimeException( __METHOD__ . ' was unable to find a repository for SP: ' . $serviceProvider->entityId ); }
php
public function fetchServiceProviderArp(ServiceProvider $serviceProvider) { foreach ($this->orderedRepositories as $repository) { if (!$repository->findServiceProviderByEntityId($serviceProvider->entityId)) { continue; } return $repository->fetchServiceProviderArp($serviceProvider); } throw new \RuntimeException( __METHOD__ . ' was unable to find a repository for SP: ' . $serviceProvider->entityId ); }
[ "public", "function", "fetchServiceProviderArp", "(", "ServiceProvider", "$", "serviceProvider", ")", "{", "foreach", "(", "$", "this", "->", "orderedRepositories", "as", "$", "repository", ")", "{", "if", "(", "!", "$", "repository", "->", "findServiceProviderByEntityId", "(", "$", "serviceProvider", "->", "entityId", ")", ")", "{", "continue", ";", "}", "return", "$", "repository", "->", "fetchServiceProviderArp", "(", "$", "serviceProvider", ")", ";", "}", "throw", "new", "\\", "RuntimeException", "(", "__METHOD__", ".", "' was unable to find a repository for SP: '", ".", "$", "serviceProvider", "->", "entityId", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/OpenConext-Attic/OpenConext-engineblock-metadata/blob/236e2f52ef9cf28e71404544a1c4388f63ee535d/src/MetadataRepository/CompositeMetadataRepository.php#L275-L288
OpenConext-Attic/OpenConext-engineblock-metadata
src/MetadataRepository/CompositeMetadataRepository.php
CompositeMetadataRepository.findAllowedIdpEntityIdsForSp
public function findAllowedIdpEntityIdsForSp(ServiceProvider $serviceProvider) { $allowed = array(); foreach ($this->orderedRepositories as $repository) { $allowed += $repository->findAllowedIdpEntityIdsForSp($serviceProvider); } return array_values(array_unique($allowed)); }
php
public function findAllowedIdpEntityIdsForSp(ServiceProvider $serviceProvider) { $allowed = array(); foreach ($this->orderedRepositories as $repository) { $allowed += $repository->findAllowedIdpEntityIdsForSp($serviceProvider); } return array_values(array_unique($allowed)); }
[ "public", "function", "findAllowedIdpEntityIdsForSp", "(", "ServiceProvider", "$", "serviceProvider", ")", "{", "$", "allowed", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "orderedRepositories", "as", "$", "repository", ")", "{", "$", "allowed", "+=", "$", "repository", "->", "findAllowedIdpEntityIdsForSp", "(", "$", "serviceProvider", ")", ";", "}", "return", "array_values", "(", "array_unique", "(", "$", "allowed", ")", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/OpenConext-Attic/OpenConext-engineblock-metadata/blob/236e2f52ef9cf28e71404544a1c4388f63ee535d/src/MetadataRepository/CompositeMetadataRepository.php#L293-L301
elifesciences/bus-sdk-php
src/Queue/SqsWatchableQueue.php
SqsWatchableQueue.enqueue
public function enqueue(QueueItem $item) { $this->client->sendMessage([ 'QueueUrl' => $this->url, 'MessageBody' => json_encode([ 'type' => $item->getType(), 'id' => $item->getId(), ]), ]); }
php
public function enqueue(QueueItem $item) { $this->client->sendMessage([ 'QueueUrl' => $this->url, 'MessageBody' => json_encode([ 'type' => $item->getType(), 'id' => $item->getId(), ]), ]); }
[ "public", "function", "enqueue", "(", "QueueItem", "$", "item", ")", "{", "$", "this", "->", "client", "->", "sendMessage", "(", "[", "'QueueUrl'", "=>", "$", "this", "->", "url", ",", "'MessageBody'", "=>", "json_encode", "(", "[", "'type'", "=>", "$", "item", "->", "getType", "(", ")", ",", "'id'", "=>", "$", "item", "->", "getId", "(", ")", ",", "]", ")", ",", "]", ")", ";", "}" ]
Adds item to the queue.
[ "Adds", "item", "to", "the", "queue", "." ]
train
https://github.com/elifesciences/bus-sdk-php/blob/3af0739fac110e79ea7f21aadf8d17b891f3b918/src/Queue/SqsWatchableQueue.php#L25-L34
elifesciences/bus-sdk-php
src/Queue/SqsWatchableQueue.php
SqsWatchableQueue.dequeue
public function dequeue() { $message = $this->client->receiveMessage([ 'AttributeNames' => ['ApproximateReceiveCount'], 'QueueUrl' => $this->url, 'WaitTimeSeconds' => $this->pollingTimeout, 'VisibilityTimeout' => $this->visibilityTimeout, ])->toArray(); if (!SqsMessageTransformer::hasItems($message)) { return false; } return SqsMessageTransformer::fromMessage($message); }
php
public function dequeue() { $message = $this->client->receiveMessage([ 'AttributeNames' => ['ApproximateReceiveCount'], 'QueueUrl' => $this->url, 'WaitTimeSeconds' => $this->pollingTimeout, 'VisibilityTimeout' => $this->visibilityTimeout, ])->toArray(); if (!SqsMessageTransformer::hasItems($message)) { return false; } return SqsMessageTransformer::fromMessage($message); }
[ "public", "function", "dequeue", "(", ")", "{", "$", "message", "=", "$", "this", "->", "client", "->", "receiveMessage", "(", "[", "'AttributeNames'", "=>", "[", "'ApproximateReceiveCount'", "]", ",", "'QueueUrl'", "=>", "$", "this", "->", "url", ",", "'WaitTimeSeconds'", "=>", "$", "this", "->", "pollingTimeout", ",", "'VisibilityTimeout'", "=>", "$", "this", "->", "visibilityTimeout", ",", "]", ")", "->", "toArray", "(", ")", ";", "if", "(", "!", "SqsMessageTransformer", "::", "hasItems", "(", "$", "message", ")", ")", "{", "return", "false", ";", "}", "return", "SqsMessageTransformer", "::", "fromMessage", "(", "$", "message", ")", ";", "}" ]
Get an item from the queue and start is processing, making it invisible to other processes for $timeoutOverride seconds.
[ "Get", "an", "item", "from", "the", "queue", "and", "start", "is", "processing", "making", "it", "invisible", "to", "other", "processes", "for", "$timeoutOverride", "seconds", "." ]
train
https://github.com/elifesciences/bus-sdk-php/blob/3af0739fac110e79ea7f21aadf8d17b891f3b918/src/Queue/SqsWatchableQueue.php#L40-L54
elifesciences/bus-sdk-php
src/Queue/SqsWatchableQueue.php
SqsWatchableQueue.commit
public function commit(QueueItem $item) { $this->client->deleteMessage([ 'QueueUrl' => $this->url, 'ReceiptHandle' => $item->getReceipt(), ]); }
php
public function commit(QueueItem $item) { $this->client->deleteMessage([ 'QueueUrl' => $this->url, 'ReceiptHandle' => $item->getReceipt(), ]); }
[ "public", "function", "commit", "(", "QueueItem", "$", "item", ")", "{", "$", "this", "->", "client", "->", "deleteMessage", "(", "[", "'QueueUrl'", "=>", "$", "this", "->", "url", ",", "'ReceiptHandle'", "=>", "$", "item", "->", "getReceipt", "(", ")", ",", "]", ")", ";", "}" ]
Commits to removing item from queue, marks item as done and processed.
[ "Commits", "to", "removing", "item", "from", "queue", "marks", "item", "as", "done", "and", "processed", "." ]
train
https://github.com/elifesciences/bus-sdk-php/blob/3af0739fac110e79ea7f21aadf8d17b891f3b918/src/Queue/SqsWatchableQueue.php#L59-L65
elifesciences/bus-sdk-php
src/Queue/SqsWatchableQueue.php
SqsWatchableQueue.release
public function release(QueueItem $item) { $this->client->changeMessageVisibility([ 'QueueUrl' => $this->url, 'ReceiptHandle' => $item->getReceipt(), 'VisibilityTimeout' => $this->visibilityTimeout * ($item->getAttempts() + 1), ]); }
php
public function release(QueueItem $item) { $this->client->changeMessageVisibility([ 'QueueUrl' => $this->url, 'ReceiptHandle' => $item->getReceipt(), 'VisibilityTimeout' => $this->visibilityTimeout * ($item->getAttempts() + 1), ]); }
[ "public", "function", "release", "(", "QueueItem", "$", "item", ")", "{", "$", "this", "->", "client", "->", "changeMessageVisibility", "(", "[", "'QueueUrl'", "=>", "$", "this", "->", "url", ",", "'ReceiptHandle'", "=>", "$", "item", "->", "getReceipt", "(", ")", ",", "'VisibilityTimeout'", "=>", "$", "this", "->", "visibilityTimeout", "*", "(", "$", "item", "->", "getAttempts", "(", ")", "+", "1", ")", ",", "]", ")", ";", "}" ]
This will happen when an error happens, we release the item back into the queue.
[ "This", "will", "happen", "when", "an", "error", "happens", "we", "release", "the", "item", "back", "into", "the", "queue", "." ]
train
https://github.com/elifesciences/bus-sdk-php/blob/3af0739fac110e79ea7f21aadf8d17b891f3b918/src/Queue/SqsWatchableQueue.php#L70-L77
mitogh/Katana
src/Filters/Page.php
Page.filter_by_template_page
public function filter_by_template_page( $sizes, $id = 0 ) { $template = get_page_template_slug( $id ); if ( empty( $template ) ) { return $sizes; } $template_name = Formatter::to_filter_format( $template ); return apply_filters( Formatter::katana_filter( $template_name ), $sizes ); }
php
public function filter_by_template_page( $sizes, $id = 0 ) { $template = get_page_template_slug( $id ); if ( empty( $template ) ) { return $sizes; } $template_name = Formatter::to_filter_format( $template ); return apply_filters( Formatter::katana_filter( $template_name ), $sizes ); }
[ "public", "function", "filter_by_template_page", "(", "$", "sizes", ",", "$", "id", "=", "0", ")", "{", "$", "template", "=", "get_page_template_slug", "(", "$", "id", ")", ";", "if", "(", "empty", "(", "$", "template", ")", ")", "{", "return", "$", "sizes", ";", "}", "$", "template_name", "=", "Formatter", "::", "to_filter_format", "(", "$", "template", ")", ";", "return", "apply_filters", "(", "Formatter", "::", "katana_filter", "(", "$", "template_name", ")", ",", "$", "sizes", ")", ";", "}" ]
Filter that allow to change the sizes on pages that uses custom page templates. @since 1.1.0 @param array $sizes The images sizes. @param int $id The id of the post, page or custom post type. @return return the array with the new sizes.
[ "Filter", "that", "allow", "to", "change", "the", "sizes", "on", "pages", "that", "uses", "custom", "page", "templates", "." ]
train
https://github.com/mitogh/Katana/blob/9eb7267f061fbe555dbe9c12461650bb4153915f/src/Filters/Page.php#L32-L39
Subscribo/klarna-invoice-sdk-wrapped
src/Currency.php
KlarnaCurrency.fromCode
public static function fromCode($val) { switch(strtolower($val)) { case 'dkk': return self::DKK; case 'eur': case 'euro': return self::EUR; case 'nok': return self::NOK; case 'sek': return self::SEK; default: return null; } }
php
public static function fromCode($val) { switch(strtolower($val)) { case 'dkk': return self::DKK; case 'eur': case 'euro': return self::EUR; case 'nok': return self::NOK; case 'sek': return self::SEK; default: return null; } }
[ "public", "static", "function", "fromCode", "(", "$", "val", ")", "{", "switch", "(", "strtolower", "(", "$", "val", ")", ")", "{", "case", "'dkk'", ":", "return", "self", "::", "DKK", ";", "case", "'eur'", ":", "case", "'euro'", ":", "return", "self", "::", "EUR", ";", "case", "'nok'", ":", "return", "self", "::", "NOK", ";", "case", "'sek'", ":", "return", "self", "::", "SEK", ";", "default", ":", "return", "null", ";", "}", "}" ]
Converts a currency code, e.g. 'eur' to the KlarnaCurrency constant. @param string $val currency code @return int|null
[ "Converts", "a", "currency", "code", "e", ".", "g", ".", "eur", "to", "the", "KlarnaCurrency", "constant", "." ]
train
https://github.com/Subscribo/klarna-invoice-sdk-wrapped/blob/4a45ddd9ec444f5a6d02628ad65e635a3e12611c/src/Currency.php#L64-L79
Subscribo/klarna-invoice-sdk-wrapped
src/Currency.php
KlarnaCurrency.getCode
public static function getCode($val) { switch($val) { case self::DKK: return 'dkk'; case self::EUR: return 'eur'; case self::NOK: return 'nok'; case self::SEK: return 'sek'; default: return null; } }
php
public static function getCode($val) { switch($val) { case self::DKK: return 'dkk'; case self::EUR: return 'eur'; case self::NOK: return 'nok'; case self::SEK: return 'sek'; default: return null; } }
[ "public", "static", "function", "getCode", "(", "$", "val", ")", "{", "switch", "(", "$", "val", ")", "{", "case", "self", "::", "DKK", ":", "return", "'dkk'", ";", "case", "self", "::", "EUR", ":", "return", "'eur'", ";", "case", "self", "::", "NOK", ":", "return", "'nok'", ";", "case", "self", "::", "SEK", ":", "return", "'sek'", ";", "default", ":", "return", "null", ";", "}", "}" ]
Converts a KlarnaCurrency constant to the respective language code. @param int $val KlarnaCurrency constant @return string|null
[ "Converts", "a", "KlarnaCurrency", "constant", "to", "the", "respective", "language", "code", "." ]
train
https://github.com/Subscribo/klarna-invoice-sdk-wrapped/blob/4a45ddd9ec444f5a6d02628ad65e635a3e12611c/src/Currency.php#L88-L102
porkchopsandwiches/doctrine-utilities
lib/src/PorkChopSandwiches/Doctrine/Utilities/Types/UTCDateTimeType.php
UTCDateTimeType.convertToDatabaseValue
public function convertToDatabaseValue ($value, AbstractPlatform $platform) { if ($value === null) { return null; } $value -> setTimezone(self::getUTCTimeZone()); return $value -> format($platform -> getDateTimeFormatString()); }
php
public function convertToDatabaseValue ($value, AbstractPlatform $platform) { if ($value === null) { return null; } $value -> setTimezone(self::getUTCTimeZone()); return $value -> format($platform -> getDateTimeFormatString()); }
[ "public", "function", "convertToDatabaseValue", "(", "$", "value", ",", "AbstractPlatform", "$", "platform", ")", "{", "if", "(", "$", "value", "===", "null", ")", "{", "return", "null", ";", "}", "$", "value", "->", "setTimezone", "(", "self", "::", "getUTCTimeZone", "(", ")", ")", ";", "return", "$", "value", "->", "format", "(", "$", "platform", "->", "getDateTimeFormatString", "(", ")", ")", ";", "}" ]
Converts a PHP-land value (a DateTime instance) to a Database string value. @param DateTime|null $value @param AbstractPlatform $platform @return string|null
[ "Converts", "a", "PHP", "-", "land", "value", "(", "a", "DateTime", "instance", ")", "to", "a", "Database", "string", "value", "." ]
train
https://github.com/porkchopsandwiches/doctrine-utilities/blob/cc5e4268bac36c68af62d69d9512a0dd01ee310f/lib/src/PorkChopSandwiches/Doctrine/Utilities/Types/UTCDateTimeType.php#L29-L36
mcustiel/phiremock-server
src/Utils/RequestExpectationComparator.php
RequestExpectationComparator.equals
public function equals(ServerRequestInterface $httpRequest, MockConfig $expectation) { $this->logger->debug('Checking if request matches an expectation'); if (!$this->isExpectedScenarioState($expectation)) { return false; } $expectedRequest = $expectation->getRequest(); $atLeastOneExecution = $this->compareRequestParts($httpRequest, $expectedRequest); if (null !== $atLeastOneExecution && $expectedRequest->getHeaders()) { $this->logger->debug('Checking headers against expectation'); return $this->requestHeadersMatchExpectation($httpRequest, $expectedRequest); } return (bool) $atLeastOneExecution; }
php
public function equals(ServerRequestInterface $httpRequest, MockConfig $expectation) { $this->logger->debug('Checking if request matches an expectation'); if (!$this->isExpectedScenarioState($expectation)) { return false; } $expectedRequest = $expectation->getRequest(); $atLeastOneExecution = $this->compareRequestParts($httpRequest, $expectedRequest); if (null !== $atLeastOneExecution && $expectedRequest->getHeaders()) { $this->logger->debug('Checking headers against expectation'); return $this->requestHeadersMatchExpectation($httpRequest, $expectedRequest); } return (bool) $atLeastOneExecution; }
[ "public", "function", "equals", "(", "ServerRequestInterface", "$", "httpRequest", ",", "MockConfig", "$", "expectation", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "'Checking if request matches an expectation'", ")", ";", "if", "(", "!", "$", "this", "->", "isExpectedScenarioState", "(", "$", "expectation", ")", ")", "{", "return", "false", ";", "}", "$", "expectedRequest", "=", "$", "expectation", "->", "getRequest", "(", ")", ";", "$", "atLeastOneExecution", "=", "$", "this", "->", "compareRequestParts", "(", "$", "httpRequest", ",", "$", "expectedRequest", ")", ";", "if", "(", "null", "!==", "$", "atLeastOneExecution", "&&", "$", "expectedRequest", "->", "getHeaders", "(", ")", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "'Checking headers against expectation'", ")", ";", "return", "$", "this", "->", "requestHeadersMatchExpectation", "(", "$", "httpRequest", ",", "$", "expectedRequest", ")", ";", "}", "return", "(", "bool", ")", "$", "atLeastOneExecution", ";", "}" ]
@param \Psr\Http\Message\ServerRequestInterface $httpRequest @param \Mcustiel\Phiremock\Domain\MockConfig $expectation @return bool
[ "@param", "\\", "Psr", "\\", "Http", "\\", "Message", "\\", "ServerRequestInterface", "$httpRequest", "@param", "\\", "Mcustiel", "\\", "Phiremock", "\\", "Domain", "\\", "MockConfig", "$expectation" ]
train
https://github.com/mcustiel/phiremock-server/blob/7be42ce7c5c4d441410d80e158477910924cfbd9/src/Utils/RequestExpectationComparator.php#L68-L87
mcustiel/phiremock-server
src/Utils/RequestExpectationComparator.php
RequestExpectationComparator.compareRequestParts
private function compareRequestParts(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest) { $atLeastOneExecution = false; $requestParts = ['Method', 'Url', 'Body']; foreach ($requestParts as $requestPart) { $getter = "get{$requestPart}"; $matcher = "request{$requestPart}MatchesExpectation"; if ($expectedRequest->{$getter}()) { $this->logger->debug("Checking {$requestPart} against expectation"); if (!$this->{$matcher}($httpRequest, $expectedRequest)) { return null; } $atLeastOneExecution = true; } } return $atLeastOneExecution; }
php
private function compareRequestParts(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest) { $atLeastOneExecution = false; $requestParts = ['Method', 'Url', 'Body']; foreach ($requestParts as $requestPart) { $getter = "get{$requestPart}"; $matcher = "request{$requestPart}MatchesExpectation"; if ($expectedRequest->{$getter}()) { $this->logger->debug("Checking {$requestPart} against expectation"); if (!$this->{$matcher}($httpRequest, $expectedRequest)) { return null; } $atLeastOneExecution = true; } } return $atLeastOneExecution; }
[ "private", "function", "compareRequestParts", "(", "ServerRequestInterface", "$", "httpRequest", ",", "RequestConditions", "$", "expectedRequest", ")", "{", "$", "atLeastOneExecution", "=", "false", ";", "$", "requestParts", "=", "[", "'Method'", ",", "'Url'", ",", "'Body'", "]", ";", "foreach", "(", "$", "requestParts", "as", "$", "requestPart", ")", "{", "$", "getter", "=", "\"get{$requestPart}\"", ";", "$", "matcher", "=", "\"request{$requestPart}MatchesExpectation\"", ";", "if", "(", "$", "expectedRequest", "->", "{", "$", "getter", "}", "(", ")", ")", "{", "$", "this", "->", "logger", "->", "debug", "(", "\"Checking {$requestPart} against expectation\"", ")", ";", "if", "(", "!", "$", "this", "->", "{", "$", "matcher", "}", "(", "$", "httpRequest", ",", "$", "expectedRequest", ")", ")", "{", "return", "null", ";", "}", "$", "atLeastOneExecution", "=", "true", ";", "}", "}", "return", "$", "atLeastOneExecution", ";", "}" ]
@param \Psr\Http\Message\ServerRequestInterface $httpRequest @param \Mcustiel\Phiremock\Domain\RequestConditions $expectedRequest @return null|bool
[ "@param", "\\", "Psr", "\\", "Http", "\\", "Message", "\\", "ServerRequestInterface", "$httpRequest", "@param", "\\", "Mcustiel", "\\", "Phiremock", "\\", "Domain", "\\", "RequestConditions", "$expectedRequest" ]
train
https://github.com/mcustiel/phiremock-server/blob/7be42ce7c5c4d441410d80e158477910924cfbd9/src/Utils/RequestExpectationComparator.php#L95-L113
mcustiel/phiremock-server
src/Utils/RequestExpectationComparator.php
RequestExpectationComparator.isExpectedScenarioState
private function isExpectedScenarioState(MockConfig $expectation) { if ($expectation->getRequest()->hasScenarioState()) { $this->checkScenarioNameOrThrowException($expectation); $this->logger->debug('Checking scenario state again expectation'); $scenarioState = $this->scenarioStorage->getScenarioState( $expectation->getScenarioName() ); if (!$expectation->getRequest()->getScenarioState()->equals($scenarioState)) { return false; } } return true; }
php
private function isExpectedScenarioState(MockConfig $expectation) { if ($expectation->getRequest()->hasScenarioState()) { $this->checkScenarioNameOrThrowException($expectation); $this->logger->debug('Checking scenario state again expectation'); $scenarioState = $this->scenarioStorage->getScenarioState( $expectation->getScenarioName() ); if (!$expectation->getRequest()->getScenarioState()->equals($scenarioState)) { return false; } } return true; }
[ "private", "function", "isExpectedScenarioState", "(", "MockConfig", "$", "expectation", ")", "{", "if", "(", "$", "expectation", "->", "getRequest", "(", ")", "->", "hasScenarioState", "(", ")", ")", "{", "$", "this", "->", "checkScenarioNameOrThrowException", "(", "$", "expectation", ")", ";", "$", "this", "->", "logger", "->", "debug", "(", "'Checking scenario state again expectation'", ")", ";", "$", "scenarioState", "=", "$", "this", "->", "scenarioStorage", "->", "getScenarioState", "(", "$", "expectation", "->", "getScenarioName", "(", ")", ")", ";", "if", "(", "!", "$", "expectation", "->", "getRequest", "(", ")", "->", "getScenarioState", "(", ")", "->", "equals", "(", "$", "scenarioState", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
@param MockConfig $expectation @return bool
[ "@param", "MockConfig", "$expectation" ]
train
https://github.com/mcustiel/phiremock-server/blob/7be42ce7c5c4d441410d80e158477910924cfbd9/src/Utils/RequestExpectationComparator.php#L120-L134
mcustiel/phiremock-server
src/Utils/RequestExpectationComparator.php
RequestExpectationComparator.requestMethodMatchesExpectation
private function requestMethodMatchesExpectation(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest) { $inputSource = $this->inputSourceLocator->locate(InputSources::METHOD); $matcher = $this->matcherLocator->locate(Matchers::SAME_STRING); return $matcher->match( $inputSource->getValue($httpRequest), $expectedRequest->getMethod()->asString() ); }
php
private function requestMethodMatchesExpectation(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest) { $inputSource = $this->inputSourceLocator->locate(InputSources::METHOD); $matcher = $this->matcherLocator->locate(Matchers::SAME_STRING); return $matcher->match( $inputSource->getValue($httpRequest), $expectedRequest->getMethod()->asString() ); }
[ "private", "function", "requestMethodMatchesExpectation", "(", "ServerRequestInterface", "$", "httpRequest", ",", "RequestConditions", "$", "expectedRequest", ")", "{", "$", "inputSource", "=", "$", "this", "->", "inputSourceLocator", "->", "locate", "(", "InputSources", "::", "METHOD", ")", ";", "$", "matcher", "=", "$", "this", "->", "matcherLocator", "->", "locate", "(", "Matchers", "::", "SAME_STRING", ")", ";", "return", "$", "matcher", "->", "match", "(", "$", "inputSource", "->", "getValue", "(", "$", "httpRequest", ")", ",", "$", "expectedRequest", "->", "getMethod", "(", ")", "->", "asString", "(", ")", ")", ";", "}" ]
@param ServerRequestInterface $httpRequest @param RequestConditions $expectedRequest @return bool
[ "@param", "ServerRequestInterface", "$httpRequest", "@param", "RequestConditions", "$expectedRequest" ]
train
https://github.com/mcustiel/phiremock-server/blob/7be42ce7c5c4d441410d80e158477910924cfbd9/src/Utils/RequestExpectationComparator.php#L156-L165
mcustiel/phiremock-server
src/Utils/RequestExpectationComparator.php
RequestExpectationComparator.requestUrlMatchesExpectation
private function requestUrlMatchesExpectation(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest) { $inputSource = $this->inputSourceLocator->locate('url'); $matcher = $this->matcherLocator->locate($expectedRequest->getUrl()->getMatcher()->asString()); return $matcher->match( $inputSource->getValue($httpRequest), $expectedRequest->getUrl()->getValue()->asString() ); }
php
private function requestUrlMatchesExpectation(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest) { $inputSource = $this->inputSourceLocator->locate('url'); $matcher = $this->matcherLocator->locate($expectedRequest->getUrl()->getMatcher()->asString()); return $matcher->match( $inputSource->getValue($httpRequest), $expectedRequest->getUrl()->getValue()->asString() ); }
[ "private", "function", "requestUrlMatchesExpectation", "(", "ServerRequestInterface", "$", "httpRequest", ",", "RequestConditions", "$", "expectedRequest", ")", "{", "$", "inputSource", "=", "$", "this", "->", "inputSourceLocator", "->", "locate", "(", "'url'", ")", ";", "$", "matcher", "=", "$", "this", "->", "matcherLocator", "->", "locate", "(", "$", "expectedRequest", "->", "getUrl", "(", ")", "->", "getMatcher", "(", ")", "->", "asString", "(", ")", ")", ";", "return", "$", "matcher", "->", "match", "(", "$", "inputSource", "->", "getValue", "(", "$", "httpRequest", ")", ",", "$", "expectedRequest", "->", "getUrl", "(", ")", "->", "getValue", "(", ")", "->", "asString", "(", ")", ")", ";", "}" ]
@param ServerRequestInterface $httpRequest @param RequestConditions $expectedRequest @return bool
[ "@param", "ServerRequestInterface", "$httpRequest", "@param", "RequestConditions", "$expectedRequest" ]
train
https://github.com/mcustiel/phiremock-server/blob/7be42ce7c5c4d441410d80e158477910924cfbd9/src/Utils/RequestExpectationComparator.php#L173-L182
mcustiel/phiremock-server
src/Utils/RequestExpectationComparator.php
RequestExpectationComparator.requestBodyMatchesExpectation
private function requestBodyMatchesExpectation(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest) { $inputSource = $this->inputSourceLocator->locate('body'); $matcher = $this->matcherLocator->locate( $expectedRequest->getBody()->getMatcher()->asString() ); return $matcher->match( $inputSource->getValue($httpRequest), $expectedRequest->getBody()->getValue()->asString() ); }
php
private function requestBodyMatchesExpectation(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest) { $inputSource = $this->inputSourceLocator->locate('body'); $matcher = $this->matcherLocator->locate( $expectedRequest->getBody()->getMatcher()->asString() ); return $matcher->match( $inputSource->getValue($httpRequest), $expectedRequest->getBody()->getValue()->asString() ); }
[ "private", "function", "requestBodyMatchesExpectation", "(", "ServerRequestInterface", "$", "httpRequest", ",", "RequestConditions", "$", "expectedRequest", ")", "{", "$", "inputSource", "=", "$", "this", "->", "inputSourceLocator", "->", "locate", "(", "'body'", ")", ";", "$", "matcher", "=", "$", "this", "->", "matcherLocator", "->", "locate", "(", "$", "expectedRequest", "->", "getBody", "(", ")", "->", "getMatcher", "(", ")", "->", "asString", "(", ")", ")", ";", "return", "$", "matcher", "->", "match", "(", "$", "inputSource", "->", "getValue", "(", "$", "httpRequest", ")", ",", "$", "expectedRequest", "->", "getBody", "(", ")", "->", "getValue", "(", ")", "->", "asString", "(", ")", ")", ";", "}" ]
@param ServerRequestInterface $httpRequest @param RequestConditions $expectedRequest @return bool
[ "@param", "ServerRequestInterface", "$httpRequest", "@param", "RequestConditions", "$expectedRequest" ]
train
https://github.com/mcustiel/phiremock-server/blob/7be42ce7c5c4d441410d80e158477910924cfbd9/src/Utils/RequestExpectationComparator.php#L190-L201
mcustiel/phiremock-server
src/Utils/RequestExpectationComparator.php
RequestExpectationComparator.requestHeadersMatchExpectation
private function requestHeadersMatchExpectation(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest) { $inputSource = $this->inputSourceLocator->locate('header'); foreach ($expectedRequest->getHeaders() as $header => $headerCondition) { $matcher = $this->matcherLocator->locate( $headerCondition->getMatcher()->asString() ); $matches = $matcher->match( $inputSource->getValue($httpRequest, $header->asString()), $headerCondition->getValue()->asString() ); if (!$matches) { return false; } } return true; }
php
private function requestHeadersMatchExpectation(ServerRequestInterface $httpRequest, RequestConditions $expectedRequest) { $inputSource = $this->inputSourceLocator->locate('header'); foreach ($expectedRequest->getHeaders() as $header => $headerCondition) { $matcher = $this->matcherLocator->locate( $headerCondition->getMatcher()->asString() ); $matches = $matcher->match( $inputSource->getValue($httpRequest, $header->asString()), $headerCondition->getValue()->asString() ); if (!$matches) { return false; } } return true; }
[ "private", "function", "requestHeadersMatchExpectation", "(", "ServerRequestInterface", "$", "httpRequest", ",", "RequestConditions", "$", "expectedRequest", ")", "{", "$", "inputSource", "=", "$", "this", "->", "inputSourceLocator", "->", "locate", "(", "'header'", ")", ";", "foreach", "(", "$", "expectedRequest", "->", "getHeaders", "(", ")", "as", "$", "header", "=>", "$", "headerCondition", ")", "{", "$", "matcher", "=", "$", "this", "->", "matcherLocator", "->", "locate", "(", "$", "headerCondition", "->", "getMatcher", "(", ")", "->", "asString", "(", ")", ")", ";", "$", "matches", "=", "$", "matcher", "->", "match", "(", "$", "inputSource", "->", "getValue", "(", "$", "httpRequest", ",", "$", "header", "->", "asString", "(", ")", ")", ",", "$", "headerCondition", "->", "getValue", "(", ")", "->", "asString", "(", ")", ")", ";", "if", "(", "!", "$", "matches", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
@param ServerRequestInterface $httpRequest @param RequestConditions $expectedRequest @return bool
[ "@param", "ServerRequestInterface", "$httpRequest", "@param", "RequestConditions", "$expectedRequest" ]
train
https://github.com/mcustiel/phiremock-server/blob/7be42ce7c5c4d441410d80e158477910924cfbd9/src/Utils/RequestExpectationComparator.php#L209-L227
NukaCode/users
src/NukaCode/Users/Presenters/UserPresenter.php
UserPresenter.gravatar
public function gravatar() { // Check for valid gravatar $gravCheck = 'http://www.gravatar.com/avatar/'. md5( strtolower( trim( $this->email ) ) ) .'.png?d=404'; $response = get_headers($gravCheck); // If a valid gravatar URL is found, use the gravatar image if ($response[0] != "HTTP/1.0 404 Not Found"){ return 'http://www.gravatar.com/avatar/'. md5( strtolower( trim( $this->email ) ) ) .'.png?s=200&d=blank'; } // If no other image is set, use the default return '/img/no_user.png'; }
php
public function gravatar() { // Check for valid gravatar $gravCheck = 'http://www.gravatar.com/avatar/'. md5( strtolower( trim( $this->email ) ) ) .'.png?d=404'; $response = get_headers($gravCheck); // If a valid gravatar URL is found, use the gravatar image if ($response[0] != "HTTP/1.0 404 Not Found"){ return 'http://www.gravatar.com/avatar/'. md5( strtolower( trim( $this->email ) ) ) .'.png?s=200&d=blank'; } // If no other image is set, use the default return '/img/no_user.png'; }
[ "public", "function", "gravatar", "(", ")", "{", "// Check for valid gravatar\r", "$", "gravCheck", "=", "'http://www.gravatar.com/avatar/'", ".", "md5", "(", "strtolower", "(", "trim", "(", "$", "this", "->", "email", ")", ")", ")", ".", "'.png?d=404'", ";", "$", "response", "=", "get_headers", "(", "$", "gravCheck", ")", ";", "// If a valid gravatar URL is found, use the gravatar image\r", "if", "(", "$", "response", "[", "0", "]", "!=", "\"HTTP/1.0 404 Not Found\"", ")", "{", "return", "'http://www.gravatar.com/avatar/'", ".", "md5", "(", "strtolower", "(", "trim", "(", "$", "this", "->", "email", ")", ")", ")", ".", "'.png?s=200&d=blank'", ";", "}", "// If no other image is set, use the default\r", "return", "'/img/no_user.png'", ";", "}" ]
Check for an avatar uploaded to the site, resort to gravatar if none exists, resort to no user image if no gravatar exists @return string
[ "Check", "for", "an", "avatar", "uploaded", "to", "the", "site", "resort", "to", "gravatar", "if", "none", "exists", "resort", "to", "no", "user", "image", "if", "no", "gravatar", "exists" ]
train
https://github.com/NukaCode/users/blob/d827b8e6ba3faf27c85d867ec1d7e0a426968551/src/NukaCode/Users/Presenters/UserPresenter.php#L88-L101
NukaCode/users
src/NukaCode/Users/Presenters/UserPresenter.php
UserPresenter.postsCount
public function postsCount() { $postsCount = $this->posts->count(); $repliesCount = $this->replies->count(); return $postsCount + $repliesCount; }
php
public function postsCount() { $postsCount = $this->posts->count(); $repliesCount = $this->replies->count(); return $postsCount + $repliesCount; }
[ "public", "function", "postsCount", "(", ")", "{", "$", "postsCount", "=", "$", "this", "->", "posts", "->", "count", "(", ")", ";", "$", "repliesCount", "=", "$", "this", "->", "replies", "->", "count", "(", ")", ";", "return", "$", "postsCount", "+", "$", "repliesCount", ";", "}" ]
Get the number of posts from this user
[ "Get", "the", "number", "of", "posts", "from", "this", "user" ]
train
https://github.com/NukaCode/users/blob/d827b8e6ba3faf27c85d867ec1d7e0a426968551/src/NukaCode/Users/Presenters/UserPresenter.php#L130-L136
NukaCode/users
src/NukaCode/Users/Presenters/UserPresenter.php
UserPresenter.lastActiveReadable
public function lastActiveReadable() { return ($this->lastActive == '0000-00-00 00:00:00' || $this->lastActive == null ? 'Never' : date('F jS, Y \a\t h:ia', strtotime($this->lastActive))); }
php
public function lastActiveReadable() { return ($this->lastActive == '0000-00-00 00:00:00' || $this->lastActive == null ? 'Never' : date('F jS, Y \a\t h:ia', strtotime($this->lastActive))); }
[ "public", "function", "lastActiveReadable", "(", ")", "{", "return", "(", "$", "this", "->", "lastActive", "==", "'0000-00-00 00:00:00'", "||", "$", "this", "->", "lastActive", "==", "null", "?", "'Never'", ":", "date", "(", "'F jS, Y \\a\\t h:ia'", ",", "strtotime", "(", "$", "this", "->", "lastActive", ")", ")", ")", ";", "}" ]
Make the last active date easier to read @return string
[ "Make", "the", "last", "active", "date", "easier", "to", "read" ]
train
https://github.com/NukaCode/users/blob/d827b8e6ba3faf27c85d867ec1d7e0a426968551/src/NukaCode/Users/Presenters/UserPresenter.php#L181-L184
vainproject/vain-user
src/User/Services/Registrar.php
Registrar.create
public function create(array $data) { $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), 'birthday_at' => $data['birthday_at'], 'locale' => $data['locale'], 'gender' => $data['gender'], 'city' => $data['city'], 'about' => $data['about'], 'profession' => $data['profession'], 'hobbies' => $data['hobbies'], 'homepage' => $data['homepage'], 'skype' => $data['skype'], 'facebook' => $data['facebook'], 'twitter' => $data['twitter'], 'main_character' => $data['main_character'], 'main_guild' => $data['main_guild'], 'favorite_race' => $data['favorite_race'], 'favorite_spec' => $data['favorite_spec'], 'favorite_instance' => $data['favorite_instance'], 'favorite_battleground' => $data['favorite_battleground'], ]); return $user; }
php
public function create(array $data) { $user = User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), 'birthday_at' => $data['birthday_at'], 'locale' => $data['locale'], 'gender' => $data['gender'], 'city' => $data['city'], 'about' => $data['about'], 'profession' => $data['profession'], 'hobbies' => $data['hobbies'], 'homepage' => $data['homepage'], 'skype' => $data['skype'], 'facebook' => $data['facebook'], 'twitter' => $data['twitter'], 'main_character' => $data['main_character'], 'main_guild' => $data['main_guild'], 'favorite_race' => $data['favorite_race'], 'favorite_spec' => $data['favorite_spec'], 'favorite_instance' => $data['favorite_instance'], 'favorite_battleground' => $data['favorite_battleground'], ]); return $user; }
[ "public", "function", "create", "(", "array", "$", "data", ")", "{", "$", "user", "=", "User", "::", "create", "(", "[", "'name'", "=>", "$", "data", "[", "'name'", "]", ",", "'email'", "=>", "$", "data", "[", "'email'", "]", ",", "'password'", "=>", "bcrypt", "(", "$", "data", "[", "'password'", "]", ")", ",", "'birthday_at'", "=>", "$", "data", "[", "'birthday_at'", "]", ",", "'locale'", "=>", "$", "data", "[", "'locale'", "]", ",", "'gender'", "=>", "$", "data", "[", "'gender'", "]", ",", "'city'", "=>", "$", "data", "[", "'city'", "]", ",", "'about'", "=>", "$", "data", "[", "'about'", "]", ",", "'profession'", "=>", "$", "data", "[", "'profession'", "]", ",", "'hobbies'", "=>", "$", "data", "[", "'hobbies'", "]", ",", "'homepage'", "=>", "$", "data", "[", "'homepage'", "]", ",", "'skype'", "=>", "$", "data", "[", "'skype'", "]", ",", "'facebook'", "=>", "$", "data", "[", "'facebook'", "]", ",", "'twitter'", "=>", "$", "data", "[", "'twitter'", "]", ",", "'main_character'", "=>", "$", "data", "[", "'main_character'", "]", ",", "'main_guild'", "=>", "$", "data", "[", "'main_guild'", "]", ",", "'favorite_race'", "=>", "$", "data", "[", "'favorite_race'", "]", ",", "'favorite_spec'", "=>", "$", "data", "[", "'favorite_spec'", "]", ",", "'favorite_instance'", "=>", "$", "data", "[", "'favorite_instance'", "]", ",", "'favorite_battleground'", "=>", "$", "data", "[", "'favorite_battleground'", "]", ",", "]", ")", ";", "return", "$", "user", ";", "}" ]
Create a new user instance after a valid registration. @param array $data @return User
[ "Create", "a", "new", "user", "instance", "after", "a", "valid", "registration", "." ]
train
https://github.com/vainproject/vain-user/blob/1c059faa61ebf289fcaea39a90b4523cfc9d6efc/src/User/Services/Registrar.php#L48-L74
spryker/price-product-merchant-relationship-data-import
src/Spryker/Zed/PriceProductMerchantRelationshipDataImport/Business/Model/Step/MerchantRelationshipKeyToIdMerchantRelationshipStep.php
MerchantRelationshipKeyToIdMerchantRelationshipStep.execute
public function execute(DataSetInterface $dataSet): void { $merchantRelationshipKey = $dataSet[PriceProductMerchantRelationshipDataSetInterface::MERCHANT_RELATIONSHIP_KEY]; if (!isset($this->idMerchantRelationshipCache[$merchantRelationshipKey])) { $idMerchantRelationship = SpyMerchantRelationshipQuery::create() ->select(SpyMerchantRelationshipTableMap::COL_ID_MERCHANT_RELATIONSHIP) ->findOneByMerchantRelationshipKey($merchantRelationshipKey); if (!$idMerchantRelationship) { throw new EntityNotFoundException(sprintf('Could not find Merchant Relationship by key "%s"', $merchantRelationshipKey)); } $this->idMerchantRelationshipCache[$merchantRelationshipKey] = $idMerchantRelationship; } $dataSet[PriceProductMerchantRelationshipDataSetInterface::ID_MERCHANT_RELATIONSHIP] = $this->idMerchantRelationshipCache[$merchantRelationshipKey]; }
php
public function execute(DataSetInterface $dataSet): void { $merchantRelationshipKey = $dataSet[PriceProductMerchantRelationshipDataSetInterface::MERCHANT_RELATIONSHIP_KEY]; if (!isset($this->idMerchantRelationshipCache[$merchantRelationshipKey])) { $idMerchantRelationship = SpyMerchantRelationshipQuery::create() ->select(SpyMerchantRelationshipTableMap::COL_ID_MERCHANT_RELATIONSHIP) ->findOneByMerchantRelationshipKey($merchantRelationshipKey); if (!$idMerchantRelationship) { throw new EntityNotFoundException(sprintf('Could not find Merchant Relationship by key "%s"', $merchantRelationshipKey)); } $this->idMerchantRelationshipCache[$merchantRelationshipKey] = $idMerchantRelationship; } $dataSet[PriceProductMerchantRelationshipDataSetInterface::ID_MERCHANT_RELATIONSHIP] = $this->idMerchantRelationshipCache[$merchantRelationshipKey]; }
[ "public", "function", "execute", "(", "DataSetInterface", "$", "dataSet", ")", ":", "void", "{", "$", "merchantRelationshipKey", "=", "$", "dataSet", "[", "PriceProductMerchantRelationshipDataSetInterface", "::", "MERCHANT_RELATIONSHIP_KEY", "]", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "idMerchantRelationshipCache", "[", "$", "merchantRelationshipKey", "]", ")", ")", "{", "$", "idMerchantRelationship", "=", "SpyMerchantRelationshipQuery", "::", "create", "(", ")", "->", "select", "(", "SpyMerchantRelationshipTableMap", "::", "COL_ID_MERCHANT_RELATIONSHIP", ")", "->", "findOneByMerchantRelationshipKey", "(", "$", "merchantRelationshipKey", ")", ";", "if", "(", "!", "$", "idMerchantRelationship", ")", "{", "throw", "new", "EntityNotFoundException", "(", "sprintf", "(", "'Could not find Merchant Relationship by key \"%s\"'", ",", "$", "merchantRelationshipKey", ")", ")", ";", "}", "$", "this", "->", "idMerchantRelationshipCache", "[", "$", "merchantRelationshipKey", "]", "=", "$", "idMerchantRelationship", ";", "}", "$", "dataSet", "[", "PriceProductMerchantRelationshipDataSetInterface", "::", "ID_MERCHANT_RELATIONSHIP", "]", "=", "$", "this", "->", "idMerchantRelationshipCache", "[", "$", "merchantRelationshipKey", "]", ";", "}" ]
@param \Spryker\Zed\DataImport\Business\Model\DataSet\DataSetInterface $dataSet @throws \Spryker\Zed\DataImport\Business\Exception\EntityNotFoundException @return void
[ "@param", "\\", "Spryker", "\\", "Zed", "\\", "DataImport", "\\", "Business", "\\", "Model", "\\", "DataSet", "\\", "DataSetInterface", "$dataSet" ]
train
https://github.com/spryker/price-product-merchant-relationship-data-import/blob/2b96c8a449920daa286e60ce6f98bde0989c7683/src/Spryker/Zed/PriceProductMerchantRelationshipDataImport/Business/Model/Step/MerchantRelationshipKeyToIdMerchantRelationshipStep.php#L31-L47
vpg/titon.utility
src/Titon/Utility/Crypt.php
Crypt.blowfish
public static function blowfish($string, $key, $operation = self::ENCRYPT) { if ($operation === static::ENCRYPT) { return static::encrypt($string, $key, static::BLOWFISH); } else { return static::decrypt($string, $key, static::BLOWFISH); } }
php
public static function blowfish($string, $key, $operation = self::ENCRYPT) { if ($operation === static::ENCRYPT) { return static::encrypt($string, $key, static::BLOWFISH); } else { return static::decrypt($string, $key, static::BLOWFISH); } }
[ "public", "static", "function", "blowfish", "(", "$", "string", ",", "$", "key", ",", "$", "operation", "=", "self", "::", "ENCRYPT", ")", "{", "if", "(", "$", "operation", "===", "static", "::", "ENCRYPT", ")", "{", "return", "static", "::", "encrypt", "(", "$", "string", ",", "$", "key", ",", "static", "::", "BLOWFISH", ")", ";", "}", "else", "{", "return", "static", "::", "decrypt", "(", "$", "string", ",", "$", "key", ",", "static", "::", "BLOWFISH", ")", ";", "}", "}" ]
Encrypt and decrypt a string using the Blowfish algorithm with CBC mode. @param string $string @param string $key @param int $operation @return string
[ "Encrypt", "and", "decrypt", "a", "string", "using", "the", "Blowfish", "algorithm", "with", "CBC", "mode", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Crypt.php#L45-L51
vpg/titon.utility
src/Titon/Utility/Crypt.php
Crypt.decrypt
public static function decrypt($string, $key, $cipher, $mode = MCRYPT_MODE_CBC) { list($key, $iv) = static::vector($key, $cipher, $mode); return rtrim(mcrypt_decrypt($cipher, $key, $string, $mode, $iv), "\0"); }
php
public static function decrypt($string, $key, $cipher, $mode = MCRYPT_MODE_CBC) { list($key, $iv) = static::vector($key, $cipher, $mode); return rtrim(mcrypt_decrypt($cipher, $key, $string, $mode, $iv), "\0"); }
[ "public", "static", "function", "decrypt", "(", "$", "string", ",", "$", "key", ",", "$", "cipher", ",", "$", "mode", "=", "MCRYPT_MODE_CBC", ")", "{", "list", "(", "$", "key", ",", "$", "iv", ")", "=", "static", "::", "vector", "(", "$", "key", ",", "$", "cipher", ",", "$", "mode", ")", ";", "return", "rtrim", "(", "mcrypt_decrypt", "(", "$", "cipher", ",", "$", "key", ",", "$", "string", ",", "$", "mode", ",", "$", "iv", ")", ",", "\"\\0\"", ")", ";", "}" ]
Decrypt an encrypted string using the passed cipher and mode. Additional types of ciphers and modes can be used that aren't constants of this class. @param string $string @param string $key @param string $cipher @param string $mode @return string
[ "Decrypt", "an", "encrypted", "string", "using", "the", "passed", "cipher", "and", "mode", ".", "Additional", "types", "of", "ciphers", "and", "modes", "can", "be", "used", "that", "aren", "t", "constants", "of", "this", "class", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Crypt.php#L63-L67
vpg/titon.utility
src/Titon/Utility/Crypt.php
Crypt.des
public static function des($string, $key, $operation = self::ENCRYPT) { if ($operation === static::ENCRYPT) { return static::encrypt($string, $key, static::DES); } else { return static::decrypt($string, $key, static::DES); } }
php
public static function des($string, $key, $operation = self::ENCRYPT) { if ($operation === static::ENCRYPT) { return static::encrypt($string, $key, static::DES); } else { return static::decrypt($string, $key, static::DES); } }
[ "public", "static", "function", "des", "(", "$", "string", ",", "$", "key", ",", "$", "operation", "=", "self", "::", "ENCRYPT", ")", "{", "if", "(", "$", "operation", "===", "static", "::", "ENCRYPT", ")", "{", "return", "static", "::", "encrypt", "(", "$", "string", ",", "$", "key", ",", "static", "::", "DES", ")", ";", "}", "else", "{", "return", "static", "::", "decrypt", "(", "$", "string", ",", "$", "key", ",", "static", "::", "DES", ")", ";", "}", "}" ]
Encrypt and decrypt a string using the DES (data encryption standard) algorithm with CBC mode. @param string $string @param string $key @param int $operation @return string
[ "Encrypt", "and", "decrypt", "a", "string", "using", "the", "DES", "(", "data", "encryption", "standard", ")", "algorithm", "with", "CBC", "mode", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Crypt.php#L77-L83
vpg/titon.utility
src/Titon/Utility/Crypt.php
Crypt.encrypt
public static function encrypt($string, $key, $cipher, $mode = MCRYPT_MODE_CBC) { list($key, $iv) = static::vector($key, $cipher, $mode); return mcrypt_encrypt($cipher, $key, $string, $mode, $iv); }
php
public static function encrypt($string, $key, $cipher, $mode = MCRYPT_MODE_CBC) { list($key, $iv) = static::vector($key, $cipher, $mode); return mcrypt_encrypt($cipher, $key, $string, $mode, $iv); }
[ "public", "static", "function", "encrypt", "(", "$", "string", ",", "$", "key", ",", "$", "cipher", ",", "$", "mode", "=", "MCRYPT_MODE_CBC", ")", "{", "list", "(", "$", "key", ",", "$", "iv", ")", "=", "static", "::", "vector", "(", "$", "key", ",", "$", "cipher", ",", "$", "mode", ")", ";", "return", "mcrypt_encrypt", "(", "$", "cipher", ",", "$", "key", ",", "$", "string", ",", "$", "mode", ",", "$", "iv", ")", ";", "}" ]
Encrypt string using the passed cipher and mode. Additional types of ciphers and modes can be used that aren't constants of this class. @param string $string @param string $key @param string $cipher @param string $mode @return string
[ "Encrypt", "string", "using", "the", "passed", "cipher", "and", "mode", ".", "Additional", "types", "of", "ciphers", "and", "modes", "can", "be", "used", "that", "aren", "t", "constants", "of", "this", "class", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Crypt.php#L95-L99
vpg/titon.utility
src/Titon/Utility/Crypt.php
Crypt.hash
public static function hash($cipher, $string, $salt = self::SALT) { return hash_hmac($cipher, $string, $salt); }
php
public static function hash($cipher, $string, $salt = self::SALT) { return hash_hmac($cipher, $string, $salt); }
[ "public", "static", "function", "hash", "(", "$", "cipher", ",", "$", "string", ",", "$", "salt", "=", "self", "::", "SALT", ")", "{", "return", "hash_hmac", "(", "$", "cipher", ",", "$", "string", ",", "$", "salt", ")", ";", "}" ]
Return a hashed string using one of the built in ciphers (md5, sha1, sha256, etc) and use the config salt if it has been set. Can also supply an optional second salt for increased security. @param string $cipher @param string $string @param string $salt @return string
[ "Return", "a", "hashed", "string", "using", "one", "of", "the", "built", "in", "ciphers", "(", "md5", "sha1", "sha256", "etc", ")", "and", "use", "the", "config", "salt", "if", "it", "has", "been", "set", ".", "Can", "also", "supply", "an", "optional", "second", "salt", "for", "increased", "security", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Crypt.php#L110-L112
vpg/titon.utility
src/Titon/Utility/Crypt.php
Crypt.obfuscate
public static function obfuscate($string) { $string = (string) $string; $length = mb_strlen($string); $scrambled = ''; if ($length > 0) { for ($i = 0; $i < $length; $i++) { $scrambled .= '&#' . ord($string[$i]) . ';'; } } return $scrambled; }
php
public static function obfuscate($string) { $string = (string) $string; $length = mb_strlen($string); $scrambled = ''; if ($length > 0) { for ($i = 0; $i < $length; $i++) { $scrambled .= '&#' . ord($string[$i]) . ';'; } } return $scrambled; }
[ "public", "static", "function", "obfuscate", "(", "$", "string", ")", "{", "$", "string", "=", "(", "string", ")", "$", "string", ";", "$", "length", "=", "mb_strlen", "(", "$", "string", ")", ";", "$", "scrambled", "=", "''", ";", "if", "(", "$", "length", ">", "0", ")", "{", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "$", "i", "++", ")", "{", "$", "scrambled", ".=", "'&#'", ".", "ord", "(", "$", "string", "[", "$", "i", "]", ")", ".", "';'", ";", "}", "}", "return", "$", "scrambled", ";", "}" ]
Scrambles the source of a string. @param string $string @return string
[ "Scrambles", "the", "source", "of", "a", "string", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Crypt.php#L120-L132
vpg/titon.utility
src/Titon/Utility/Crypt.php
Crypt.rijndael
public static function rijndael($string, $key, $operation = self::ENCRYPT) { if ($operation === static::ENCRYPT) { return static::encrypt($string, $key, static::RIJNDAEL); } else { return static::decrypt($string, $key, static::RIJNDAEL); } }
php
public static function rijndael($string, $key, $operation = self::ENCRYPT) { if ($operation === static::ENCRYPT) { return static::encrypt($string, $key, static::RIJNDAEL); } else { return static::decrypt($string, $key, static::RIJNDAEL); } }
[ "public", "static", "function", "rijndael", "(", "$", "string", ",", "$", "key", ",", "$", "operation", "=", "self", "::", "ENCRYPT", ")", "{", "if", "(", "$", "operation", "===", "static", "::", "ENCRYPT", ")", "{", "return", "static", "::", "encrypt", "(", "$", "string", ",", "$", "key", ",", "static", "::", "RIJNDAEL", ")", ";", "}", "else", "{", "return", "static", "::", "decrypt", "(", "$", "string", ",", "$", "key", ",", "static", "::", "RIJNDAEL", ")", ";", "}", "}" ]
Encrypt and decrypt a string using the Rijndael 128 algorithm with CBC mode. @param string $string @param string $key @param int $operation @return string
[ "Encrypt", "and", "decrypt", "a", "string", "using", "the", "Rijndael", "128", "algorithm", "with", "CBC", "mode", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Crypt.php#L142-L148
vpg/titon.utility
src/Titon/Utility/Crypt.php
Crypt.tripledes
public static function tripledes($string, $key, $operation = self::ENCRYPT) { if ($operation === static::ENCRYPT) { return static::encrypt($string, $key, static::TRIPLEDES); } else { return static::decrypt($string, $key, static::TRIPLEDES); } }
php
public static function tripledes($string, $key, $operation = self::ENCRYPT) { if ($operation === static::ENCRYPT) { return static::encrypt($string, $key, static::TRIPLEDES); } else { return static::decrypt($string, $key, static::TRIPLEDES); } }
[ "public", "static", "function", "tripledes", "(", "$", "string", ",", "$", "key", ",", "$", "operation", "=", "self", "::", "ENCRYPT", ")", "{", "if", "(", "$", "operation", "===", "static", "::", "ENCRYPT", ")", "{", "return", "static", "::", "encrypt", "(", "$", "string", ",", "$", "key", ",", "static", "::", "TRIPLEDES", ")", ";", "}", "else", "{", "return", "static", "::", "decrypt", "(", "$", "string", ",", "$", "key", ",", "static", "::", "TRIPLEDES", ")", ";", "}", "}" ]
Encrypt and decrypt a string using the 3DES (triple data encryption standard) algorithm with CBC mode. @param string $string @param string $key @param int $operation @return string
[ "Encrypt", "and", "decrypt", "a", "string", "using", "the", "3DES", "(", "triple", "data", "encryption", "standard", ")", "algorithm", "with", "CBC", "mode", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Crypt.php#L158-L164
vpg/titon.utility
src/Titon/Utility/Crypt.php
Crypt.vector
public static function vector($key, $cipher, $mode) { $keySize = mcrypt_get_key_size($cipher, $mode); $key = str_pad(static::hash('md5', $key), $keySize, mb_substr($cipher, -1), STR_PAD_BOTH); if (mb_strlen($key) > $keySize) { $key = mb_substr($key, 0, $keySize); } $ivSize = mcrypt_get_iv_size($cipher, $mode); $iv = str_pad(static::hash('md5', $key, $mode), $ivSize, mb_substr($cipher, 0, 1), STR_PAD_BOTH); if (mb_strlen($iv) > $ivSize) { $iv = mb_substr($iv, 0, $ivSize); } return array($key, $iv); }
php
public static function vector($key, $cipher, $mode) { $keySize = mcrypt_get_key_size($cipher, $mode); $key = str_pad(static::hash('md5', $key), $keySize, mb_substr($cipher, -1), STR_PAD_BOTH); if (mb_strlen($key) > $keySize) { $key = mb_substr($key, 0, $keySize); } $ivSize = mcrypt_get_iv_size($cipher, $mode); $iv = str_pad(static::hash('md5', $key, $mode), $ivSize, mb_substr($cipher, 0, 1), STR_PAD_BOTH); if (mb_strlen($iv) > $ivSize) { $iv = mb_substr($iv, 0, $ivSize); } return array($key, $iv); }
[ "public", "static", "function", "vector", "(", "$", "key", ",", "$", "cipher", ",", "$", "mode", ")", "{", "$", "keySize", "=", "mcrypt_get_key_size", "(", "$", "cipher", ",", "$", "mode", ")", ";", "$", "key", "=", "str_pad", "(", "static", "::", "hash", "(", "'md5'", ",", "$", "key", ")", ",", "$", "keySize", ",", "mb_substr", "(", "$", "cipher", ",", "-", "1", ")", ",", "STR_PAD_BOTH", ")", ";", "if", "(", "mb_strlen", "(", "$", "key", ")", ">", "$", "keySize", ")", "{", "$", "key", "=", "mb_substr", "(", "$", "key", ",", "0", ",", "$", "keySize", ")", ";", "}", "$", "ivSize", "=", "mcrypt_get_iv_size", "(", "$", "cipher", ",", "$", "mode", ")", ";", "$", "iv", "=", "str_pad", "(", "static", "::", "hash", "(", "'md5'", ",", "$", "key", ",", "$", "mode", ")", ",", "$", "ivSize", ",", "mb_substr", "(", "$", "cipher", ",", "0", ",", "1", ")", ",", "STR_PAD_BOTH", ")", ";", "if", "(", "mb_strlen", "(", "$", "iv", ")", ">", "$", "ivSize", ")", "{", "$", "iv", "=", "mb_substr", "(", "$", "iv", ",", "0", ",", "$", "ivSize", ")", ";", "}", "return", "array", "(", "$", "key", ",", "$", "iv", ")", ";", "}" ]
Prepare for en/decryption by generating persistent keys and IVs. We can't use randomization as the key/iv needs to be the same for both encrypt and decrypt. @param string $key @param string $cipher @param string $mode @return string[]
[ "Prepare", "for", "en", "/", "decryption", "by", "generating", "persistent", "keys", "and", "IVs", ".", "We", "can", "t", "use", "randomization", "as", "the", "key", "/", "iv", "needs", "to", "be", "the", "same", "for", "both", "encrypt", "and", "decrypt", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Crypt.php#L175-L191
naucon/Utility
src/HashSetAbstract.php
HashSetAbstract.add
public function add($element) { if (!$this->contains($element)) { $hashIndex = $this->hashIndex($element); $this->_items[$hashIndex] = $element; $this->_iterator = null; return true; } else { // element already exist return false; } }
php
public function add($element) { if (!$this->contains($element)) { $hashIndex = $this->hashIndex($element); $this->_items[$hashIndex] = $element; $this->_iterator = null; return true; } else { // element already exist return false; } }
[ "public", "function", "add", "(", "$", "element", ")", "{", "if", "(", "!", "$", "this", "->", "contains", "(", "$", "element", ")", ")", "{", "$", "hashIndex", "=", "$", "this", "->", "hashIndex", "(", "$", "element", ")", ";", "$", "this", "->", "_items", "[", "$", "hashIndex", "]", "=", "$", "element", ";", "$", "this", "->", "_iterator", "=", "null", ";", "return", "true", ";", "}", "else", "{", "// element already exist", "return", "false", ";", "}", "}" ]
add a element to the end of the collection @param mixed $element element @return bool
[ "add", "a", "element", "to", "the", "end", "of", "the", "collection" ]
train
https://github.com/naucon/Utility/blob/d225bb5d09d82400917f710c9d502949a66442c4/src/HashSetAbstract.php#L27-L39
naucon/Utility
src/HashSetAbstract.php
HashSetAbstract.contains
public function contains($element) { $hashIndex = $this->hashIndex($element); if (array_key_exists($hashIndex, $this->_items)) { return true; } return false; }
php
public function contains($element) { $hashIndex = $this->hashIndex($element); if (array_key_exists($hashIndex, $this->_items)) { return true; } return false; }
[ "public", "function", "contains", "(", "$", "element", ")", "{", "$", "hashIndex", "=", "$", "this", "->", "hashIndex", "(", "$", "element", ")", ";", "if", "(", "array_key_exists", "(", "$", "hashIndex", ",", "$", "this", "->", "_items", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
collection contains a given element @param mixed $element element @return bool true if the hashset contains a specified element
[ "collection", "contains", "a", "given", "element" ]
train
https://github.com/naucon/Utility/blob/d225bb5d09d82400917f710c9d502949a66442c4/src/HashSetAbstract.php#L63-L71
tonis-io-legacy/package
src/PackageManager.php
PackageManager.load
public function load() { if ($this->loaded) { return; } $event = new PackageEvent($this); $this->getEventManager()->fire(self::EVENT_ON_LOAD, $event); $cacheFile = $this->getCacheFile(); if (null !== $cacheFile && file_exists($cacheFile)) { $this->mergedConfig = include $cacheFile; } else { foreach ($this->getEventManager()->fire(self::EVENT_ON_MERGE, $event) as $config) { if (empty($config)) { continue; } $this->mergedConfig = $this->merge($this->mergedConfig, $config); } $this->writeCache(); } $this->loaded = true; }
php
public function load() { if ($this->loaded) { return; } $event = new PackageEvent($this); $this->getEventManager()->fire(self::EVENT_ON_LOAD, $event); $cacheFile = $this->getCacheFile(); if (null !== $cacheFile && file_exists($cacheFile)) { $this->mergedConfig = include $cacheFile; } else { foreach ($this->getEventManager()->fire(self::EVENT_ON_MERGE, $event) as $config) { if (empty($config)) { continue; } $this->mergedConfig = $this->merge($this->mergedConfig, $config); } $this->writeCache(); } $this->loaded = true; }
[ "public", "function", "load", "(", ")", "{", "if", "(", "$", "this", "->", "loaded", ")", "{", "return", ";", "}", "$", "event", "=", "new", "PackageEvent", "(", "$", "this", ")", ";", "$", "this", "->", "getEventManager", "(", ")", "->", "fire", "(", "self", "::", "EVENT_ON_LOAD", ",", "$", "event", ")", ";", "$", "cacheFile", "=", "$", "this", "->", "getCacheFile", "(", ")", ";", "if", "(", "null", "!==", "$", "cacheFile", "&&", "file_exists", "(", "$", "cacheFile", ")", ")", "{", "$", "this", "->", "mergedConfig", "=", "include", "$", "cacheFile", ";", "}", "else", "{", "foreach", "(", "$", "this", "->", "getEventManager", "(", ")", "->", "fire", "(", "self", "::", "EVENT_ON_MERGE", ",", "$", "event", ")", "as", "$", "config", ")", "{", "if", "(", "empty", "(", "$", "config", ")", ")", "{", "continue", ";", "}", "$", "this", "->", "mergedConfig", "=", "$", "this", "->", "merge", "(", "$", "this", "->", "mergedConfig", ",", "$", "config", ")", ";", "}", "$", "this", "->", "writeCache", "(", ")", ";", "}", "$", "this", "->", "loaded", "=", "true", ";", "}" ]
Performs the loading of modules by firing the load event, merging the configurations, and firing the load post event.
[ "Performs", "the", "loading", "of", "modules", "by", "firing", "the", "load", "event", "merging", "the", "configurations", "and", "firing", "the", "load", "post", "event", "." ]
train
https://github.com/tonis-io-legacy/package/blob/ecb7eb5778bfbdd2d0f367bdfa9281e098483341/src/PackageManager.php#L116-L140
tonis-io-legacy/package
src/PackageManager.php
PackageManager.merge
public function merge(array $a, array $b) { foreach ($b as $key => $value) { if (array_key_exists($key, $a)) { if (is_int($key)) { $a[] = $value; } elseif (is_array($value) && is_array($a[$key])) { $a[$key] = $this->merge($a[$key], $value); } else { $a[$key] = $value; } } else { $a[$key] = $value; } } return $a; }
php
public function merge(array $a, array $b) { foreach ($b as $key => $value) { if (array_key_exists($key, $a)) { if (is_int($key)) { $a[] = $value; } elseif (is_array($value) && is_array($a[$key])) { $a[$key] = $this->merge($a[$key], $value); } else { $a[$key] = $value; } } else { $a[$key] = $value; } } return $a; }
[ "public", "function", "merge", "(", "array", "$", "a", ",", "array", "$", "b", ")", "{", "foreach", "(", "$", "b", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "a", ")", ")", "{", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "$", "a", "[", "]", "=", "$", "value", ";", "}", "elseif", "(", "is_array", "(", "$", "value", ")", "&&", "is_array", "(", "$", "a", "[", "$", "key", "]", ")", ")", "{", "$", "a", "[", "$", "key", "]", "=", "$", "this", "->", "merge", "(", "$", "a", "[", "$", "key", "]", ",", "$", "value", ")", ";", "}", "else", "{", "$", "a", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "else", "{", "$", "a", "[", "$", "key", "]", "=", "$", "value", ";", "}", "}", "return", "$", "a", ";", "}" ]
Borrowed from ZF2's ArrayUtils::merge() method. @param array $a @param array $b @return array
[ "Borrowed", "from", "ZF2", "s", "ArrayUtils", "::", "merge", "()", "method", "." ]
train
https://github.com/tonis-io-legacy/package/blob/ecb7eb5778bfbdd2d0f367bdfa9281e098483341/src/PackageManager.php#L157-L174
drdplusinfo/drdplus-properties
DrdPlus/Properties/Combat/Fight.php
Fight.getFightNumberByProfession
private static function getFightNumberByProfession(ProfessionCode $professionCode, BaseProperties $baseProperties): int { switch ($professionCode->getValue()) { case ProfessionCode::FIGHTER : return $baseProperties->getAgility()->getValue(); case ProfessionCode::THIEF : case ProfessionCode::RANGER : // same as a thief return SumAndRound::average($baseProperties->getAgility()->getValue(), $baseProperties->getKnack()->getValue()); case ProfessionCode::WIZARD : case ProfessionCode::THEURGIST : // same as a wizard return SumAndRound::average($baseProperties->getAgility()->getValue(), $baseProperties->getIntelligence()->getValue()); case ProfessionCode::PRIEST : return SumAndRound::average($baseProperties->getAgility()->getValue(), $baseProperties->getCharisma()->getValue()); case ProfessionCode::COMMONER : return 0; default : throw new Exceptions\UnknownProfession( 'Unknown profession of code ' . ValueDescriber::describe($professionCode->getValue()) ); } }
php
private static function getFightNumberByProfession(ProfessionCode $professionCode, BaseProperties $baseProperties): int { switch ($professionCode->getValue()) { case ProfessionCode::FIGHTER : return $baseProperties->getAgility()->getValue(); case ProfessionCode::THIEF : case ProfessionCode::RANGER : // same as a thief return SumAndRound::average($baseProperties->getAgility()->getValue(), $baseProperties->getKnack()->getValue()); case ProfessionCode::WIZARD : case ProfessionCode::THEURGIST : // same as a wizard return SumAndRound::average($baseProperties->getAgility()->getValue(), $baseProperties->getIntelligence()->getValue()); case ProfessionCode::PRIEST : return SumAndRound::average($baseProperties->getAgility()->getValue(), $baseProperties->getCharisma()->getValue()); case ProfessionCode::COMMONER : return 0; default : throw new Exceptions\UnknownProfession( 'Unknown profession of code ' . ValueDescriber::describe($professionCode->getValue()) ); } }
[ "private", "static", "function", "getFightNumberByProfession", "(", "ProfessionCode", "$", "professionCode", ",", "BaseProperties", "$", "baseProperties", ")", ":", "int", "{", "switch", "(", "$", "professionCode", "->", "getValue", "(", ")", ")", "{", "case", "ProfessionCode", "::", "FIGHTER", ":", "return", "$", "baseProperties", "->", "getAgility", "(", ")", "->", "getValue", "(", ")", ";", "case", "ProfessionCode", "::", "THIEF", ":", "case", "ProfessionCode", "::", "RANGER", ":", "// same as a thief", "return", "SumAndRound", "::", "average", "(", "$", "baseProperties", "->", "getAgility", "(", ")", "->", "getValue", "(", ")", ",", "$", "baseProperties", "->", "getKnack", "(", ")", "->", "getValue", "(", ")", ")", ";", "case", "ProfessionCode", "::", "WIZARD", ":", "case", "ProfessionCode", "::", "THEURGIST", ":", "// same as a wizard", "return", "SumAndRound", "::", "average", "(", "$", "baseProperties", "->", "getAgility", "(", ")", "->", "getValue", "(", ")", ",", "$", "baseProperties", "->", "getIntelligence", "(", ")", "->", "getValue", "(", ")", ")", ";", "case", "ProfessionCode", "::", "PRIEST", ":", "return", "SumAndRound", "::", "average", "(", "$", "baseProperties", "->", "getAgility", "(", ")", "->", "getValue", "(", ")", ",", "$", "baseProperties", "->", "getCharisma", "(", ")", "->", "getValue", "(", ")", ")", ";", "case", "ProfessionCode", "::", "COMMONER", ":", "return", "0", ";", "default", ":", "throw", "new", "Exceptions", "\\", "UnknownProfession", "(", "'Unknown profession of code '", ".", "ValueDescriber", "::", "describe", "(", "$", "professionCode", "->", "getValue", "(", ")", ")", ")", ";", "}", "}" ]
See PPH page 34 left column, @link https://pph.drdplus.info/#tabulka_boje @param ProfessionCode $professionCode @param BaseProperties $baseProperties @return int @throws \DrdPlus\Properties\Combat\Exceptions\UnknownProfession
[ "See", "PPH", "page", "34", "left", "column", "@link", "https", ":", "//", "pph", ".", "drdplus", ".", "info", "/", "#tabulka_boje" ]
train
https://github.com/drdplusinfo/drdplus-properties/blob/519670e75491af4c2e5d111a01f2cb1a581d8b2c/DrdPlus/Properties/Combat/Fight.php#L52-L72
gplcart/cli
controllers/commands/Zone.php
Zone.cmdGetZone
public function cmdGetZone() { $result = $this->getListZone(); $this->outputFormat($result); $this->outputFormatTableZone($result); $this->output(); }
php
public function cmdGetZone() { $result = $this->getListZone(); $this->outputFormat($result); $this->outputFormatTableZone($result); $this->output(); }
[ "public", "function", "cmdGetZone", "(", ")", "{", "$", "result", "=", "$", "this", "->", "getListZone", "(", ")", ";", "$", "this", "->", "outputFormat", "(", "$", "result", ")", ";", "$", "this", "->", "outputFormatTableZone", "(", "$", "result", ")", ";", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "zone-get" command
[ "Callback", "for", "zone", "-", "get", "command" ]
train
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Zone.php#L40-L46
gplcart/cli
controllers/commands/Zone.php
Zone.cmdUpdateZone
public function cmdUpdateZone() { $params = $this->getParam(); if (empty($params[0]) || count($params) < 2) { $this->errorAndExit($this->text('Invalid command')); } if (!is_numeric($params[0])) { $this->errorAndExit($this->text('Invalid argument')); } $this->setSubmitted(null, $params); $this->setSubmitted('update', $params[0]); $this->validateComponent('zone'); $this->updateZone($params[0]); $this->output(); }
php
public function cmdUpdateZone() { $params = $this->getParam(); if (empty($params[0]) || count($params) < 2) { $this->errorAndExit($this->text('Invalid command')); } if (!is_numeric($params[0])) { $this->errorAndExit($this->text('Invalid argument')); } $this->setSubmitted(null, $params); $this->setSubmitted('update', $params[0]); $this->validateComponent('zone'); $this->updateZone($params[0]); $this->output(); }
[ "public", "function", "cmdUpdateZone", "(", ")", "{", "$", "params", "=", "$", "this", "->", "getParam", "(", ")", ";", "if", "(", "empty", "(", "$", "params", "[", "0", "]", ")", "||", "count", "(", "$", "params", ")", "<", "2", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid command'", ")", ")", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "params", "[", "0", "]", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid argument'", ")", ")", ";", "}", "$", "this", "->", "setSubmitted", "(", "null", ",", "$", "params", ")", ";", "$", "this", "->", "setSubmitted", "(", "'update'", ",", "$", "params", "[", "0", "]", ")", ";", "$", "this", "->", "validateComponent", "(", "'zone'", ")", ";", "$", "this", "->", "updateZone", "(", "$", "params", "[", "0", "]", ")", ";", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "zone-update" command
[ "Callback", "for", "zone", "-", "update", "command" ]
train
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Zone.php#L66-L85
gplcart/cli
controllers/commands/Zone.php
Zone.cmdDeleteZone
public function cmdDeleteZone() { $id = $this->getParam(0); $all = $this->getParam('all'); if (empty($id) && empty($all)) { $this->errorAndExit($this->text('Invalid command')); } $result = false; if (!empty($id)) { $result = $this->zone->delete($id); } else if (!empty($all)) { $deleted = $count = 0; foreach ($this->zone->getList() as $zone) { $count++; $deleted += (int) $this->zone->delete($zone['zone_id']); } $result = $count && $count == $deleted; } if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } $this->output(); }
php
public function cmdDeleteZone() { $id = $this->getParam(0); $all = $this->getParam('all'); if (empty($id) && empty($all)) { $this->errorAndExit($this->text('Invalid command')); } $result = false; if (!empty($id)) { $result = $this->zone->delete($id); } else if (!empty($all)) { $deleted = $count = 0; foreach ($this->zone->getList() as $zone) { $count++; $deleted += (int) $this->zone->delete($zone['zone_id']); } $result = $count && $count == $deleted; } if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } $this->output(); }
[ "public", "function", "cmdDeleteZone", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getParam", "(", "0", ")", ";", "$", "all", "=", "$", "this", "->", "getParam", "(", "'all'", ")", ";", "if", "(", "empty", "(", "$", "id", ")", "&&", "empty", "(", "$", "all", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid command'", ")", ")", ";", "}", "$", "result", "=", "false", ";", "if", "(", "!", "empty", "(", "$", "id", ")", ")", "{", "$", "result", "=", "$", "this", "->", "zone", "->", "delete", "(", "$", "id", ")", ";", "}", "else", "if", "(", "!", "empty", "(", "$", "all", ")", ")", "{", "$", "deleted", "=", "$", "count", "=", "0", ";", "foreach", "(", "$", "this", "->", "zone", "->", "getList", "(", ")", "as", "$", "zone", ")", "{", "$", "count", "++", ";", "$", "deleted", "+=", "(", "int", ")", "$", "this", "->", "zone", "->", "delete", "(", "$", "zone", "[", "'zone_id'", "]", ")", ";", "}", "$", "result", "=", "$", "count", "&&", "$", "count", "==", "$", "deleted", ";", "}", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "zone-delete" command
[ "Callback", "for", "zone", "-", "delete", "command" ]
train
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Zone.php#L90-L119
gplcart/cli
controllers/commands/Zone.php
Zone.getListZone
protected function getListZone() { $id = $this->getParam(0); if (!isset($id)) { return $this->zone->getList(array('limit' => $this->getLimit())); } if (!is_numeric($id)) { $this->errorAndExit($this->text('Invalid argument')); } $result = $this->zone->get($id); if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } return array($result); }
php
protected function getListZone() { $id = $this->getParam(0); if (!isset($id)) { return $this->zone->getList(array('limit' => $this->getLimit())); } if (!is_numeric($id)) { $this->errorAndExit($this->text('Invalid argument')); } $result = $this->zone->get($id); if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } return array($result); }
[ "protected", "function", "getListZone", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getParam", "(", "0", ")", ";", "if", "(", "!", "isset", "(", "$", "id", ")", ")", "{", "return", "$", "this", "->", "zone", "->", "getList", "(", "array", "(", "'limit'", "=>", "$", "this", "->", "getLimit", "(", ")", ")", ")", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "id", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid argument'", ")", ")", ";", "}", "$", "result", "=", "$", "this", "->", "zone", "->", "get", "(", "$", "id", ")", ";", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "return", "array", "(", "$", "result", ")", ";", "}" ]
Returns an array of zones @return array
[ "Returns", "an", "array", "of", "zones" ]
train
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Zone.php#L125-L144
gplcart/cli
controllers/commands/Zone.php
Zone.updateZone
protected function updateZone($zone_id) { if (!$this->isError() && !$this->zone->update($zone_id, $this->getSubmitted())) { $this->errorAndExit($this->text('Unexpected result')); } }
php
protected function updateZone($zone_id) { if (!$this->isError() && !$this->zone->update($zone_id, $this->getSubmitted())) { $this->errorAndExit($this->text('Unexpected result')); } }
[ "protected", "function", "updateZone", "(", "$", "zone_id", ")", "{", "if", "(", "!", "$", "this", "->", "isError", "(", ")", "&&", "!", "$", "this", "->", "zone", "->", "update", "(", "$", "zone_id", ",", "$", "this", "->", "getSubmitted", "(", ")", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "}" ]
Updates a zone @param string $zone_id
[ "Updates", "a", "zone" ]
train
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Zone.php#L175-L180
gplcart/cli
controllers/commands/Zone.php
Zone.submitAddZone
protected function submitAddZone() { $this->setSubmitted(null, $this->getParam()); $this->validateComponent('zone'); $this->addZone(); }
php
protected function submitAddZone() { $this->setSubmitted(null, $this->getParam()); $this->validateComponent('zone'); $this->addZone(); }
[ "protected", "function", "submitAddZone", "(", ")", "{", "$", "this", "->", "setSubmitted", "(", "null", ",", "$", "this", "->", "getParam", "(", ")", ")", ";", "$", "this", "->", "validateComponent", "(", "'zone'", ")", ";", "$", "this", "->", "addZone", "(", ")", ";", "}" ]
Add a new zone at once
[ "Add", "a", "new", "zone", "at", "once" ]
train
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Zone.php#L185-L190
gplcart/cli
controllers/commands/Zone.php
Zone.addZone
protected function addZone() { if (!$this->isError()) { $id = $this->zone->add($this->getSubmitted()); if (empty($id)) { $this->errorAndExit($this->text('Unexpected result')); } $this->line($id); } }
php
protected function addZone() { if (!$this->isError()) { $id = $this->zone->add($this->getSubmitted()); if (empty($id)) { $this->errorAndExit($this->text('Unexpected result')); } $this->line($id); } }
[ "protected", "function", "addZone", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isError", "(", ")", ")", "{", "$", "id", "=", "$", "this", "->", "zone", "->", "add", "(", "$", "this", "->", "getSubmitted", "(", ")", ")", ";", "if", "(", "empty", "(", "$", "id", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "$", "this", "->", "line", "(", "$", "id", ")", ";", "}", "}" ]
Add a new zone
[ "Add", "a", "new", "zone" ]
train
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Zone.php#L195-L204
gplcart/cli
controllers/commands/Zone.php
Zone.wizardAddZone
protected function wizardAddZone() { $this->validatePrompt('title', $this->text('Title'), 'zone'); $this->validatePrompt('status', $this->text('Status'), 'zone', 0); $this->validateComponent('zone'); $this->addZone(); }
php
protected function wizardAddZone() { $this->validatePrompt('title', $this->text('Title'), 'zone'); $this->validatePrompt('status', $this->text('Status'), 'zone', 0); $this->validateComponent('zone'); $this->addZone(); }
[ "protected", "function", "wizardAddZone", "(", ")", "{", "$", "this", "->", "validatePrompt", "(", "'title'", ",", "$", "this", "->", "text", "(", "'Title'", ")", ",", "'zone'", ")", ";", "$", "this", "->", "validatePrompt", "(", "'status'", ",", "$", "this", "->", "text", "(", "'Status'", ")", ",", "'zone'", ",", "0", ")", ";", "$", "this", "->", "validateComponent", "(", "'zone'", ")", ";", "$", "this", "->", "addZone", "(", ")", ";", "}" ]
Add a new zone step by step
[ "Add", "a", "new", "zone", "step", "by", "step" ]
train
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Zone.php#L209-L216
climphp/Clim
Clim/Helper/DeferredDefinitionTrait.php
DeferredDefinitionTrait.needDefined
protected function needDefined() { if ($this->defined) return; $this->defined = true; $name = $pattern = $note = null; if (preg_match(PARSER_PATTERN, $this->definition, $matches)) { $body = $matches[1]; $name = $matches[2]; $note = $matches[3]; $pos = strpos($name, '|'); if ($pos !== false) { $pattern = $this->assertPattern(trim(substr($name, $pos + 1))); $name = trim(substr($name, 0, $pos)); } } else { $body = $this->definition; } $this->define($body, $name, $pattern, $note); }
php
protected function needDefined() { if ($this->defined) return; $this->defined = true; $name = $pattern = $note = null; if (preg_match(PARSER_PATTERN, $this->definition, $matches)) { $body = $matches[1]; $name = $matches[2]; $note = $matches[3]; $pos = strpos($name, '|'); if ($pos !== false) { $pattern = $this->assertPattern(trim(substr($name, $pos + 1))); $name = trim(substr($name, 0, $pos)); } } else { $body = $this->definition; } $this->define($body, $name, $pattern, $note); }
[ "protected", "function", "needDefined", "(", ")", "{", "if", "(", "$", "this", "->", "defined", ")", "return", ";", "$", "this", "->", "defined", "=", "true", ";", "$", "name", "=", "$", "pattern", "=", "$", "note", "=", "null", ";", "if", "(", "preg_match", "(", "PARSER_PATTERN", ",", "$", "this", "->", "definition", ",", "$", "matches", ")", ")", "{", "$", "body", "=", "$", "matches", "[", "1", "]", ";", "$", "name", "=", "$", "matches", "[", "2", "]", ";", "$", "note", "=", "$", "matches", "[", "3", "]", ";", "$", "pos", "=", "strpos", "(", "$", "name", ",", "'|'", ")", ";", "if", "(", "$", "pos", "!==", "false", ")", "{", "$", "pattern", "=", "$", "this", "->", "assertPattern", "(", "trim", "(", "substr", "(", "$", "name", ",", "$", "pos", "+", "1", ")", ")", ")", ";", "$", "name", "=", "trim", "(", "substr", "(", "$", "name", ",", "0", ",", "$", "pos", ")", ")", ";", "}", "}", "else", "{", "$", "body", "=", "$", "this", "->", "definition", ";", "}", "$", "this", "->", "define", "(", "$", "body", ",", "$", "name", ",", "$", "pattern", ",", "$", "note", ")", ";", "}" ]
Ensure definition has been parsed before actual use. It is safe to call it multiple times.
[ "Ensure", "definition", "has", "been", "parsed", "before", "actual", "use", ".", "It", "is", "safe", "to", "call", "it", "multiple", "times", "." ]
train
https://github.com/climphp/Clim/blob/d2d09a82e1b7a0b8d454e585e6db421ff02ec8e4/Clim/Helper/DeferredDefinitionTrait.php#L44-L67
climphp/Clim
Clim/Helper/DeferredDefinitionTrait.php
DeferredDefinitionTrait.assertPattern
protected function assertPattern($pattern) { if (strlen($pattern) == 0) return null; $pattern = '/^'. str_replace('/', '\\/', $pattern). '$/'; if (@preg_match($pattern, null) === false) { throw new DefinitionException("invalid regular expression pattern"); } return $pattern; }
php
protected function assertPattern($pattern) { if (strlen($pattern) == 0) return null; $pattern = '/^'. str_replace('/', '\\/', $pattern). '$/'; if (@preg_match($pattern, null) === false) { throw new DefinitionException("invalid regular expression pattern"); } return $pattern; }
[ "protected", "function", "assertPattern", "(", "$", "pattern", ")", "{", "if", "(", "strlen", "(", "$", "pattern", ")", "==", "0", ")", "return", "null", ";", "$", "pattern", "=", "'/^'", ".", "str_replace", "(", "'/'", ",", "'\\\\/'", ",", "$", "pattern", ")", ".", "'$/'", ";", "if", "(", "@", "preg_match", "(", "$", "pattern", ",", "null", ")", "===", "false", ")", "{", "throw", "new", "DefinitionException", "(", "\"invalid regular expression pattern\"", ")", ";", "}", "return", "$", "pattern", ";", "}" ]
Validate the regular expression pattern string @param string $pattern @return string|null @throws DefinitionException
[ "Validate", "the", "regular", "expression", "pattern", "string" ]
train
https://github.com/climphp/Clim/blob/d2d09a82e1b7a0b8d454e585e6db421ff02ec8e4/Clim/Helper/DeferredDefinitionTrait.php#L75-L85
rawphp/RawCodeStandards
RawPHP/Sniffs/Functions/FunctionDeclarationSniff.php
RawPHP_Sniffs_Functions_FunctionDeclarationSniff.process
public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); $spaces = 0; if ( $tokens[ ($stackPtr + 1) ][ 'code' ] === T_WHITESPACE ) { $spaces = strlen( $tokens[ ($stackPtr + 1) ][ 'content' ] ); } if ( $spaces !== 1 ) { $error = 'Expected 1 space after FUNCTION keyword; %s found'; $data = array( $spaces ); $phpcsFile->addError( $error, $stackPtr, 'SpaceAfterFunction', $data ); } // Must be one space before and after USE keyword for closures. $openBracket = $tokens[ $stackPtr ][ 'parenthesis_opener' ]; $closeBracket = $tokens[ $stackPtr ][ 'parenthesis_closer' ]; if ( $tokens[ $stackPtr ][ 'code' ] === T_CLOSURE ) { $use = $phpcsFile->findNext( T_USE, ($closeBracket + 1 ), $tokens[ $stackPtr ][ 'scope_opener' ] ); if ( $use !== FALSE ) { if ( $tokens[ ($use + 1) ][ 'code' ] !== T_WHITESPACE ) { $length = 0; } else if ( $tokens[ ($use + 1) ][ 'content' ] === "\t" ) { $length = '\t'; } else { $length = strlen( $tokens[ ($use + 1) ][ 'content' ] ); } if ( $length !== 1 ) { $error = 'Expected 1 space after USE keyword; found %s'; $data = array( $length ); $phpcsFile->addError( $error, $use, 'SpaceAfterUse', $data ); } if ( $tokens[ ($use - 1) ][ 'code' ] !== T_WHITESPACE ) { $length = 0; } else if ( $tokens[ ($use - 1) ][ 'content' ] === "\t" ) { $length = '\t'; } else { $length = strlen( $tokens[ ($use - 1) ][ 'content' ] ); } if ( $length !== 1 ) { $error = 'Expected 1 space before USE keyword; found %s'; $data = array( $length ); $phpcsFile->addError( $error, $use, 'SpaceBeforeUse', $data ); } } } // Check if this is a single line or multi-line declaration. $singleLine = TRUE; if ( $tokens[ $openBracket ][ 'line' ] === $tokens[ $closeBracket ][ 'line' ] ) { // Closures may use the USE keyword and so be multi-line in this way. if ( $tokens[ $stackPtr ][ 'code' ] === T_CLOSURE ) { if ( $use !== FALSE ) { // If the opening and closing parenthesis of the use statement // are also on the same line, this is a single line declaration. $open = $phpcsFile->findNext( T_OPEN_PARENTHESIS, ($use + 1 ) ); $close = $tokens[ $open ][ 'parenthesis_closer' ]; if ( $tokens[ $open ][ 'line' ] !== $tokens[ $close ][ 'line' ] ) { $singleLine = FALSE; } } } } else { $singleLine = FALSE; } if ( $singleLine === TRUE ) { $this->processSingleLineDeclaration( $phpcsFile, $stackPtr, $tokens ); } else { $this->processMultiLineDeclaration( $phpcsFile, $stackPtr, $tokens ); } }
php
public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); $spaces = 0; if ( $tokens[ ($stackPtr + 1) ][ 'code' ] === T_WHITESPACE ) { $spaces = strlen( $tokens[ ($stackPtr + 1) ][ 'content' ] ); } if ( $spaces !== 1 ) { $error = 'Expected 1 space after FUNCTION keyword; %s found'; $data = array( $spaces ); $phpcsFile->addError( $error, $stackPtr, 'SpaceAfterFunction', $data ); } // Must be one space before and after USE keyword for closures. $openBracket = $tokens[ $stackPtr ][ 'parenthesis_opener' ]; $closeBracket = $tokens[ $stackPtr ][ 'parenthesis_closer' ]; if ( $tokens[ $stackPtr ][ 'code' ] === T_CLOSURE ) { $use = $phpcsFile->findNext( T_USE, ($closeBracket + 1 ), $tokens[ $stackPtr ][ 'scope_opener' ] ); if ( $use !== FALSE ) { if ( $tokens[ ($use + 1) ][ 'code' ] !== T_WHITESPACE ) { $length = 0; } else if ( $tokens[ ($use + 1) ][ 'content' ] === "\t" ) { $length = '\t'; } else { $length = strlen( $tokens[ ($use + 1) ][ 'content' ] ); } if ( $length !== 1 ) { $error = 'Expected 1 space after USE keyword; found %s'; $data = array( $length ); $phpcsFile->addError( $error, $use, 'SpaceAfterUse', $data ); } if ( $tokens[ ($use - 1) ][ 'code' ] !== T_WHITESPACE ) { $length = 0; } else if ( $tokens[ ($use - 1) ][ 'content' ] === "\t" ) { $length = '\t'; } else { $length = strlen( $tokens[ ($use - 1) ][ 'content' ] ); } if ( $length !== 1 ) { $error = 'Expected 1 space before USE keyword; found %s'; $data = array( $length ); $phpcsFile->addError( $error, $use, 'SpaceBeforeUse', $data ); } } } // Check if this is a single line or multi-line declaration. $singleLine = TRUE; if ( $tokens[ $openBracket ][ 'line' ] === $tokens[ $closeBracket ][ 'line' ] ) { // Closures may use the USE keyword and so be multi-line in this way. if ( $tokens[ $stackPtr ][ 'code' ] === T_CLOSURE ) { if ( $use !== FALSE ) { // If the opening and closing parenthesis of the use statement // are also on the same line, this is a single line declaration. $open = $phpcsFile->findNext( T_OPEN_PARENTHESIS, ($use + 1 ) ); $close = $tokens[ $open ][ 'parenthesis_closer' ]; if ( $tokens[ $open ][ 'line' ] !== $tokens[ $close ][ 'line' ] ) { $singleLine = FALSE; } } } } else { $singleLine = FALSE; } if ( $singleLine === TRUE ) { $this->processSingleLineDeclaration( $phpcsFile, $stackPtr, $tokens ); } else { $this->processMultiLineDeclaration( $phpcsFile, $stackPtr, $tokens ); } }
[ "public", "function", "process", "(", "PHP_CodeSniffer_File", "$", "phpcsFile", ",", "$", "stackPtr", ")", "{", "$", "tokens", "=", "$", "phpcsFile", "->", "getTokens", "(", ")", ";", "$", "spaces", "=", "0", ";", "if", "(", "$", "tokens", "[", "(", "$", "stackPtr", "+", "1", ")", "]", "[", "'code'", "]", "===", "T_WHITESPACE", ")", "{", "$", "spaces", "=", "strlen", "(", "$", "tokens", "[", "(", "$", "stackPtr", "+", "1", ")", "]", "[", "'content'", "]", ")", ";", "}", "if", "(", "$", "spaces", "!==", "1", ")", "{", "$", "error", "=", "'Expected 1 space after FUNCTION keyword; %s found'", ";", "$", "data", "=", "array", "(", "$", "spaces", ")", ";", "$", "phpcsFile", "->", "addError", "(", "$", "error", ",", "$", "stackPtr", ",", "'SpaceAfterFunction'", ",", "$", "data", ")", ";", "}", "// Must be one space before and after USE keyword for closures.", "$", "openBracket", "=", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'parenthesis_opener'", "]", ";", "$", "closeBracket", "=", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'parenthesis_closer'", "]", ";", "if", "(", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'code'", "]", "===", "T_CLOSURE", ")", "{", "$", "use", "=", "$", "phpcsFile", "->", "findNext", "(", "T_USE", ",", "(", "$", "closeBracket", "+", "1", ")", ",", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'scope_opener'", "]", ")", ";", "if", "(", "$", "use", "!==", "FALSE", ")", "{", "if", "(", "$", "tokens", "[", "(", "$", "use", "+", "1", ")", "]", "[", "'code'", "]", "!==", "T_WHITESPACE", ")", "{", "$", "length", "=", "0", ";", "}", "else", "if", "(", "$", "tokens", "[", "(", "$", "use", "+", "1", ")", "]", "[", "'content'", "]", "===", "\"\\t\"", ")", "{", "$", "length", "=", "'\\t'", ";", "}", "else", "{", "$", "length", "=", "strlen", "(", "$", "tokens", "[", "(", "$", "use", "+", "1", ")", "]", "[", "'content'", "]", ")", ";", "}", "if", "(", "$", "length", "!==", "1", ")", "{", "$", "error", "=", "'Expected 1 space after USE keyword; found %s'", ";", "$", "data", "=", "array", "(", "$", "length", ")", ";", "$", "phpcsFile", "->", "addError", "(", "$", "error", ",", "$", "use", ",", "'SpaceAfterUse'", ",", "$", "data", ")", ";", "}", "if", "(", "$", "tokens", "[", "(", "$", "use", "-", "1", ")", "]", "[", "'code'", "]", "!==", "T_WHITESPACE", ")", "{", "$", "length", "=", "0", ";", "}", "else", "if", "(", "$", "tokens", "[", "(", "$", "use", "-", "1", ")", "]", "[", "'content'", "]", "===", "\"\\t\"", ")", "{", "$", "length", "=", "'\\t'", ";", "}", "else", "{", "$", "length", "=", "strlen", "(", "$", "tokens", "[", "(", "$", "use", "-", "1", ")", "]", "[", "'content'", "]", ")", ";", "}", "if", "(", "$", "length", "!==", "1", ")", "{", "$", "error", "=", "'Expected 1 space before USE keyword; found %s'", ";", "$", "data", "=", "array", "(", "$", "length", ")", ";", "$", "phpcsFile", "->", "addError", "(", "$", "error", ",", "$", "use", ",", "'SpaceBeforeUse'", ",", "$", "data", ")", ";", "}", "}", "}", "// Check if this is a single line or multi-line declaration.", "$", "singleLine", "=", "TRUE", ";", "if", "(", "$", "tokens", "[", "$", "openBracket", "]", "[", "'line'", "]", "===", "$", "tokens", "[", "$", "closeBracket", "]", "[", "'line'", "]", ")", "{", "// Closures may use the USE keyword and so be multi-line in this way.", "if", "(", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'code'", "]", "===", "T_CLOSURE", ")", "{", "if", "(", "$", "use", "!==", "FALSE", ")", "{", "// If the opening and closing parenthesis of the use statement", "// are also on the same line, this is a single line declaration.", "$", "open", "=", "$", "phpcsFile", "->", "findNext", "(", "T_OPEN_PARENTHESIS", ",", "(", "$", "use", "+", "1", ")", ")", ";", "$", "close", "=", "$", "tokens", "[", "$", "open", "]", "[", "'parenthesis_closer'", "]", ";", "if", "(", "$", "tokens", "[", "$", "open", "]", "[", "'line'", "]", "!==", "$", "tokens", "[", "$", "close", "]", "[", "'line'", "]", ")", "{", "$", "singleLine", "=", "FALSE", ";", "}", "}", "}", "}", "else", "{", "$", "singleLine", "=", "FALSE", ";", "}", "if", "(", "$", "singleLine", "===", "TRUE", ")", "{", "$", "this", "->", "processSingleLineDeclaration", "(", "$", "phpcsFile", ",", "$", "stackPtr", ",", "$", "tokens", ")", ";", "}", "else", "{", "$", "this", "->", "processMultiLineDeclaration", "(", "$", "phpcsFile", ",", "$", "stackPtr", ",", "$", "tokens", ")", ";", "}", "}" ]
Processes this test, when one of its tokens is encountered. @param PHP_CodeSniffer_File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
[ "Processes", "this", "test", "when", "one", "of", "its", "tokens", "is", "encountered", "." ]
train
https://github.com/rawphp/RawCodeStandards/blob/aa40b4b085bfb3317843883124da246c32c4bb92/RawPHP/Sniffs/Functions/FunctionDeclarationSniff.php#L56-L158
rawphp/RawCodeStandards
RawPHP/Sniffs/Functions/FunctionDeclarationSniff.php
RawPHP_Sniffs_Functions_FunctionDeclarationSniff.processSingleLineDeclaration
public function processSingleLineDeclaration( PHP_CodeSniffer_File $phpcsFile, $stackPtr, $tokens ) { if ( $tokens[ $stackPtr ][ 'code' ] === T_CLOSURE ) { if ( class_exists( 'Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff', TRUE ) === FALSE ) { $message = 'Class '; $message .= 'Generic_Sniffs_Functions_OpeningFunctionBraceKernighanRitchieSniff '; $message .= 'not found'; throw new PHP_CodeSniffer_Exception( $message ); } $sniff = new Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff(); } else { if ( class_exists( 'Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff', TRUE ) === FALSE ) { $message = 'Class '; $message .= 'Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff '; $message .= 'not found'; throw new PHP_CodeSniffer_Exception( $message ); } $sniff = new Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff(); } $sniff->process( $phpcsFile, $stackPtr ); }
php
public function processSingleLineDeclaration( PHP_CodeSniffer_File $phpcsFile, $stackPtr, $tokens ) { if ( $tokens[ $stackPtr ][ 'code' ] === T_CLOSURE ) { if ( class_exists( 'Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff', TRUE ) === FALSE ) { $message = 'Class '; $message .= 'Generic_Sniffs_Functions_OpeningFunctionBraceKernighanRitchieSniff '; $message .= 'not found'; throw new PHP_CodeSniffer_Exception( $message ); } $sniff = new Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff(); } else { if ( class_exists( 'Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff', TRUE ) === FALSE ) { $message = 'Class '; $message .= 'Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff '; $message .= 'not found'; throw new PHP_CodeSniffer_Exception( $message ); } $sniff = new Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff(); } $sniff->process( $phpcsFile, $stackPtr ); }
[ "public", "function", "processSingleLineDeclaration", "(", "PHP_CodeSniffer_File", "$", "phpcsFile", ",", "$", "stackPtr", ",", "$", "tokens", ")", "{", "if", "(", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'code'", "]", "===", "T_CLOSURE", ")", "{", "if", "(", "class_exists", "(", "'Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff'", ",", "TRUE", ")", "===", "FALSE", ")", "{", "$", "message", "=", "'Class '", ";", "$", "message", ".=", "'Generic_Sniffs_Functions_OpeningFunctionBraceKernighanRitchieSniff '", ";", "$", "message", ".=", "'not found'", ";", "throw", "new", "PHP_CodeSniffer_Exception", "(", "$", "message", ")", ";", "}", "$", "sniff", "=", "new", "Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff", "(", ")", ";", "}", "else", "{", "if", "(", "class_exists", "(", "'Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff'", ",", "TRUE", ")", "===", "FALSE", ")", "{", "$", "message", "=", "'Class '", ";", "$", "message", ".=", "'Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff '", ";", "$", "message", ".=", "'not found'", ";", "throw", "new", "PHP_CodeSniffer_Exception", "(", "$", "message", ")", ";", "}", "$", "sniff", "=", "new", "Generic_Sniffs_Functions_OpeningFunctionBraceBsdAllmanSniff", "(", ")", ";", "}", "$", "sniff", "->", "process", "(", "$", "phpcsFile", ",", "$", "stackPtr", ")", ";", "}" ]
Processes single-line declarations. Just uses the Generic BSD-Allman brace sniff. @param PHP_CodeSniffer_File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @param array $tokens The stack of tokens that make up the file. @return void
[ "Processes", "single", "-", "line", "declarations", "." ]
train
https://github.com/rawphp/RawCodeStandards/blob/aa40b4b085bfb3317843883124da246c32c4bb92/RawPHP/Sniffs/Functions/FunctionDeclarationSniff.php#L173-L207
rawphp/RawCodeStandards
RawPHP/Sniffs/Functions/FunctionDeclarationSniff.php
RawPHP_Sniffs_Functions_FunctionDeclarationSniff.processMultiLineDeclaration
public function processMultiLineDeclaration( PHP_CodeSniffer_File $phpcsFile, $stackPtr, $tokens ) { // We need to work out how far indented the function // declaration itself is, so we can work out how far to // indent parameters. $functionIndent = 0; for ( $i = ($stackPtr - 1); $i >= 0; $i-- ) { if ( $tokens[ $i ][ 'line' ] !== $tokens[ $stackPtr ][ 'line' ] ) { $i++; break; } } if ( $tokens[ $i ][ 'code' ] === T_WHITESPACE ) { $functionIndent = strlen( $tokens[ $i ][ 'content' ] ); } // The closing parenthesis must be on a new line, even // when checking abstract function definitions. $closeBracket = $tokens[ $stackPtr ][ 'parenthesis_closer' ]; $prev = $phpcsFile->findPrevious( T_WHITESPACE, ($closeBracket - 1 ), NULL, TRUE ); if ( $tokens[ $closeBracket ][ 'line' ] !== $tokens[ $tokens[ $closeBracket ][ 'parenthesis_opener' ] ][ 'line' ] ) { if ( $tokens[ $prev ][ 'line' ] === $tokens[ $closeBracket ][ 'line' ] ) { $error = 'The closing parenthesis of a multi-line function '; $error .= 'declaration must be on a new line'; $phpcsFile->addError( $error, $closeBracket, 'CloseBracketLine' ); } } // If this is a closure and is using a USE statement, the closing // parenthesis we need to look at from now on is the closing parenthesis // of the USE statement. if ( $tokens[ $stackPtr ][ 'code' ] === T_CLOSURE ) { $use = $phpcsFile->findNext( T_USE, ($closeBracket + 1 ), $tokens[ $stackPtr ][ 'scope_opener' ] ); if ( $use !== FALSE ) { $open = $phpcsFile->findNext( T_OPEN_PARENTHESIS, ($use + 1 ) ); $closeBracket = $tokens[ $open ][ 'parenthesis_closer' ]; $prev = $phpcsFile->findPrevious( T_WHITESPACE, ($closeBracket - 1 ), NULL, TRUE ); if ( $tokens[ $closeBracket ][ 'line' ] !== $tokens[ $tokens[ $closeBracket ][ 'parenthesis_opener' ] ][ 'line' ] ) { if ( $tokens[ $prev ][ 'line' ] === $tokens[ $closeBracket ][ 'line' ] ) { $error = 'The closing parenthesis of a multi-line use '; $error .= 'declaration must be on a new line'; $phpcsFile->addError( $error, $closeBracket, 'CloseBracketLine' ); } } } } // Each line between the parenthesis should be indented 4 spaces. $openBracket = $tokens[ $stackPtr ][ 'parenthesis_opener' ]; $lastLine = $tokens[ $openBracket ][ 'line' ]; for ( $i = ($openBracket + 1); $i < $closeBracket; $i++ ) { if ( $tokens[ $i ][ 'line' ] !== $lastLine ) { if ( $i === $tokens[ $stackPtr ][ 'parenthesis_closer' ] || ($tokens[ $i ][ 'code' ] === T_WHITESPACE && ($i + 1) === $tokens[ $stackPtr ][ 'parenthesis_closer' ]) ) { // Closing braces need to be indented to the same level // as the function. $expectedIndent = $functionIndent; } else { $expectedIndent = ($functionIndent + 4); } // We changed lines, so this should be a whitespace indent token. if ( $tokens[ $i ][ 'code' ] !== T_WHITESPACE ) { $foundIndent = 0; } else { $foundIndent = strlen( $tokens[ $i ][ 'content' ] ); } if ( $expectedIndent !== $foundIndent ) { $error = 'Multi-line function declaration not indented '; $error .= 'correctly; expected %s spaces but found %s'; $data = array( $expectedIndent, $foundIndent, ); $phpcsFile->addError( $error, $i, 'Indent', $data ); } $lastLine = $tokens[ $i ][ 'line' ]; } if ( $tokens[ $i ][ 'code' ] === T_ARRAY ) { // Skip arrays as they have their own indentation rules. $i = $tokens[ $i ][ 'parenthesis_closer' ]; $lastLine = $tokens[ $i ][ 'line' ]; continue; } } if ( isset( $tokens[ $stackPtr ][ 'scope_opener' ] ) === TRUE ) { // The opening brace needs to be on a new line $next = $tokens[ ($closeBracket + 1) ]; if ( $next[ 'content' ] !== $phpcsFile->eolChar ) { $error = 'Opening brace must be on a new line'; $phpcsFile->addError( $error, $next, 'NoSpaceBeforeOpenBrace' ); } // And just in case they do something funny before the brace... $next = $phpcsFile->findNext( T_WHITESPACE, ($closeBracket + 1 ), NULL, TRUE ); if ( $next !== FALSE && $tokens[ $next ][ 'code' ] !== T_OPEN_CURLY_BRACKET ) { $error = 'There must be a single space between the closing '; $error .= 'parenthesis and the opening brace of a multi-line '; $error .= 'function declaration'; $phpcsFile->addError( $error, $next, 'NoSpaceBeforeOpenBrace' ); } } }
php
public function processMultiLineDeclaration( PHP_CodeSniffer_File $phpcsFile, $stackPtr, $tokens ) { // We need to work out how far indented the function // declaration itself is, so we can work out how far to // indent parameters. $functionIndent = 0; for ( $i = ($stackPtr - 1); $i >= 0; $i-- ) { if ( $tokens[ $i ][ 'line' ] !== $tokens[ $stackPtr ][ 'line' ] ) { $i++; break; } } if ( $tokens[ $i ][ 'code' ] === T_WHITESPACE ) { $functionIndent = strlen( $tokens[ $i ][ 'content' ] ); } // The closing parenthesis must be on a new line, even // when checking abstract function definitions. $closeBracket = $tokens[ $stackPtr ][ 'parenthesis_closer' ]; $prev = $phpcsFile->findPrevious( T_WHITESPACE, ($closeBracket - 1 ), NULL, TRUE ); if ( $tokens[ $closeBracket ][ 'line' ] !== $tokens[ $tokens[ $closeBracket ][ 'parenthesis_opener' ] ][ 'line' ] ) { if ( $tokens[ $prev ][ 'line' ] === $tokens[ $closeBracket ][ 'line' ] ) { $error = 'The closing parenthesis of a multi-line function '; $error .= 'declaration must be on a new line'; $phpcsFile->addError( $error, $closeBracket, 'CloseBracketLine' ); } } // If this is a closure and is using a USE statement, the closing // parenthesis we need to look at from now on is the closing parenthesis // of the USE statement. if ( $tokens[ $stackPtr ][ 'code' ] === T_CLOSURE ) { $use = $phpcsFile->findNext( T_USE, ($closeBracket + 1 ), $tokens[ $stackPtr ][ 'scope_opener' ] ); if ( $use !== FALSE ) { $open = $phpcsFile->findNext( T_OPEN_PARENTHESIS, ($use + 1 ) ); $closeBracket = $tokens[ $open ][ 'parenthesis_closer' ]; $prev = $phpcsFile->findPrevious( T_WHITESPACE, ($closeBracket - 1 ), NULL, TRUE ); if ( $tokens[ $closeBracket ][ 'line' ] !== $tokens[ $tokens[ $closeBracket ][ 'parenthesis_opener' ] ][ 'line' ] ) { if ( $tokens[ $prev ][ 'line' ] === $tokens[ $closeBracket ][ 'line' ] ) { $error = 'The closing parenthesis of a multi-line use '; $error .= 'declaration must be on a new line'; $phpcsFile->addError( $error, $closeBracket, 'CloseBracketLine' ); } } } } // Each line between the parenthesis should be indented 4 spaces. $openBracket = $tokens[ $stackPtr ][ 'parenthesis_opener' ]; $lastLine = $tokens[ $openBracket ][ 'line' ]; for ( $i = ($openBracket + 1); $i < $closeBracket; $i++ ) { if ( $tokens[ $i ][ 'line' ] !== $lastLine ) { if ( $i === $tokens[ $stackPtr ][ 'parenthesis_closer' ] || ($tokens[ $i ][ 'code' ] === T_WHITESPACE && ($i + 1) === $tokens[ $stackPtr ][ 'parenthesis_closer' ]) ) { // Closing braces need to be indented to the same level // as the function. $expectedIndent = $functionIndent; } else { $expectedIndent = ($functionIndent + 4); } // We changed lines, so this should be a whitespace indent token. if ( $tokens[ $i ][ 'code' ] !== T_WHITESPACE ) { $foundIndent = 0; } else { $foundIndent = strlen( $tokens[ $i ][ 'content' ] ); } if ( $expectedIndent !== $foundIndent ) { $error = 'Multi-line function declaration not indented '; $error .= 'correctly; expected %s spaces but found %s'; $data = array( $expectedIndent, $foundIndent, ); $phpcsFile->addError( $error, $i, 'Indent', $data ); } $lastLine = $tokens[ $i ][ 'line' ]; } if ( $tokens[ $i ][ 'code' ] === T_ARRAY ) { // Skip arrays as they have their own indentation rules. $i = $tokens[ $i ][ 'parenthesis_closer' ]; $lastLine = $tokens[ $i ][ 'line' ]; continue; } } if ( isset( $tokens[ $stackPtr ][ 'scope_opener' ] ) === TRUE ) { // The opening brace needs to be on a new line $next = $tokens[ ($closeBracket + 1) ]; if ( $next[ 'content' ] !== $phpcsFile->eolChar ) { $error = 'Opening brace must be on a new line'; $phpcsFile->addError( $error, $next, 'NoSpaceBeforeOpenBrace' ); } // And just in case they do something funny before the brace... $next = $phpcsFile->findNext( T_WHITESPACE, ($closeBracket + 1 ), NULL, TRUE ); if ( $next !== FALSE && $tokens[ $next ][ 'code' ] !== T_OPEN_CURLY_BRACKET ) { $error = 'There must be a single space between the closing '; $error .= 'parenthesis and the opening brace of a multi-line '; $error .= 'function declaration'; $phpcsFile->addError( $error, $next, 'NoSpaceBeforeOpenBrace' ); } } }
[ "public", "function", "processMultiLineDeclaration", "(", "PHP_CodeSniffer_File", "$", "phpcsFile", ",", "$", "stackPtr", ",", "$", "tokens", ")", "{", "// We need to work out how far indented the function", "// declaration itself is, so we can work out how far to", "// indent parameters.", "$", "functionIndent", "=", "0", ";", "for", "(", "$", "i", "=", "(", "$", "stackPtr", "-", "1", ")", ";", "$", "i", ">=", "0", ";", "$", "i", "--", ")", "{", "if", "(", "$", "tokens", "[", "$", "i", "]", "[", "'line'", "]", "!==", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'line'", "]", ")", "{", "$", "i", "++", ";", "break", ";", "}", "}", "if", "(", "$", "tokens", "[", "$", "i", "]", "[", "'code'", "]", "===", "T_WHITESPACE", ")", "{", "$", "functionIndent", "=", "strlen", "(", "$", "tokens", "[", "$", "i", "]", "[", "'content'", "]", ")", ";", "}", "// The closing parenthesis must be on a new line, even", "// when checking abstract function definitions.", "$", "closeBracket", "=", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'parenthesis_closer'", "]", ";", "$", "prev", "=", "$", "phpcsFile", "->", "findPrevious", "(", "T_WHITESPACE", ",", "(", "$", "closeBracket", "-", "1", ")", ",", "NULL", ",", "TRUE", ")", ";", "if", "(", "$", "tokens", "[", "$", "closeBracket", "]", "[", "'line'", "]", "!==", "$", "tokens", "[", "$", "tokens", "[", "$", "closeBracket", "]", "[", "'parenthesis_opener'", "]", "]", "[", "'line'", "]", ")", "{", "if", "(", "$", "tokens", "[", "$", "prev", "]", "[", "'line'", "]", "===", "$", "tokens", "[", "$", "closeBracket", "]", "[", "'line'", "]", ")", "{", "$", "error", "=", "'The closing parenthesis of a multi-line function '", ";", "$", "error", ".=", "'declaration must be on a new line'", ";", "$", "phpcsFile", "->", "addError", "(", "$", "error", ",", "$", "closeBracket", ",", "'CloseBracketLine'", ")", ";", "}", "}", "// If this is a closure and is using a USE statement, the closing", "// parenthesis we need to look at from now on is the closing parenthesis", "// of the USE statement.", "if", "(", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'code'", "]", "===", "T_CLOSURE", ")", "{", "$", "use", "=", "$", "phpcsFile", "->", "findNext", "(", "T_USE", ",", "(", "$", "closeBracket", "+", "1", ")", ",", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'scope_opener'", "]", ")", ";", "if", "(", "$", "use", "!==", "FALSE", ")", "{", "$", "open", "=", "$", "phpcsFile", "->", "findNext", "(", "T_OPEN_PARENTHESIS", ",", "(", "$", "use", "+", "1", ")", ")", ";", "$", "closeBracket", "=", "$", "tokens", "[", "$", "open", "]", "[", "'parenthesis_closer'", "]", ";", "$", "prev", "=", "$", "phpcsFile", "->", "findPrevious", "(", "T_WHITESPACE", ",", "(", "$", "closeBracket", "-", "1", ")", ",", "NULL", ",", "TRUE", ")", ";", "if", "(", "$", "tokens", "[", "$", "closeBracket", "]", "[", "'line'", "]", "!==", "$", "tokens", "[", "$", "tokens", "[", "$", "closeBracket", "]", "[", "'parenthesis_opener'", "]", "]", "[", "'line'", "]", ")", "{", "if", "(", "$", "tokens", "[", "$", "prev", "]", "[", "'line'", "]", "===", "$", "tokens", "[", "$", "closeBracket", "]", "[", "'line'", "]", ")", "{", "$", "error", "=", "'The closing parenthesis of a multi-line use '", ";", "$", "error", ".=", "'declaration must be on a new line'", ";", "$", "phpcsFile", "->", "addError", "(", "$", "error", ",", "$", "closeBracket", ",", "'CloseBracketLine'", ")", ";", "}", "}", "}", "}", "// Each line between the parenthesis should be indented 4 spaces.", "$", "openBracket", "=", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'parenthesis_opener'", "]", ";", "$", "lastLine", "=", "$", "tokens", "[", "$", "openBracket", "]", "[", "'line'", "]", ";", "for", "(", "$", "i", "=", "(", "$", "openBracket", "+", "1", ")", ";", "$", "i", "<", "$", "closeBracket", ";", "$", "i", "++", ")", "{", "if", "(", "$", "tokens", "[", "$", "i", "]", "[", "'line'", "]", "!==", "$", "lastLine", ")", "{", "if", "(", "$", "i", "===", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'parenthesis_closer'", "]", "||", "(", "$", "tokens", "[", "$", "i", "]", "[", "'code'", "]", "===", "T_WHITESPACE", "&&", "(", "$", "i", "+", "1", ")", "===", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'parenthesis_closer'", "]", ")", ")", "{", "// Closing braces need to be indented to the same level", "// as the function.", "$", "expectedIndent", "=", "$", "functionIndent", ";", "}", "else", "{", "$", "expectedIndent", "=", "(", "$", "functionIndent", "+", "4", ")", ";", "}", "// We changed lines, so this should be a whitespace indent token.", "if", "(", "$", "tokens", "[", "$", "i", "]", "[", "'code'", "]", "!==", "T_WHITESPACE", ")", "{", "$", "foundIndent", "=", "0", ";", "}", "else", "{", "$", "foundIndent", "=", "strlen", "(", "$", "tokens", "[", "$", "i", "]", "[", "'content'", "]", ")", ";", "}", "if", "(", "$", "expectedIndent", "!==", "$", "foundIndent", ")", "{", "$", "error", "=", "'Multi-line function declaration not indented '", ";", "$", "error", ".=", "'correctly; expected %s spaces but found %s'", ";", "$", "data", "=", "array", "(", "$", "expectedIndent", ",", "$", "foundIndent", ",", ")", ";", "$", "phpcsFile", "->", "addError", "(", "$", "error", ",", "$", "i", ",", "'Indent'", ",", "$", "data", ")", ";", "}", "$", "lastLine", "=", "$", "tokens", "[", "$", "i", "]", "[", "'line'", "]", ";", "}", "if", "(", "$", "tokens", "[", "$", "i", "]", "[", "'code'", "]", "===", "T_ARRAY", ")", "{", "// Skip arrays as they have their own indentation rules.", "$", "i", "=", "$", "tokens", "[", "$", "i", "]", "[", "'parenthesis_closer'", "]", ";", "$", "lastLine", "=", "$", "tokens", "[", "$", "i", "]", "[", "'line'", "]", ";", "continue", ";", "}", "}", "if", "(", "isset", "(", "$", "tokens", "[", "$", "stackPtr", "]", "[", "'scope_opener'", "]", ")", "===", "TRUE", ")", "{", "// The opening brace needs to be on a new line", "$", "next", "=", "$", "tokens", "[", "(", "$", "closeBracket", "+", "1", ")", "]", ";", "if", "(", "$", "next", "[", "'content'", "]", "!==", "$", "phpcsFile", "->", "eolChar", ")", "{", "$", "error", "=", "'Opening brace must be on a new line'", ";", "$", "phpcsFile", "->", "addError", "(", "$", "error", ",", "$", "next", ",", "'NoSpaceBeforeOpenBrace'", ")", ";", "}", "// And just in case they do something funny before the brace...", "$", "next", "=", "$", "phpcsFile", "->", "findNext", "(", "T_WHITESPACE", ",", "(", "$", "closeBracket", "+", "1", ")", ",", "NULL", ",", "TRUE", ")", ";", "if", "(", "$", "next", "!==", "FALSE", "&&", "$", "tokens", "[", "$", "next", "]", "[", "'code'", "]", "!==", "T_OPEN_CURLY_BRACKET", ")", "{", "$", "error", "=", "'There must be a single space between the closing '", ";", "$", "error", ".=", "'parenthesis and the opening brace of a multi-line '", ";", "$", "error", ".=", "'function declaration'", ";", "$", "phpcsFile", "->", "addError", "(", "$", "error", ",", "$", "next", ",", "'NoSpaceBeforeOpenBrace'", ")", ";", "}", "}", "}" ]
Processes mutli-line declarations. @param PHP_CodeSniffer_File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @param array $tokens The stack of tokens that make up the file. @return void
[ "Processes", "mutli", "-", "line", "declarations", "." ]
train
https://github.com/rawphp/RawCodeStandards/blob/aa40b4b085bfb3317843883124da246c32c4bb92/RawPHP/Sniffs/Functions/FunctionDeclarationSniff.php#L220-L370
dmitrya2e/filtration-bundle
Filter/Filter/AbstractDateFilter.php
AbstractDateFilter.appendFormFieldsToForm
public function appendFormFieldsToForm(FormBuilderInterface $formBuilder) { if ($this->isSingle()) { return $this->appendSingleFormFields($formBuilder); } return $this->appendRangedFormFields($formBuilder); }
php
public function appendFormFieldsToForm(FormBuilderInterface $formBuilder) { if ($this->isSingle()) { return $this->appendSingleFormFields($formBuilder); } return $this->appendRangedFormFields($formBuilder); }
[ "public", "function", "appendFormFieldsToForm", "(", "FormBuilderInterface", "$", "formBuilder", ")", "{", "if", "(", "$", "this", "->", "isSingle", "(", ")", ")", "{", "return", "$", "this", "->", "appendSingleFormFields", "(", "$", "formBuilder", ")", ";", "}", "return", "$", "this", "->", "appendRangedFormFields", "(", "$", "formBuilder", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/dmitrya2e/filtration-bundle/blob/fed5764af4e43871835744fb84957b2a76e9a215/Filter/Filter/AbstractDateFilter.php#L46-L53
Ydle/HubBundle
Controller/RestNodeController.php
RestNodeController.getNodesListAction
public function getNodesListAction(ParamFetcher $paramFetcher) { $page = $paramFetcher->get('page'); $count = $paramFetcher->get('count'); $pager = $this->getNodeManager()->getPager($this->filterCriteria($paramFetcher), $page, $count); return $pager; }
php
public function getNodesListAction(ParamFetcher $paramFetcher) { $page = $paramFetcher->get('page'); $count = $paramFetcher->get('count'); $pager = $this->getNodeManager()->getPager($this->filterCriteria($paramFetcher), $page, $count); return $pager; }
[ "public", "function", "getNodesListAction", "(", "ParamFetcher", "$", "paramFetcher", ")", "{", "$", "page", "=", "$", "paramFetcher", "->", "get", "(", "'page'", ")", ";", "$", "count", "=", "$", "paramFetcher", "->", "get", "(", "'count'", ")", ";", "$", "pager", "=", "$", "this", "->", "getNodeManager", "(", ")", "->", "getPager", "(", "$", "this", "->", "filterCriteria", "(", "$", "paramFetcher", ")", ",", "$", "page", ",", "$", "count", ")", ";", "return", "$", "pager", ";", "}" ]
Retrieve the list of available nodes @QueryParam(name="page", requirements="\d+", default="0", description="Number of page") @QueryParam(name="count", requirements="\d+", default="0", description="Number of nodes by page") @param ParamFetcher $paramFetcher
[ "Retrieve", "the", "list", "of", "available", "nodes" ]
train
https://github.com/Ydle/HubBundle/blob/7fa423241246bcfd115f2ed3ad3997b4b63adb01/Controller/RestNodeController.php#L53-L61
miaoxing/plugin
src/ConstTrait.php
ConstTrait.getConsts
public function getConsts($prefix) { if (isset(self::$consts[$prefix])) { return self::$consts[$prefix]; } // 1. Get all class constants $class = new \ReflectionClass($this); $consts = $class->getConstants(); // 2. Use exiting constant configs $property = lcfirst(str_replace('_', '', ucwords($prefix, '_'))) . 'Table'; if (isset($this->$property)) { $data = $this->$property; } else { $data = []; } // 3. Generate id and name $prefix .= '_'; $length = strlen($prefix); foreach ($consts as $name => $id) { if (stripos($name, $prefix) !== 0) { continue; } if (in_array($name, $this->constExcludes)) { continue; } $data[$id]['id'] = $id; $data[$id]['name'] = strtolower(strtr(substr($name, $length), ['_' => '-'])); } self::$consts[$prefix] = $data; return $data; }
php
public function getConsts($prefix) { if (isset(self::$consts[$prefix])) { return self::$consts[$prefix]; } // 1. Get all class constants $class = new \ReflectionClass($this); $consts = $class->getConstants(); // 2. Use exiting constant configs $property = lcfirst(str_replace('_', '', ucwords($prefix, '_'))) . 'Table'; if (isset($this->$property)) { $data = $this->$property; } else { $data = []; } // 3. Generate id and name $prefix .= '_'; $length = strlen($prefix); foreach ($consts as $name => $id) { if (stripos($name, $prefix) !== 0) { continue; } if (in_array($name, $this->constExcludes)) { continue; } $data[$id]['id'] = $id; $data[$id]['name'] = strtolower(strtr(substr($name, $length), ['_' => '-'])); } self::$consts[$prefix] = $data; return $data; }
[ "public", "function", "getConsts", "(", "$", "prefix", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "consts", "[", "$", "prefix", "]", ")", ")", "{", "return", "self", "::", "$", "consts", "[", "$", "prefix", "]", ";", "}", "// 1. Get all class constants", "$", "class", "=", "new", "\\", "ReflectionClass", "(", "$", "this", ")", ";", "$", "consts", "=", "$", "class", "->", "getConstants", "(", ")", ";", "// 2. Use exiting constant configs", "$", "property", "=", "lcfirst", "(", "str_replace", "(", "'_'", ",", "''", ",", "ucwords", "(", "$", "prefix", ",", "'_'", ")", ")", ")", ".", "'Table'", ";", "if", "(", "isset", "(", "$", "this", "->", "$", "property", ")", ")", "{", "$", "data", "=", "$", "this", "->", "$", "property", ";", "}", "else", "{", "$", "data", "=", "[", "]", ";", "}", "// 3. Generate id and name", "$", "prefix", ".=", "'_'", ";", "$", "length", "=", "strlen", "(", "$", "prefix", ")", ";", "foreach", "(", "$", "consts", "as", "$", "name", "=>", "$", "id", ")", "{", "if", "(", "stripos", "(", "$", "name", ",", "$", "prefix", ")", "!==", "0", ")", "{", "continue", ";", "}", "if", "(", "in_array", "(", "$", "name", ",", "$", "this", "->", "constExcludes", ")", ")", "{", "continue", ";", "}", "$", "data", "[", "$", "id", "]", "[", "'id'", "]", "=", "$", "id", ";", "$", "data", "[", "$", "id", "]", "[", "'name'", "]", "=", "strtolower", "(", "strtr", "(", "substr", "(", "$", "name", ",", "$", "length", ")", ",", "[", "'_'", "=>", "'-'", "]", ")", ")", ";", "}", "self", "::", "$", "consts", "[", "$", "prefix", "]", "=", "$", "data", ";", "return", "$", "data", ";", "}" ]
Get constants table by prefix @param string $prefix @return array
[ "Get", "constants", "table", "by", "prefix" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/ConstTrait.php#L31-L66
miaoxing/plugin
src/ConstTrait.php
ConstTrait.getConstValue
public function getConstValue($prefix, $id, $key) { $consts = $this->getConsts($prefix); return isset($consts[$id][$key]) ? $consts[$id][$key] : null; }
php
public function getConstValue($prefix, $id, $key) { $consts = $this->getConsts($prefix); return isset($consts[$id][$key]) ? $consts[$id][$key] : null; }
[ "public", "function", "getConstValue", "(", "$", "prefix", ",", "$", "id", ",", "$", "key", ")", "{", "$", "consts", "=", "$", "this", "->", "getConsts", "(", "$", "prefix", ")", ";", "return", "isset", "(", "$", "consts", "[", "$", "id", "]", "[", "$", "key", "]", ")", "?", "$", "consts", "[", "$", "id", "]", "[", "$", "key", "]", ":", "null", ";", "}" ]
Returns the constant value by specified id and key @param string $prefix @param int $id @param string $key @return mixed
[ "Returns", "the", "constant", "value", "by", "specified", "id", "and", "key" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/ConstTrait.php#L76-L81
miaoxing/plugin
src/ConstTrait.php
ConstTrait.getConstIdByName
public function getConstIdByName($prefix, $name) { $nameToIds = $this->getConstNameToIds($prefix); return isset($nameToIds[$name]) ? $nameToIds[$name] : null; }
php
public function getConstIdByName($prefix, $name) { $nameToIds = $this->getConstNameToIds($prefix); return isset($nameToIds[$name]) ? $nameToIds[$name] : null; }
[ "public", "function", "getConstIdByName", "(", "$", "prefix", ",", "$", "name", ")", "{", "$", "nameToIds", "=", "$", "this", "->", "getConstNameToIds", "(", "$", "prefix", ")", ";", "return", "isset", "(", "$", "nameToIds", "[", "$", "name", "]", ")", "?", "$", "nameToIds", "[", "$", "name", "]", ":", "null", ";", "}" ]
Returns the constant id by name @param string $prefix @param string $name @return int
[ "Returns", "the", "constant", "id", "by", "name" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/ConstTrait.php#L114-L119
miaoxing/plugin
src/ConstTrait.php
ConstTrait.getConstNameToIds
protected function getConstNameToIds($prefix) { if (!isset(self::$constNameToIds[$prefix])) { foreach ($this->getConsts($prefix) as $const) { self::$constNameToIds[$prefix][$const['name']] = $const['id']; } } return self::$constNameToIds[$prefix]; }
php
protected function getConstNameToIds($prefix) { if (!isset(self::$constNameToIds[$prefix])) { foreach ($this->getConsts($prefix) as $const) { self::$constNameToIds[$prefix][$const['name']] = $const['id']; } } return self::$constNameToIds[$prefix]; }
[ "protected", "function", "getConstNameToIds", "(", "$", "prefix", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "constNameToIds", "[", "$", "prefix", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "getConsts", "(", "$", "prefix", ")", "as", "$", "const", ")", "{", "self", "::", "$", "constNameToIds", "[", "$", "prefix", "]", "[", "$", "const", "[", "'name'", "]", "]", "=", "$", "const", "[", "'id'", "]", ";", "}", "}", "return", "self", "::", "$", "constNameToIds", "[", "$", "prefix", "]", ";", "}" ]
Returns the name to id map @param string $prefix @return array
[ "Returns", "the", "name", "to", "id", "map" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/ConstTrait.php#L127-L136
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.between
public static function between($input, $min, $max) { $length = mb_strlen($input); return ($length <= $max && $length >= $min); }
php
public static function between($input, $min, $max) { $length = mb_strlen($input); return ($length <= $max && $length >= $min); }
[ "public", "static", "function", "between", "(", "$", "input", ",", "$", "min", ",", "$", "max", ")", "{", "$", "length", "=", "mb_strlen", "(", "$", "input", ")", ";", "return", "(", "$", "length", "<=", "$", "max", "&&", "$", "length", ">=", "$", "min", ")", ";", "}" ]
Validate input string length is between the min and max. @param string $input @param int $min @param int $max @return bool
[ "Validate", "input", "string", "length", "is", "between", "the", "min", "and", "max", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L75-L79
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.comparison
public static function comparison($input, $check, $mode) { switch (mb_strtolower($mode)) { case 'greater': case 'gt': case '>': return ($input > $check); break; case 'greaterorequal': case 'gte': case '>=': return ($input >= $check); break; case 'less': case 'lt': case '<': return ($input < $check); break; case 'lessorequal': case 'lte': case '<=': return ($input <= $check); break; case 'equal': case 'eq': case '==': case '=': return ($input == $check); break; case 'notequal': case 'neq': case 'ne': case '!=': return ($input != $check); break; default: throw new InvalidArgumentException(sprintf('Unsupported mode %s for %s', $mode, __METHOD__)); break; } }
php
public static function comparison($input, $check, $mode) { switch (mb_strtolower($mode)) { case 'greater': case 'gt': case '>': return ($input > $check); break; case 'greaterorequal': case 'gte': case '>=': return ($input >= $check); break; case 'less': case 'lt': case '<': return ($input < $check); break; case 'lessorequal': case 'lte': case '<=': return ($input <= $check); break; case 'equal': case 'eq': case '==': case '=': return ($input == $check); break; case 'notequal': case 'neq': case 'ne': case '!=': return ($input != $check); break; default: throw new InvalidArgumentException(sprintf('Unsupported mode %s for %s', $mode, __METHOD__)); break; } }
[ "public", "static", "function", "comparison", "(", "$", "input", ",", "$", "check", ",", "$", "mode", ")", "{", "switch", "(", "mb_strtolower", "(", "$", "mode", ")", ")", "{", "case", "'greater'", ":", "case", "'gt'", ":", "case", "'>'", ":", "return", "(", "$", "input", ">", "$", "check", ")", ";", "break", ";", "case", "'greaterorequal'", ":", "case", "'gte'", ":", "case", "'>='", ":", "return", "(", "$", "input", ">=", "$", "check", ")", ";", "break", ";", "case", "'less'", ":", "case", "'lt'", ":", "case", "'<'", ":", "return", "(", "$", "input", "<", "$", "check", ")", ";", "break", ";", "case", "'lessorequal'", ":", "case", "'lte'", ":", "case", "'<='", ":", "return", "(", "$", "input", "<=", "$", "check", ")", ";", "break", ";", "case", "'equal'", ":", "case", "'eq'", ":", "case", "'=='", ":", "case", "'='", ":", "return", "(", "$", "input", "==", "$", "check", ")", ";", "break", ";", "case", "'notequal'", ":", "case", "'neq'", ":", "case", "'ne'", ":", "case", "'!='", ":", "return", "(", "$", "input", "!=", "$", "check", ")", ";", "break", ";", "default", ":", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Unsupported mode %s for %s'", ",", "$", "mode", ",", "__METHOD__", ")", ")", ";", "break", ";", "}", "}" ]
Compare two numerical values. @param int $input @param int $check @param string $mode @return bool @throws \Titon\Utility\Exception\InvalidArgumentException
[ "Compare", "two", "numerical", "values", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L111-L149
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.creditCard
public static function creditCard($input, $types = null) { $input = str_replace(array('-', ' '), '', $input); if (mb_strlen($input) < 13) { return false; } $cards = array( static::AMERICAN_EXPRESS => '/^3[4|7]\\d{13}$/', static::BANKCARD => '/^56(10\\d\\d|022[1-5])\\d{10}$/', static::DISCOVER => '/^(?:6011|650\\d)\\d{12}$/', static::ENROUTE => '/^2(?:014|149)\\d{11}$/', static::JCB => '/^(3\\d{4}|2100|1800)\\d{11}$/', static::MAESTRO => '/^(?:5020|6\\d{3})\\d{12}$/', static::MASTERCARD => '/^5[1-5]\\d{14}$/', static::DINERS_CLUB => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/', static::SOLO_DEBIT => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/', static::SWITCH_DEBIT => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/', static::VISA => '/^4\\d{12}(\\d{3})?$/', static::VISA_ELECTRON => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/', static::VOYAGER => '/^8699[0-9]{11}$/' ); if ($types) { $validate = array(); foreach ((array) $types as $card) { if (isset($cards[$card])) { $validate[$card] = $cards[$card]; } else { throw new InvalidCreditCardException(sprintf('Credit card type %s does not exist', $card)); } } } else { $validate = $cards; } foreach ($validate as $pattern) { if (preg_match($pattern, $input)) { return static::luhn($input); } } return false; }
php
public static function creditCard($input, $types = null) { $input = str_replace(array('-', ' '), '', $input); if (mb_strlen($input) < 13) { return false; } $cards = array( static::AMERICAN_EXPRESS => '/^3[4|7]\\d{13}$/', static::BANKCARD => '/^56(10\\d\\d|022[1-5])\\d{10}$/', static::DISCOVER => '/^(?:6011|650\\d)\\d{12}$/', static::ENROUTE => '/^2(?:014|149)\\d{11}$/', static::JCB => '/^(3\\d{4}|2100|1800)\\d{11}$/', static::MAESTRO => '/^(?:5020|6\\d{3})\\d{12}$/', static::MASTERCARD => '/^5[1-5]\\d{14}$/', static::DINERS_CLUB => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/', static::SOLO_DEBIT => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/', static::SWITCH_DEBIT => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/', static::VISA => '/^4\\d{12}(\\d{3})?$/', static::VISA_ELECTRON => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/', static::VOYAGER => '/^8699[0-9]{11}$/' ); if ($types) { $validate = array(); foreach ((array) $types as $card) { if (isset($cards[$card])) { $validate[$card] = $cards[$card]; } else { throw new InvalidCreditCardException(sprintf('Credit card type %s does not exist', $card)); } } } else { $validate = $cards; } foreach ($validate as $pattern) { if (preg_match($pattern, $input)) { return static::luhn($input); } } return false; }
[ "public", "static", "function", "creditCard", "(", "$", "input", ",", "$", "types", "=", "null", ")", "{", "$", "input", "=", "str_replace", "(", "array", "(", "'-'", ",", "' '", ")", ",", "''", ",", "$", "input", ")", ";", "if", "(", "mb_strlen", "(", "$", "input", ")", "<", "13", ")", "{", "return", "false", ";", "}", "$", "cards", "=", "array", "(", "static", "::", "AMERICAN_EXPRESS", "=>", "'/^3[4|7]\\\\d{13}$/'", ",", "static", "::", "BANKCARD", "=>", "'/^56(10\\\\d\\\\d|022[1-5])\\\\d{10}$/'", ",", "static", "::", "DISCOVER", "=>", "'/^(?:6011|650\\\\d)\\\\d{12}$/'", ",", "static", "::", "ENROUTE", "=>", "'/^2(?:014|149)\\\\d{11}$/'", ",", "static", "::", "JCB", "=>", "'/^(3\\\\d{4}|2100|1800)\\\\d{11}$/'", ",", "static", "::", "MAESTRO", "=>", "'/^(?:5020|6\\\\d{3})\\\\d{12}$/'", ",", "static", "::", "MASTERCARD", "=>", "'/^5[1-5]\\\\d{14}$/'", ",", "static", "::", "DINERS_CLUB", "=>", "'/^(?:3(0[0-5]|[68]\\\\d)\\\\d{11})|(?:5[1-5]\\\\d{14})$/'", ",", "static", "::", "SOLO_DEBIT", "=>", "'/^(6334[5-9][0-9]|6767[0-9]{2})\\\\d{10}(\\\\d{2,3})?$/'", ",", "static", "::", "SWITCH_DEBIT", "=>", "'/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\\\d{10}(\\\\d{2,3})?)|(?:564182\\\\d{10}(\\\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\\\d{10}(\\\\d{2,3})?)$/'", ",", "static", "::", "VISA", "=>", "'/^4\\\\d{12}(\\\\d{3})?$/'", ",", "static", "::", "VISA_ELECTRON", "=>", "'/^(?:417500|4917\\\\d{2}|4913\\\\d{2})\\\\d{10}$/'", ",", "static", "::", "VOYAGER", "=>", "'/^8699[0-9]{11}$/'", ")", ";", "if", "(", "$", "types", ")", "{", "$", "validate", "=", "array", "(", ")", ";", "foreach", "(", "(", "array", ")", "$", "types", "as", "$", "card", ")", "{", "if", "(", "isset", "(", "$", "cards", "[", "$", "card", "]", ")", ")", "{", "$", "validate", "[", "$", "card", "]", "=", "$", "cards", "[", "$", "card", "]", ";", "}", "else", "{", "throw", "new", "InvalidCreditCardException", "(", "sprintf", "(", "'Credit card type %s does not exist'", ",", "$", "card", ")", ")", ";", "}", "}", "}", "else", "{", "$", "validate", "=", "$", "cards", ";", "}", "foreach", "(", "$", "validate", "as", "$", "pattern", ")", "{", "if", "(", "preg_match", "(", "$", "pattern", ",", "$", "input", ")", ")", "{", "return", "static", "::", "luhn", "(", "$", "input", ")", ";", "}", "}", "return", "false", ";", "}" ]
Validate input is a credit card number. If $types is defined, will only validate against those cards, else will validate against all. @param string $input @param string|array $types @return bool @throws \Titon\Utility\Exception\InvalidCreditCardException
[ "Validate", "input", "is", "a", "credit", "card", "number", ".", "If", "$types", "is", "defined", "will", "only", "validate", "against", "those", "cards", "else", "will", "validate", "against", "all", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L159-L203
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.date
public static function date($input) { $input = Time::toUnix($input); if (!$input) { return false; } list($m, $d, $y) = explode('/', date('m/d/Y', $input)); return checkdate($m, $d, $y); }
php
public static function date($input) { $input = Time::toUnix($input); if (!$input) { return false; } list($m, $d, $y) = explode('/', date('m/d/Y', $input)); return checkdate($m, $d, $y); }
[ "public", "static", "function", "date", "(", "$", "input", ")", "{", "$", "input", "=", "Time", "::", "toUnix", "(", "$", "input", ")", ";", "if", "(", "!", "$", "input", ")", "{", "return", "false", ";", "}", "list", "(", "$", "m", ",", "$", "d", ",", "$", "y", ")", "=", "explode", "(", "'/'", ",", "date", "(", "'m/d/Y'", ",", "$", "input", ")", ")", ";", "return", "checkdate", "(", "$", "m", ",", "$", "d", ",", "$", "y", ")", ";", "}" ]
Validate input is a real date. @uses Titon\Utility\Time @param string $input @return bool
[ "Validate", "input", "is", "a", "real", "date", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L235-L245
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.decimal
public static function decimal($input, $places = 2) { if (!$places) { $regex = '/^[-+]?[0-9]*\.{1}[0-9]+(?:[eE][-+]?[0-9]+)?$/'; } else { $regex = '/^[-+]?[0-9]*\.{1}[0-9]{' . $places . '}$/'; } return static::custom($input, $regex); }
php
public static function decimal($input, $places = 2) { if (!$places) { $regex = '/^[-+]?[0-9]*\.{1}[0-9]+(?:[eE][-+]?[0-9]+)?$/'; } else { $regex = '/^[-+]?[0-9]*\.{1}[0-9]{' . $places . '}$/'; } return static::custom($input, $regex); }
[ "public", "static", "function", "decimal", "(", "$", "input", ",", "$", "places", "=", "2", ")", "{", "if", "(", "!", "$", "places", ")", "{", "$", "regex", "=", "'/^[-+]?[0-9]*\\.{1}[0-9]+(?:[eE][-+]?[0-9]+)?$/'", ";", "}", "else", "{", "$", "regex", "=", "'/^[-+]?[0-9]*\\.{1}[0-9]{'", ".", "$", "places", ".", "'}$/'", ";", "}", "return", "static", "::", "custom", "(", "$", "input", ",", "$", "regex", ")", ";", "}" ]
Validate input is a decimal. @param string $input @param int $places @return bool
[ "Validate", "input", "is", "a", "decimal", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L254-L262
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.dimensions
public static function dimensions($input, $type, $size) { if (static::file($input)) { $input = $input['tmp_name']; } if (!file_exists($input)) { return false; } if ($file = getimagesize($input)) { $width = $file[0]; $height = $file[1]; switch ($type) { case 'width': return ($width == $size); case 'height': return ($height == $size); case 'maxWidth': return ($width <= $size); case 'maxHeight': return ($height <= $size); case 'minWidth': return ($width >= $size); case 'minHeight': return ($height >= $size); } } return false; }
php
public static function dimensions($input, $type, $size) { if (static::file($input)) { $input = $input['tmp_name']; } if (!file_exists($input)) { return false; } if ($file = getimagesize($input)) { $width = $file[0]; $height = $file[1]; switch ($type) { case 'width': return ($width == $size); case 'height': return ($height == $size); case 'maxWidth': return ($width <= $size); case 'maxHeight': return ($height <= $size); case 'minWidth': return ($width >= $size); case 'minHeight': return ($height >= $size); } } return false; }
[ "public", "static", "function", "dimensions", "(", "$", "input", ",", "$", "type", ",", "$", "size", ")", "{", "if", "(", "static", "::", "file", "(", "$", "input", ")", ")", "{", "$", "input", "=", "$", "input", "[", "'tmp_name'", "]", ";", "}", "if", "(", "!", "file_exists", "(", "$", "input", ")", ")", "{", "return", "false", ";", "}", "if", "(", "$", "file", "=", "getimagesize", "(", "$", "input", ")", ")", "{", "$", "width", "=", "$", "file", "[", "0", "]", ";", "$", "height", "=", "$", "file", "[", "1", "]", ";", "switch", "(", "$", "type", ")", "{", "case", "'width'", ":", "return", "(", "$", "width", "==", "$", "size", ")", ";", "case", "'height'", ":", "return", "(", "$", "height", "==", "$", "size", ")", ";", "case", "'maxWidth'", ":", "return", "(", "$", "width", "<=", "$", "size", ")", ";", "case", "'maxHeight'", ":", "return", "(", "$", "height", "<=", "$", "size", ")", ";", "case", "'minWidth'", ":", "return", "(", "$", "width", ">=", "$", "size", ")", ";", "case", "'minHeight'", ":", "return", "(", "$", "height", ">=", "$", "size", ")", ";", "}", "}", "return", "false", ";", "}" ]
Validate an images dimensions. @param array $input @param string $type @param int $size @return bool
[ "Validate", "an", "images", "dimensions", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L272-L296
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.email
public static function email($input, $dns = true) { $result = (bool) filter_var($input, FILTER_VALIDATE_EMAIL); if (!$result) { return false; } if ($dns) { $host = trim(mb_strstr(filter_var($input, FILTER_SANITIZE_EMAIL), '@'), '@'); if (function_exists('checkdnsrr') && checkdnsrr($host, 'MX')) { return true; } return is_array(gethostbynamel($host)); } return $result; }
php
public static function email($input, $dns = true) { $result = (bool) filter_var($input, FILTER_VALIDATE_EMAIL); if (!$result) { return false; } if ($dns) { $host = trim(mb_strstr(filter_var($input, FILTER_SANITIZE_EMAIL), '@'), '@'); if (function_exists('checkdnsrr') && checkdnsrr($host, 'MX')) { return true; } return is_array(gethostbynamel($host)); } return $result; }
[ "public", "static", "function", "email", "(", "$", "input", ",", "$", "dns", "=", "true", ")", "{", "$", "result", "=", "(", "bool", ")", "filter_var", "(", "$", "input", ",", "FILTER_VALIDATE_EMAIL", ")", ";", "if", "(", "!", "$", "result", ")", "{", "return", "false", ";", "}", "if", "(", "$", "dns", ")", "{", "$", "host", "=", "trim", "(", "mb_strstr", "(", "filter_var", "(", "$", "input", ",", "FILTER_SANITIZE_EMAIL", ")", ",", "'@'", ")", ",", "'@'", ")", ";", "if", "(", "function_exists", "(", "'checkdnsrr'", ")", "&&", "checkdnsrr", "(", "$", "host", ",", "'MX'", ")", ")", "{", "return", "true", ";", "}", "return", "is_array", "(", "gethostbynamel", "(", "$", "host", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Validate input is an email. If $dns is true, will check DNS records as well. @param string $input @param bool $dns @return bool
[ "Validate", "input", "is", "an", "email", ".", "If", "$dns", "is", "true", "will", "check", "DNS", "records", "as", "well", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L305-L323
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.ext
public static function ext($input, $extensions = array('gif', 'jpeg', 'png', 'jpg')) { if (is_array($input) && isset($input['name'])) { $input = $input['name']; } return in_array(Path::ext($input), (array) $extensions, true); }
php
public static function ext($input, $extensions = array('gif', 'jpeg', 'png', 'jpg')) { if (is_array($input) && isset($input['name'])) { $input = $input['name']; } return in_array(Path::ext($input), (array) $extensions, true); }
[ "public", "static", "function", "ext", "(", "$", "input", ",", "$", "extensions", "=", "array", "(", "'gif'", ",", "'jpeg'", ",", "'png'", ",", "'jpg'", ")", ")", "{", "if", "(", "is_array", "(", "$", "input", ")", "&&", "isset", "(", "$", "input", "[", "'name'", "]", ")", ")", "{", "$", "input", "=", "$", "input", "[", "'name'", "]", ";", "}", "return", "in_array", "(", "Path", "::", "ext", "(", "$", "input", ")", ",", "(", "array", ")", "$", "extensions", ",", "true", ")", ";", "}" ]
Validate input has an extension and is in the whitelist. @uses Titon\Utility\Loader @param string $input @param string|array $extensions @return bool
[ "Validate", "input", "has", "an", "extension", "and", "is", "in", "the", "whitelist", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L370-L376
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.luhn
public static function luhn($input) { if ($input == 0) { return false; } $sum = 0; $length = mb_strlen($input); for ($position = 1 - ($length % 2); $position < $length; $position += 2) { $sum += $input[$position]; } for ($position = ($length % 2); $position < $length; $position += 2) { $number = $input[$position] * 2; $sum += ($number < 10) ? $number : $number - 9; } return ($sum % 10 == 0); }
php
public static function luhn($input) { if ($input == 0) { return false; } $sum = 0; $length = mb_strlen($input); for ($position = 1 - ($length % 2); $position < $length; $position += 2) { $sum += $input[$position]; } for ($position = ($length % 2); $position < $length; $position += 2) { $number = $input[$position] * 2; $sum += ($number < 10) ? $number : $number - 9; } return ($sum % 10 == 0); }
[ "public", "static", "function", "luhn", "(", "$", "input", ")", "{", "if", "(", "$", "input", "==", "0", ")", "{", "return", "false", ";", "}", "$", "sum", "=", "0", ";", "$", "length", "=", "mb_strlen", "(", "$", "input", ")", ";", "for", "(", "$", "position", "=", "1", "-", "(", "$", "length", "%", "2", ")", ";", "$", "position", "<", "$", "length", ";", "$", "position", "+=", "2", ")", "{", "$", "sum", "+=", "$", "input", "[", "$", "position", "]", ";", "}", "for", "(", "$", "position", "=", "(", "$", "length", "%", "2", ")", ";", "$", "position", "<", "$", "length", ";", "$", "position", "+=", "2", ")", "{", "$", "number", "=", "$", "input", "[", "$", "position", "]", "*", "2", ";", "$", "sum", "+=", "(", "$", "number", "<", "10", ")", "?", "$", "number", ":", "$", "number", "-", "9", ";", "}", "return", "(", "$", "sum", "%", "10", "==", "0", ")", ";", "}" ]
Luhn algorithm. @param string $input @return bool @link http://en.wikipedia.org/wiki/Luhn_algorithm
[ "Luhn", "algorithm", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L440-L458
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.mimeType
public static function mimeType($input, $mimes) { if (static::file($input)) { $input = $input['tmp_name']; } if (!file_exists($input)) { return false; } $file = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_file($file, $input); finfo_close($file); return in_array($type, (array) $mimes); }
php
public static function mimeType($input, $mimes) { if (static::file($input)) { $input = $input['tmp_name']; } if (!file_exists($input)) { return false; } $file = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_file($file, $input); finfo_close($file); return in_array($type, (array) $mimes); }
[ "public", "static", "function", "mimeType", "(", "$", "input", ",", "$", "mimes", ")", "{", "if", "(", "static", "::", "file", "(", "$", "input", ")", ")", "{", "$", "input", "=", "$", "input", "[", "'tmp_name'", "]", ";", "}", "if", "(", "!", "file_exists", "(", "$", "input", ")", ")", "{", "return", "false", ";", "}", "$", "file", "=", "finfo_open", "(", "FILEINFO_MIME_TYPE", ")", ";", "$", "type", "=", "finfo_file", "(", "$", "file", ",", "$", "input", ")", ";", "finfo_close", "(", "$", "file", ")", ";", "return", "in_array", "(", "$", "type", ",", "(", "array", ")", "$", "mimes", ")", ";", "}" ]
Validate a files mime type is in the whitelist. @param string $input @param string|array $mimes @return bool
[ "Validate", "a", "files", "mime", "type", "is", "in", "the", "whitelist", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L467-L481
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.minFilesize
public static function minFilesize($input, $min) { if (static::file($input)) { $size = $input['size']; } else if (file_exists($input)) { $size = filesize($input); } else { return false; } return ($size >= Number::bytesFrom($min)); }
php
public static function minFilesize($input, $min) { if (static::file($input)) { $size = $input['size']; } else if (file_exists($input)) { $size = filesize($input); } else { return false; } return ($size >= Number::bytesFrom($min)); }
[ "public", "static", "function", "minFilesize", "(", "$", "input", ",", "$", "min", ")", "{", "if", "(", "static", "::", "file", "(", "$", "input", ")", ")", "{", "$", "size", "=", "$", "input", "[", "'size'", "]", ";", "}", "else", "if", "(", "file_exists", "(", "$", "input", ")", ")", "{", "$", "size", "=", "filesize", "(", "$", "input", ")", ";", "}", "else", "{", "return", "false", ";", "}", "return", "(", "$", "size", ">=", "Number", "::", "bytesFrom", "(", "$", "min", ")", ")", ";", "}" ]
Validate an images file size is above the minimum. @param array $input @param int $min @return bool
[ "Validate", "an", "images", "file", "size", "is", "above", "the", "minimum", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L490-L502
vpg/titon.utility
src/Titon/Utility/Validate.php
Validate.maxFilesize
public static function maxFilesize($input, $max) { if (static::file($input)) { $size = $input['size']; } else if (file_exists($input)) { $size = filesize($input); } else { return false; } return ($size <= Number::bytesFrom($max)); }
php
public static function maxFilesize($input, $max) { if (static::file($input)) { $size = $input['size']; } else if (file_exists($input)) { $size = filesize($input); } else { return false; } return ($size <= Number::bytesFrom($max)); }
[ "public", "static", "function", "maxFilesize", "(", "$", "input", ",", "$", "max", ")", "{", "if", "(", "static", "::", "file", "(", "$", "input", ")", ")", "{", "$", "size", "=", "$", "input", "[", "'size'", "]", ";", "}", "else", "if", "(", "file_exists", "(", "$", "input", ")", ")", "{", "$", "size", "=", "filesize", "(", "$", "input", ")", ";", "}", "else", "{", "return", "false", ";", "}", "return", "(", "$", "size", "<=", "Number", "::", "bytesFrom", "(", "$", "max", ")", ")", ";", "}" ]
Validate an images file size is below the maximum. @uses Titon\Utility\Number @param array $input @param int $max @return bool
[ "Validate", "an", "images", "file", "size", "is", "below", "the", "maximum", "." ]
train
https://github.com/vpg/titon.utility/blob/8a77eb9e7b8baacf41cc25487289779d8319cd3a/src/Titon/Utility/Validate.php#L546-L558
miaoxing/plugin
src/Service/CurUser.php
CurUser.login
public function login($data) { // 1. 校验用户账号密码是否符合规则 $validator = wei()->validate([ 'data' => $data, 'rules' => [ 'username' => [ 'required' => true, ], 'password' => [ 'required' => true, ], ], 'names' => [ 'username' => '帐号', 'password' => '密码', ], ]); if (!$validator->isValid()) { return ['code' => -1, 'message' => $validator->getFirstMessage()]; } // 2. 检查手机/邮箱/用户名是否存在 $user = wei()->user(); switch (true) { case wei()->isMobileCn($data['username']): $field = 'mobile'; $user->mobileVerified(); break; case wei()->isEmail($data['username']): $field = 'email'; break; default: $field = 'username'; } /** @var User $user */ $user = $user->find([$field => $data['username']]); if (!$user) { return ['code' => -2, 'message' => '用户名不存在或密码错误']; } // 3. 检查用户是否有效 if (!$user['enable']) { return ['code' => -3, 'message' => '用户未启用,无法登录']; } // 4. 验证密码是否正确 if (!$user->verifyPassword($data['password'])) { return ['code' => -4, 'message' => '用户不存在或密码错误']; } // 5. 验证通过,登录用户 return $this->loginByRecord($user); }
php
public function login($data) { // 1. 校验用户账号密码是否符合规则 $validator = wei()->validate([ 'data' => $data, 'rules' => [ 'username' => [ 'required' => true, ], 'password' => [ 'required' => true, ], ], 'names' => [ 'username' => '帐号', 'password' => '密码', ], ]); if (!$validator->isValid()) { return ['code' => -1, 'message' => $validator->getFirstMessage()]; } // 2. 检查手机/邮箱/用户名是否存在 $user = wei()->user(); switch (true) { case wei()->isMobileCn($data['username']): $field = 'mobile'; $user->mobileVerified(); break; case wei()->isEmail($data['username']): $field = 'email'; break; default: $field = 'username'; } /** @var User $user */ $user = $user->find([$field => $data['username']]); if (!$user) { return ['code' => -2, 'message' => '用户名不存在或密码错误']; } // 3. 检查用户是否有效 if (!$user['enable']) { return ['code' => -3, 'message' => '用户未启用,无法登录']; } // 4. 验证密码是否正确 if (!$user->verifyPassword($data['password'])) { return ['code' => -4, 'message' => '用户不存在或密码错误']; } // 5. 验证通过,登录用户 return $this->loginByRecord($user); }
[ "public", "function", "login", "(", "$", "data", ")", "{", "// 1. 校验用户账号密码是否符合规则", "$", "validator", "=", "wei", "(", ")", "->", "validate", "(", "[", "'data'", "=>", "$", "data", ",", "'rules'", "=>", "[", "'username'", "=>", "[", "'required'", "=>", "true", ",", "]", ",", "'password'", "=>", "[", "'required'", "=>", "true", ",", "]", ",", "]", ",", "'names'", "=>", "[", "'username'", "=>", "'帐号',", "", "'password'", "=>", "'密码',", "", "]", ",", "]", ")", ";", "if", "(", "!", "$", "validator", "->", "isValid", "(", ")", ")", "{", "return", "[", "'code'", "=>", "-", "1", ",", "'message'", "=>", "$", "validator", "->", "getFirstMessage", "(", ")", "]", ";", "}", "// 2. 检查手机/邮箱/用户名是否存在", "$", "user", "=", "wei", "(", ")", "->", "user", "(", ")", ";", "switch", "(", "true", ")", "{", "case", "wei", "(", ")", "->", "isMobileCn", "(", "$", "data", "[", "'username'", "]", ")", ":", "$", "field", "=", "'mobile'", ";", "$", "user", "->", "mobileVerified", "(", ")", ";", "break", ";", "case", "wei", "(", ")", "->", "isEmail", "(", "$", "data", "[", "'username'", "]", ")", ":", "$", "field", "=", "'email'", ";", "break", ";", "default", ":", "$", "field", "=", "'username'", ";", "}", "/** @var User $user */", "$", "user", "=", "$", "user", "->", "find", "(", "[", "$", "field", "=>", "$", "data", "[", "'username'", "]", "]", ")", ";", "if", "(", "!", "$", "user", ")", "{", "return", "[", "'code'", "=>", "-", "2", ",", "'message'", "=>", "'用户名不存在或密码错误'];", "", "", "}", "// 3. 检查用户是否有效", "if", "(", "!", "$", "user", "[", "'enable'", "]", ")", "{", "return", "[", "'code'", "=>", "-", "3", ",", "'message'", "=>", "'用户未启用,无法登录'];", "", "", "}", "// 4. 验证密码是否正确", "if", "(", "!", "$", "user", "->", "verifyPassword", "(", "$", "data", "[", "'password'", "]", ")", ")", "{", "return", "[", "'code'", "=>", "-", "4", ",", "'message'", "=>", "'用户不存在或密码错误'];", "", "", "}", "// 5. 验证通过,登录用户", "return", "$", "this", "->", "loginByRecord", "(", "$", "user", ")", ";", "}" ]
根据用户账号密码,登录用户 @param mixed $data @return array
[ "根据用户账号密码", "登录用户" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/CurUser.php#L33-L90
miaoxing/plugin
src/Service/CurUser.php
CurUser.loginById
public function loginById($id) { /** @var User $user */ $user = wei()->user()->findById($id); if (!$user) { return ['code' => -1, 'message' => '用户不存在']; } else { return $this->loginByRecord($user); } }
php
public function loginById($id) { /** @var User $user */ $user = wei()->user()->findById($id); if (!$user) { return ['code' => -1, 'message' => '用户不存在']; } else { return $this->loginByRecord($user); } }
[ "public", "function", "loginById", "(", "$", "id", ")", "{", "/** @var User $user */", "$", "user", "=", "wei", "(", ")", "->", "user", "(", ")", "->", "findById", "(", "$", "id", ")", ";", "if", "(", "!", "$", "user", ")", "{", "return", "[", "'code'", "=>", "-", "1", ",", "'message'", "=>", "'用户不存在'];", "", "", "}", "else", "{", "return", "$", "this", "->", "loginByRecord", "(", "$", "user", ")", ";", "}", "}" ]
根据用户ID直接登录用户 @param int $id @return array
[ "根据用户ID直接登录用户" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/CurUser.php#L98-L107
miaoxing/plugin
src/Service/CurUser.php
CurUser.loginBy
public function loginBy($conditions, $data = []) { $user = wei()->user()->findOrCreate($conditions, $data); $this->loginByRecord($user); return $this; }
php
public function loginBy($conditions, $data = []) { $user = wei()->user()->findOrCreate($conditions, $data); $this->loginByRecord($user); return $this; }
[ "public", "function", "loginBy", "(", "$", "conditions", ",", "$", "data", "=", "[", "]", ")", "{", "$", "user", "=", "wei", "(", ")", "->", "user", "(", ")", "->", "findOrCreate", "(", "$", "conditions", ",", "$", "data", ")", ";", "$", "this", "->", "loginByRecord", "(", "$", "user", ")", ";", "return", "$", "this", ";", "}" ]
根据条件查找或创建用户,并登录 @param mixed $conditions @param array $data @return $this
[ "根据条件查找或创建用户", "并登录" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/CurUser.php#L116-L122
miaoxing/plugin
src/Service/CurUser.php
CurUser.loginByRecord
public function loginByRecord(User $user) { $this->loadRecordData($user); $this->session['user'] = $user->toArray($this->sessionFields); wei()->event->trigger('userLogin', [$user]); return ['code' => 1, 'message' => '登录成功']; }
php
public function loginByRecord(User $user) { $this->loadRecordData($user); $this->session['user'] = $user->toArray($this->sessionFields); wei()->event->trigger('userLogin', [$user]); return ['code' => 1, 'message' => '登录成功']; }
[ "public", "function", "loginByRecord", "(", "User", "$", "user", ")", "{", "$", "this", "->", "loadRecordData", "(", "$", "user", ")", ";", "$", "this", "->", "session", "[", "'user'", "]", "=", "$", "user", "->", "toArray", "(", "$", "this", "->", "sessionFields", ")", ";", "wei", "(", ")", "->", "event", "->", "trigger", "(", "'userLogin'", ",", "[", "$", "user", "]", ")", ";", "return", "[", "'code'", "=>", "1", ",", "'message'", "=>", "'登录成功'];", "", "", "}" ]
根据用户对象登录用户 @param User $user @return array
[ "根据用户对象登录用户" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/CurUser.php#L130-L137
miaoxing/plugin
src/Service/CurUser.php
CurUser.refresh
public function refresh(User $user) { if ($user['id'] == $this->session['user']['id']) { $this->loginByRecord($user); } return $this; }
php
public function refresh(User $user) { if ($user['id'] == $this->session['user']['id']) { $this->loginByRecord($user); } return $this; }
[ "public", "function", "refresh", "(", "User", "$", "user", ")", "{", "if", "(", "$", "user", "[", "'id'", "]", "==", "$", "this", "->", "session", "[", "'user'", "]", "[", "'id'", "]", ")", "{", "$", "this", "->", "loginByRecord", "(", "$", "user", ")", ";", "}", "return", "$", "this", ";", "}" ]
当用户信息更改后,可以主动调用该方法,刷新会话中的数据 @param User $user @return $this
[ "当用户信息更改后", "可以主动调用该方法", "刷新会话中的数据" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/CurUser.php#L168-L175
miaoxing/plugin
src/Service/CurUser.php
CurUser.save
public function save($data = []) { // 确保是更新操作,同时有ID作为更新条件 $this->isNew = false; $this['id'] = $this->session['user']['id']; return parent::save($data); }
php
public function save($data = []) { // 确保是更新操作,同时有ID作为更新条件 $this->isNew = false; $this['id'] = $this->session['user']['id']; return parent::save($data); }
[ "public", "function", "save", "(", "$", "data", "=", "[", "]", ")", "{", "// 确保是更新操作,同时有ID作为更新条件", "$", "this", "->", "isNew", "=", "false", ";", "$", "this", "[", "'id'", "]", "=", "$", "this", "->", "session", "[", "'user'", "]", "[", "'id'", "]", ";", "return", "parent", "::", "save", "(", "$", "data", ")", ";", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/CurUser.php#L190-L197
miaoxing/plugin
src/Service/CurUser.php
CurUser.get
public function get($name) { // 未加载数据,已登录,session中存在需要的key if (!$this->isLoaded() && isset($this->session['user'][$name])) { return $this->session['user'][$name]; } else { $this->loadDbUser(); return parent::get($name); } }
php
public function get($name) { // 未加载数据,已登录,session中存在需要的key if (!$this->isLoaded() && isset($this->session['user'][$name])) { return $this->session['user'][$name]; } else { $this->loadDbUser(); return parent::get($name); } }
[ "public", "function", "get", "(", "$", "name", ")", "{", "// 未加载数据,已登录,session中存在需要的key", "if", "(", "!", "$", "this", "->", "isLoaded", "(", ")", "&&", "isset", "(", "$", "this", "->", "session", "[", "'user'", "]", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "session", "[", "'user'", "]", "[", "$", "name", "]", ";", "}", "else", "{", "$", "this", "->", "loadDbUser", "(", ")", ";", "return", "parent", "::", "get", "(", "$", "name", ")", ";", "}", "}" ]
Record: 获取用户资料,优先从session中获取 {@inheritdoc}
[ "Record", ":", "获取用户资料", "优先从session中获取" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/CurUser.php#L204-L214
miaoxing/plugin
src/Service/CurUser.php
CurUser.loadDbUser
protected function loadDbUser() { if ($this->isLoaded() || !$this->isLogin()) { return; } $id = $this['id']; $user = wei()->user() ->cache() ->tags(false) ->setCacheKey($this->getRecordCacheKey($id)) ->findOrInitById($id); $this->loadRecordData($user); }
php
protected function loadDbUser() { if ($this->isLoaded() || !$this->isLogin()) { return; } $id = $this['id']; $user = wei()->user() ->cache() ->tags(false) ->setCacheKey($this->getRecordCacheKey($id)) ->findOrInitById($id); $this->loadRecordData($user); }
[ "protected", "function", "loadDbUser", "(", ")", "{", "if", "(", "$", "this", "->", "isLoaded", "(", ")", "||", "!", "$", "this", "->", "isLogin", "(", ")", ")", "{", "return", ";", "}", "$", "id", "=", "$", "this", "[", "'id'", "]", ";", "$", "user", "=", "wei", "(", ")", "->", "user", "(", ")", "->", "cache", "(", ")", "->", "tags", "(", "false", ")", "->", "setCacheKey", "(", "$", "this", "->", "getRecordCacheKey", "(", "$", "id", ")", ")", "->", "findOrInitById", "(", "$", "id", ")", ";", "$", "this", "->", "loadRecordData", "(", "$", "user", ")", ";", "}" ]
从数据库中查找用户加载到当前记录中
[ "从数据库中查找用户加载到当前记录中" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/CurUser.php#L219-L233
miaoxing/plugin
src/Service/CurUser.php
CurUser.loadRecordData
protected function loadRecordData(User $user) { $this->setData($user->getData()); // 清空更改状态 $this->isChanged = false; $this->changedData = []; }
php
protected function loadRecordData(User $user) { $this->setData($user->getData()); // 清空更改状态 $this->isChanged = false; $this->changedData = []; }
[ "protected", "function", "loadRecordData", "(", "User", "$", "user", ")", "{", "$", "this", "->", "setData", "(", "$", "user", "->", "getData", "(", ")", ")", ";", "// 清空更改状态", "$", "this", "->", "isChanged", "=", "false", ";", "$", "this", "->", "changedData", "=", "[", "]", ";", "}" ]
加载外部记录的数据 @param User $user
[ "加载外部记录的数据" ]
train
https://github.com/miaoxing/plugin/blob/f287a1e6c97abba6f06906255b8c26e8ab0afe61/src/Service/CurUser.php#L240-L247
mtils/file-db
src/FileDB/Model/DependencyFinderChain.php
DependencyFinderChain.find
public function find(FileInterface $file, array $filters=[], $sort='title') { if (!$result = $this->all($file)) { return []; } return $result; }
php
public function find(FileInterface $file, array $filters=[], $sort='title') { if (!$result = $this->all($file)) { return []; } return $result; }
[ "public", "function", "find", "(", "FileInterface", "$", "file", ",", "array", "$", "filters", "=", "[", "]", ",", "$", "sort", "=", "'title'", ")", "{", "if", "(", "!", "$", "result", "=", "$", "this", "->", "all", "(", "$", "file", ")", ")", "{", "return", "[", "]", ";", "}", "return", "$", "result", ";", "}" ]
Lists all dependencies for file $file and filters, sorts and limit the result @param \FileDB\Model\FileInterface $file @param array $filters (optional) @param string $sort id|title|category (default:title) @return \Traversable of \FileDB\Contracts\FileSystem\Dependency @see \FileDB\Contracts\FileSystem\Dependency
[ "Lists", "all", "dependencies", "for", "file", "$file", "and", "filters", "sorts", "and", "limit", "the", "result" ]
train
https://github.com/mtils/file-db/blob/270ebc26b0fa3d2c996ca8861507fa63d2db6814/src/FileDB/Model/DependencyFinderChain.php#L34-L42
dogyford/WebChatApi
src/Api/WeiXinMiniProgramApi.php
WeiXinMiniProgramApi.code2session
public function code2session($code){ if (empty($code)){ if ($this->business_interface) $this->business_interface->log('code2session code exception'); return false; } $url = self::API_CODE2SESSION."appid={$this->config['app_id']}&secret={$this->config['app_secret']}&js_code={$code}&grant_type=authorization_code"; return $this->curl($url); }
php
public function code2session($code){ if (empty($code)){ if ($this->business_interface) $this->business_interface->log('code2session code exception'); return false; } $url = self::API_CODE2SESSION."appid={$this->config['app_id']}&secret={$this->config['app_secret']}&js_code={$code}&grant_type=authorization_code"; return $this->curl($url); }
[ "public", "function", "code2session", "(", "$", "code", ")", "{", "if", "(", "empty", "(", "$", "code", ")", ")", "{", "if", "(", "$", "this", "->", "business_interface", ")", "$", "this", "->", "business_interface", "->", "log", "(", "'code2session code exception'", ")", ";", "return", "false", ";", "}", "$", "url", "=", "self", "::", "API_CODE2SESSION", ".", "\"appid={$this->config['app_id']}&secret={$this->config['app_secret']}&js_code={$code}&grant_type=authorization_code\"", ";", "return", "$", "this", "->", "curl", "(", "$", "url", ")", ";", "}" ]
code换取 @param $code @return bool|mixed
[ "code换取" ]
train
https://github.com/dogyford/WebChatApi/blob/31b570e429bce459bf031ecb5c3e3bbd9605ef33/src/Api/WeiXinMiniProgramApi.php#L27-L34
itkg/core
src/Itkg/Core/Command/DatabaseUpdate/Setup.php
Setup.createMigration
public function createMigration($script, $rollbackScript) { $this->releaseChecker->checkScript($script, $rollbackScript); if ($this->rollbackedFirst) { /* When rollback is needed first we invert script & rollback script */ list($rollbackScript, $script) = array($script, $rollbackScript); } $this->migrations[] = $this->migrationFactory->createMigration( $this->loader->load($script)->getQueries(), $this->loader->load($rollbackScript)->getQueries() ); return $this; }
php
public function createMigration($script, $rollbackScript) { $this->releaseChecker->checkScript($script, $rollbackScript); if ($this->rollbackedFirst) { /* When rollback is needed first we invert script & rollback script */ list($rollbackScript, $script) = array($script, $rollbackScript); } $this->migrations[] = $this->migrationFactory->createMigration( $this->loader->load($script)->getQueries(), $this->loader->load($rollbackScript)->getQueries() ); return $this; }
[ "public", "function", "createMigration", "(", "$", "script", ",", "$", "rollbackScript", ")", "{", "$", "this", "->", "releaseChecker", "->", "checkScript", "(", "$", "script", ",", "$", "rollbackScript", ")", ";", "if", "(", "$", "this", "->", "rollbackedFirst", ")", "{", "/* When rollback is needed first we invert script & rollback script */", "list", "(", "$", "rollbackScript", ",", "$", "script", ")", "=", "array", "(", "$", "script", ",", "$", "rollbackScript", ")", ";", "}", "$", "this", "->", "migrations", "[", "]", "=", "$", "this", "->", "migrationFactory", "->", "createMigration", "(", "$", "this", "->", "loader", "->", "load", "(", "$", "script", ")", "->", "getQueries", "(", ")", ",", "$", "this", "->", "loader", "->", "load", "(", "$", "rollbackScript", ")", "->", "getQueries", "(", ")", ")", ";", "return", "$", "this", ";", "}" ]
Create a migration from SQL script & rollback script @param $script @param $rollbackScript @throws \InvalidArgumentException @return $this
[ "Create", "a", "migration", "from", "SQL", "script", "&", "rollback", "script" ]
train
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Command/DatabaseUpdate/Setup.php#L129-L144
itkg/core
src/Itkg/Core/Command/DatabaseUpdate/Setup.php
Setup.createMigrations
private function createMigrations() { $scripts = $this->locator->findScripts(); $rollbacks = $this->locator->findRollbackScripts(); $this->releaseChecker->checkScripts($scripts, $rollbacks); foreach ($scripts as $k => $script) { $this->createMigration($script, $rollbacks[$k]); } }
php
private function createMigrations() { $scripts = $this->locator->findScripts(); $rollbacks = $this->locator->findRollbackScripts(); $this->releaseChecker->checkScripts($scripts, $rollbacks); foreach ($scripts as $k => $script) { $this->createMigration($script, $rollbacks[$k]); } }
[ "private", "function", "createMigrations", "(", ")", "{", "$", "scripts", "=", "$", "this", "->", "locator", "->", "findScripts", "(", ")", ";", "$", "rollbacks", "=", "$", "this", "->", "locator", "->", "findRollbackScripts", "(", ")", ";", "$", "this", "->", "releaseChecker", "->", "checkScripts", "(", "$", "scripts", ",", "$", "rollbacks", ")", ";", "foreach", "(", "$", "scripts", "as", "$", "k", "=>", "$", "script", ")", "{", "$", "this", "->", "createMigration", "(", "$", "script", ",", "$", "rollbacks", "[", "$", "k", "]", ")", ";", "}", "}" ]
Create migrations from scripts & rollback files @return void @throws \RuntimeException @throws \LogicException
[ "Create", "migrations", "from", "scripts", "&", "rollback", "files" ]
train
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Command/DatabaseUpdate/Setup.php#L154-L164
itkg/core
src/Itkg/Core/Command/DatabaseUpdate/Setup.php
Setup.run
public function run() { $this->createMigrations(); foreach ($this->migrations as $migration) { $this->runner->run($migration, $this->executeQueries, $this->forcedRollback); } // After run, we add decorated queries return $this->decorator->decorateAll($this->runner->getPlayedQueries()); }
php
public function run() { $this->createMigrations(); foreach ($this->migrations as $migration) { $this->runner->run($migration, $this->executeQueries, $this->forcedRollback); } // After run, we add decorated queries return $this->decorator->decorateAll($this->runner->getPlayedQueries()); }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "createMigrations", "(", ")", ";", "foreach", "(", "$", "this", "->", "migrations", "as", "$", "migration", ")", "{", "$", "this", "->", "runner", "->", "run", "(", "$", "migration", ",", "$", "this", "->", "executeQueries", ",", "$", "this", "->", "forcedRollback", ")", ";", "}", "// After run, we add decorated queries", "return", "$", "this", "->", "decorator", "->", "decorateAll", "(", "$", "this", "->", "runner", "->", "getPlayedQueries", "(", ")", ")", ";", "}" ]
Run migrations
[ "Run", "migrations" ]
train
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Command/DatabaseUpdate/Setup.php#L169-L180
codemojo-dr/startkit-php-sdk
src/CodeMojo/Client/Services/MetaService.php
MetaService.get
public function get($key){ $url = $this->authenticationService->getServerEndPoint() . Endpoints::VERSION . Endpoints::BASE_META . Endpoints::META; $result = $this->authenticationService->getTransport()->fetch($url,array("key"=>$key)); if($result["code"] == APIResponse::RESPONSE_SUCCESS){ $unwrapped = @json_decode($result['results']['value']); $value = $unwrapped === null ? $result['results']['value'] : $unwrapped; return array("value" => $value, "validity" => $result['results']['validity']); }else{ return null; } }
php
public function get($key){ $url = $this->authenticationService->getServerEndPoint() . Endpoints::VERSION . Endpoints::BASE_META . Endpoints::META; $result = $this->authenticationService->getTransport()->fetch($url,array("key"=>$key)); if($result["code"] == APIResponse::RESPONSE_SUCCESS){ $unwrapped = @json_decode($result['results']['value']); $value = $unwrapped === null ? $result['results']['value'] : $unwrapped; return array("value" => $value, "validity" => $result['results']['validity']); }else{ return null; } }
[ "public", "function", "get", "(", "$", "key", ")", "{", "$", "url", "=", "$", "this", "->", "authenticationService", "->", "getServerEndPoint", "(", ")", ".", "Endpoints", "::", "VERSION", ".", "Endpoints", "::", "BASE_META", ".", "Endpoints", "::", "META", ";", "$", "result", "=", "$", "this", "->", "authenticationService", "->", "getTransport", "(", ")", "->", "fetch", "(", "$", "url", ",", "array", "(", "\"key\"", "=>", "$", "key", ")", ")", ";", "if", "(", "$", "result", "[", "\"code\"", "]", "==", "APIResponse", "::", "RESPONSE_SUCCESS", ")", "{", "$", "unwrapped", "=", "@", "json_decode", "(", "$", "result", "[", "'results'", "]", "[", "'value'", "]", ")", ";", "$", "value", "=", "$", "unwrapped", "===", "null", "?", "$", "result", "[", "'results'", "]", "[", "'value'", "]", ":", "$", "unwrapped", ";", "return", "array", "(", "\"value\"", "=>", "$", "value", ",", "\"validity\"", "=>", "$", "result", "[", "'results'", "]", "[", "'validity'", "]", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Gets the stored meta data for the key provided @param $key @return array
[ "Gets", "the", "stored", "meta", "data", "for", "the", "key", "provided" ]
train
https://github.com/codemojo-dr/startkit-php-sdk/blob/cd2227e1a221be2cd75dc96d1c9e0acfda936fb3/src/CodeMojo/Client/Services/MetaService.php#L35-L47
codemojo-dr/startkit-php-sdk
src/CodeMojo/Client/Services/MetaService.php
MetaService.add
public function add($key, $value, $valid_for_minutes = null){ if(is_object($value) || is_array($value)){ $value = json_encode($value); } $url = $this->authenticationService->getServerEndPoint() . Endpoints::VERSION . Endpoints::BASE_META . Endpoints::META; $result = $this->authenticationService->getTransport()->fetch($url,array("key"=>$key,"value"=>$value,"validity"=>$valid_for_minutes),'PUT',array(),0); if($result["code"] == APIResponse::RESPONSE_SUCCESS){ return true; }else{ return false; } }
php
public function add($key, $value, $valid_for_minutes = null){ if(is_object($value) || is_array($value)){ $value = json_encode($value); } $url = $this->authenticationService->getServerEndPoint() . Endpoints::VERSION . Endpoints::BASE_META . Endpoints::META; $result = $this->authenticationService->getTransport()->fetch($url,array("key"=>$key,"value"=>$value,"validity"=>$valid_for_minutes),'PUT',array(),0); if($result["code"] == APIResponse::RESPONSE_SUCCESS){ return true; }else{ return false; } }
[ "public", "function", "add", "(", "$", "key", ",", "$", "value", ",", "$", "valid_for_minutes", "=", "null", ")", "{", "if", "(", "is_object", "(", "$", "value", ")", "||", "is_array", "(", "$", "value", ")", ")", "{", "$", "value", "=", "json_encode", "(", "$", "value", ")", ";", "}", "$", "url", "=", "$", "this", "->", "authenticationService", "->", "getServerEndPoint", "(", ")", ".", "Endpoints", "::", "VERSION", ".", "Endpoints", "::", "BASE_META", ".", "Endpoints", "::", "META", ";", "$", "result", "=", "$", "this", "->", "authenticationService", "->", "getTransport", "(", ")", "->", "fetch", "(", "$", "url", ",", "array", "(", "\"key\"", "=>", "$", "key", ",", "\"value\"", "=>", "$", "value", ",", "\"validity\"", "=>", "$", "valid_for_minutes", ")", ",", "'PUT'", ",", "array", "(", ")", ",", "0", ")", ";", "if", "(", "$", "result", "[", "\"code\"", "]", "==", "APIResponse", "::", "RESPONSE_SUCCESS", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Adds or Updates meta data for the key provided @param $key @param $value @return bool
[ "Adds", "or", "Updates", "meta", "data", "for", "the", "key", "provided" ]
train
https://github.com/codemojo-dr/startkit-php-sdk/blob/cd2227e1a221be2cd75dc96d1c9e0acfda936fb3/src/CodeMojo/Client/Services/MetaService.php#L55-L69
codemojo-dr/startkit-php-sdk
src/CodeMojo/Client/Services/MetaService.php
MetaService.delete
public function delete($key){ $url = $this->authenticationService->getServerEndPoint() . Endpoints::VERSION . Endpoints::BASE_META . Endpoints::META; $result = $this->authenticationService->getTransport()->fetch($url,array("key"=>$key),'DELETE',array(),0); return $result["code"] == APIResponse::RESPONSE_SUCCESS; }
php
public function delete($key){ $url = $this->authenticationService->getServerEndPoint() . Endpoints::VERSION . Endpoints::BASE_META . Endpoints::META; $result = $this->authenticationService->getTransport()->fetch($url,array("key"=>$key),'DELETE',array(),0); return $result["code"] == APIResponse::RESPONSE_SUCCESS; }
[ "public", "function", "delete", "(", "$", "key", ")", "{", "$", "url", "=", "$", "this", "->", "authenticationService", "->", "getServerEndPoint", "(", ")", ".", "Endpoints", "::", "VERSION", ".", "Endpoints", "::", "BASE_META", ".", "Endpoints", "::", "META", ";", "$", "result", "=", "$", "this", "->", "authenticationService", "->", "getTransport", "(", ")", "->", "fetch", "(", "$", "url", ",", "array", "(", "\"key\"", "=>", "$", "key", ")", ",", "'DELETE'", ",", "array", "(", ")", ",", "0", ")", ";", "return", "$", "result", "[", "\"code\"", "]", "==", "APIResponse", "::", "RESPONSE_SUCCESS", ";", "}" ]
Deletes the stored meta data for the key provided @param $key @return bool
[ "Deletes", "the", "stored", "meta", "data", "for", "the", "key", "provided" ]
train
https://github.com/codemojo-dr/startkit-php-sdk/blob/cd2227e1a221be2cd75dc96d1c9e0acfda936fb3/src/CodeMojo/Client/Services/MetaService.php#L86-L92
spress/spress-core
Spress.php
Spress.parse
public function parse() { $attributes = $this['spress.config.values']; $spressAttributes = $this->getSpressAttributes(); $result = $this['spress.cms.contentManager']->parseSite( $attributes, $spressAttributes, $attributes['drafts'], $attributes['safe'], $attributes['timezone']); return $result; }
php
public function parse() { $attributes = $this['spress.config.values']; $spressAttributes = $this->getSpressAttributes(); $result = $this['spress.cms.contentManager']->parseSite( $attributes, $spressAttributes, $attributes['drafts'], $attributes['safe'], $attributes['timezone']); return $result; }
[ "public", "function", "parse", "(", ")", "{", "$", "attributes", "=", "$", "this", "[", "'spress.config.values'", "]", ";", "$", "spressAttributes", "=", "$", "this", "->", "getSpressAttributes", "(", ")", ";", "$", "result", "=", "$", "this", "[", "'spress.cms.contentManager'", "]", "->", "parseSite", "(", "$", "attributes", ",", "$", "spressAttributes", ",", "$", "attributes", "[", "'drafts'", "]", ",", "$", "attributes", "[", "'safe'", "]", ",", "$", "attributes", "[", "'timezone'", "]", ")", ";", "return", "$", "result", ";", "}" ]
Parse a site. Example: $spress['spress.config.site_dir'] = '/my-site-folder'; $spress['spress.config.drafts'] = true; $spress['spress.config.safe'] = false; $spress['spress.config.timezone'] = 'UTC'; $spress['spress.config.url'] = 'http://your-domain.local:4000'; $spress->parse(); @return \Yosymfony\Spress\Core\DataSource\ItemInterface[] Items of the site
[ "Parse", "a", "site", "." ]
train
https://github.com/spress/spress-core/blob/a61008c4cde3ba990e7faa164462171b019a60bf/Spress.php#L311-L324
cmsgears/module-sns-connect
common/config/LinkedinProperties.php
LinkedinProperties.getInstance
public static function getInstance() { if( !isset( self::$instance ) ) { self::$instance = new LinkedinProperties(); self::$instance->init( SnsConnectGlobal::CONFIG_SNS_LINKEDIN ); } return self::$instance; }
php
public static function getInstance() { if( !isset( self::$instance ) ) { self::$instance = new LinkedinProperties(); self::$instance->init( SnsConnectGlobal::CONFIG_SNS_LINKEDIN ); } return self::$instance; }
[ "public", "static", "function", "getInstance", "(", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "instance", ")", ")", "{", "self", "::", "$", "instance", "=", "new", "LinkedinProperties", "(", ")", ";", "self", "::", "$", "instance", "->", "init", "(", "SnsConnectGlobal", "::", "CONFIG_SNS_LINKEDIN", ")", ";", "}", "return", "self", "::", "$", "instance", ";", "}" ]
Return Singleton instance.
[ "Return", "Singleton", "instance", "." ]
train
https://github.com/cmsgears/module-sns-connect/blob/753ee4157d41c81a701689624f4c44760a6cada3/common/config/LinkedinProperties.php#L52-L62
Wedeto/DB
src/Schema/Schema.php
Schema.loadCache
public function loadCache() { if (empty($this->name)) throw new DBException("Please provide a name for the schema when using the cache"); $cachemgr = CacheManager::getInstance(); $this->tables = $cachemgr->getCache('dbschema_' . $this->name); }
php
public function loadCache() { if (empty($this->name)) throw new DBException("Please provide a name for the schema when using the cache"); $cachemgr = CacheManager::getInstance(); $this->tables = $cachemgr->getCache('dbschema_' . $this->name); }
[ "public", "function", "loadCache", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "name", ")", ")", "throw", "new", "DBException", "(", "\"Please provide a name for the schema when using the cache\"", ")", ";", "$", "cachemgr", "=", "CacheManager", "::", "getInstance", "(", ")", ";", "$", "this", "->", "tables", "=", "$", "cachemgr", "->", "getCache", "(", "'dbschema_'", ".", "$", "this", "->", "name", ")", ";", "}" ]
Load the cache containing table definitions
[ "Load", "the", "cache", "containing", "table", "definitions" ]
train
https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Schema/Schema.php#L78-L85
Wedeto/DB
src/Schema/Schema.php
Schema.getTable
public function getTable($table_name) { if (!$this->tables->has('tables', $table_name)) { if ($this->db !== null) { $table = $this->db->loadTable($table_name); $this->tables->set('tables', $table_name, $table); } else throw new DBException("Table $table not ofund"); } return $this->tables->get('tables', $table_name); }
php
public function getTable($table_name) { if (!$this->tables->has('tables', $table_name)) { if ($this->db !== null) { $table = $this->db->loadTable($table_name); $this->tables->set('tables', $table_name, $table); } else throw new DBException("Table $table not ofund"); } return $this->tables->get('tables', $table_name); }
[ "public", "function", "getTable", "(", "$", "table_name", ")", "{", "if", "(", "!", "$", "this", "->", "tables", "->", "has", "(", "'tables'", ",", "$", "table_name", ")", ")", "{", "if", "(", "$", "this", "->", "db", "!==", "null", ")", "{", "$", "table", "=", "$", "this", "->", "db", "->", "loadTable", "(", "$", "table_name", ")", ";", "$", "this", "->", "tables", "->", "set", "(", "'tables'", ",", "$", "table_name", ",", "$", "table", ")", ";", "}", "else", "throw", "new", "DBException", "(", "\"Table $table not ofund\"", ")", ";", "}", "return", "$", "this", "->", "tables", "->", "get", "(", "'tables'", ",", "$", "table_name", ")", ";", "}" ]
Get a table definition from the schema
[ "Get", "a", "table", "definition", "from", "the", "schema" ]
train
https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Schema/Schema.php#L108-L122
Wedeto/DB
src/Schema/Schema.php
Schema.putTable
public function putTable(Table $table) { $this->tables->set('tables', $table->getName(), $table); return $this; }
php
public function putTable(Table $table) { $this->tables->set('tables', $table->getName(), $table); return $this; }
[ "public", "function", "putTable", "(", "Table", "$", "table", ")", "{", "$", "this", "->", "tables", "->", "set", "(", "'tables'", ",", "$", "table", "->", "getName", "(", ")", ",", "$", "table", ")", ";", "return", "$", "this", ";", "}" ]
Add a table to the schema @return Wedeto\DB\Schema\Schema Provides fluent interface
[ "Add", "a", "table", "to", "the", "schema" ]
train
https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Schema/Schema.php#L129-L133
Wedeto/DB
src/Schema/Schema.php
Schema.removeTable
public function removeTable($table) { if ($table instanceof Table) $table = $table->getName(); $this->tables->set('tables', $table, null); return $this; }
php
public function removeTable($table) { if ($table instanceof Table) $table = $table->getName(); $this->tables->set('tables', $table, null); return $this; }
[ "public", "function", "removeTable", "(", "$", "table", ")", "{", "if", "(", "$", "table", "instanceof", "Table", ")", "$", "table", "=", "$", "table", "->", "getName", "(", ")", ";", "$", "this", "->", "tables", "->", "set", "(", "'tables'", ",", "$", "table", ",", "null", ")", ";", "return", "$", "this", ";", "}" ]
Remove a schema from the table definition @param string|Table The table to remove @return Wedeto\DB\Schema\Schema Provides fluent interface
[ "Remove", "a", "schema", "from", "the", "table", "definition" ]
train
https://github.com/Wedeto/DB/blob/715f8f2e3ae6b53c511c40b620921cb9c87e6f62/src/Schema/Schema.php#L140-L146
phata/widgetfy
src/Theme.php
Theme.stringTrim
public static function stringTrim(string $string, int $length): string { if ($length<16) return $string; if (strlen($string)>$length) { $str_head = substr($string, 0, $length-10); $str_tail = substr($string, -7, 7); return $str_head.'...'.$str_tail; } return $string; }
php
public static function stringTrim(string $string, int $length): string { if ($length<16) return $string; if (strlen($string)>$length) { $str_head = substr($string, 0, $length-10); $str_tail = substr($string, -7, 7); return $str_head.'...'.$str_tail; } return $string; }
[ "public", "static", "function", "stringTrim", "(", "string", "$", "string", ",", "int", "$", "length", ")", ":", "string", "{", "if", "(", "$", "length", "<", "16", ")", "return", "$", "string", ";", "if", "(", "strlen", "(", "$", "string", ")", ">", "$", "length", ")", "{", "$", "str_head", "=", "substr", "(", "$", "string", ",", "0", ",", "$", "length", "-", "10", ")", ";", "$", "str_tail", "=", "substr", "(", "$", "string", ",", "-", "7", ",", "7", ")", ";", "return", "$", "str_head", ".", "'...'", ".", "$", "str_tail", ";", "}", "return", "$", "string", ";", "}" ]
Helper function to make a non-unicode string shortter @param string $string The string to be trimmed @param int $length The targeted trimed length @return string trimmed string
[ "Helper", "function", "to", "make", "a", "non", "-", "unicode", "string", "shortter" ]
train
https://github.com/phata/widgetfy/blob/00102c35ec5267b42c627f1e34b8e64a7dd3590c/src/Theme.php#L65-L74
phata/widgetfy
src/Theme.php
Theme.renderBlockAttrs
public static function renderBlockAttrs(array $embed): string { // attributes to be rendered $classes = array(); $styles = array(); // shortcuts $d = &$embed['dimension']; // determine classes $classes[] = 'videoblock'; if ($d->dynamic) { $classes[] = 'videoblock-dynamic'; } // determine inline CSS style(s) // if scale model is no-scale, allow to "force dynamic" // by setting "dynamic" to TRUE if ($d->dynamic) { $styles[] = 'max-width:'.$d->width.'px'; } else { $styles[] = 'width: '.$d->width.'px'; } // render the attributes $class = implode(' ', $classes); $style = implode('; ', $styles) . (!empty($styles) ? ';' : ''); return 'class="'.$class.'" style="'.$style.'"'; }
php
public static function renderBlockAttrs(array $embed): string { // attributes to be rendered $classes = array(); $styles = array(); // shortcuts $d = &$embed['dimension']; // determine classes $classes[] = 'videoblock'; if ($d->dynamic) { $classes[] = 'videoblock-dynamic'; } // determine inline CSS style(s) // if scale model is no-scale, allow to "force dynamic" // by setting "dynamic" to TRUE if ($d->dynamic) { $styles[] = 'max-width:'.$d->width.'px'; } else { $styles[] = 'width: '.$d->width.'px'; } // render the attributes $class = implode(' ', $classes); $style = implode('; ', $styles) . (!empty($styles) ? ';' : ''); return 'class="'.$class.'" style="'.$style.'"'; }
[ "public", "static", "function", "renderBlockAttrs", "(", "array", "$", "embed", ")", ":", "string", "{", "// attributes to be rendered", "$", "classes", "=", "array", "(", ")", ";", "$", "styles", "=", "array", "(", ")", ";", "// shortcuts", "$", "d", "=", "&", "$", "embed", "[", "'dimension'", "]", ";", "// determine classes", "$", "classes", "[", "]", "=", "'videoblock'", ";", "if", "(", "$", "d", "->", "dynamic", ")", "{", "$", "classes", "[", "]", "=", "'videoblock-dynamic'", ";", "}", "// determine inline CSS style(s)", "// if scale model is no-scale, allow to \"force dynamic\"", "// by setting \"dynamic\" to TRUE", "if", "(", "$", "d", "->", "dynamic", ")", "{", "$", "styles", "[", "]", "=", "'max-width:'", ".", "$", "d", "->", "width", ".", "'px'", ";", "}", "else", "{", "$", "styles", "[", "]", "=", "'width: '", ".", "$", "d", "->", "width", ".", "'px'", ";", "}", "// render the attributes", "$", "class", "=", "implode", "(", "' '", ",", "$", "classes", ")", ";", "$", "style", "=", "implode", "(", "'; '", ",", "$", "styles", ")", ".", "(", "!", "empty", "(", "$", "styles", ")", "?", "';'", ":", "''", ")", ";", "return", "'class=\"'", ".", "$", "class", ".", "'\" style=\"'", ".", "$", "style", ".", "'\"'", ";", "}" ]
Helper funcion to template. Render attributes for .videoblock @param array $embed embed definition @return string HTTP attributes
[ "Helper", "funcion", "to", "template", ".", "Render", "attributes", "for", ".", "videoblock" ]
train
https://github.com/phata/widgetfy/blob/00102c35ec5267b42c627f1e34b8e64a7dd3590c/src/Theme.php#L82-L106
phata/widgetfy
src/Theme.php
Theme.renderWrapperAttrs
public static function renderWrapperAttrs(array $embed): string { // attributes to be rendered $classes = array(); $styles = array(); // shortcuts $d = &$embed['dimension']; // determine classes $classes[] = 'video-wrapper'; if ($d->dynamic) { $classes[] = 'wrap-'.$d->scale_model; } // determine inline CSS style(s) if ($d->dynamic && ($d->scale_model == 'scale-width-height')) { $styles[] = 'padding-bottom: ' . ($d->factor * 100) . '%;'; } // render the attributes $class = implode(' ', $classes); $style = implode('; ', $styles) . (!empty($styles) ? ';' : ''); return 'class="'.$class.'" style="'.$style.'"'; }
php
public static function renderWrapperAttrs(array $embed): string { // attributes to be rendered $classes = array(); $styles = array(); // shortcuts $d = &$embed['dimension']; // determine classes $classes[] = 'video-wrapper'; if ($d->dynamic) { $classes[] = 'wrap-'.$d->scale_model; } // determine inline CSS style(s) if ($d->dynamic && ($d->scale_model == 'scale-width-height')) { $styles[] = 'padding-bottom: ' . ($d->factor * 100) . '%;'; } // render the attributes $class = implode(' ', $classes); $style = implode('; ', $styles) . (!empty($styles) ? ';' : ''); return 'class="'.$class.'" style="'.$style.'"'; }
[ "public", "static", "function", "renderWrapperAttrs", "(", "array", "$", "embed", ")", ":", "string", "{", "// attributes to be rendered", "$", "classes", "=", "array", "(", ")", ";", "$", "styles", "=", "array", "(", ")", ";", "// shortcuts", "$", "d", "=", "&", "$", "embed", "[", "'dimension'", "]", ";", "// determine classes", "$", "classes", "[", "]", "=", "'video-wrapper'", ";", "if", "(", "$", "d", "->", "dynamic", ")", "{", "$", "classes", "[", "]", "=", "'wrap-'", ".", "$", "d", "->", "scale_model", ";", "}", "// determine inline CSS style(s)", "if", "(", "$", "d", "->", "dynamic", "&&", "(", "$", "d", "->", "scale_model", "==", "'scale-width-height'", ")", ")", "{", "$", "styles", "[", "]", "=", "'padding-bottom: '", ".", "(", "$", "d", "->", "factor", "*", "100", ")", ".", "'%;'", ";", "}", "// render the attributes", "$", "class", "=", "implode", "(", "' '", ",", "$", "classes", ")", ";", "$", "style", "=", "implode", "(", "'; '", ",", "$", "styles", ")", ".", "(", "!", "empty", "(", "$", "styles", ")", "?", "';'", ":", "''", ")", ";", "return", "'class=\"'", ".", "$", "class", ".", "'\" style=\"'", ".", "$", "style", ".", "'\"'", ";", "}" ]
Helper funcion to template. Render attributes for .videowrapper @param array $embed embed definition @return string HTTP attributes
[ "Helper", "funcion", "to", "template", ".", "Render", "attributes", "for", ".", "videowrapper" ]
train
https://github.com/phata/widgetfy/blob/00102c35ec5267b42c627f1e34b8e64a7dd3590c/src/Theme.php#L116-L136
phata/widgetfy
src/Theme.php
Theme.toHTML
public static function toHTML(array $embed, bool $inlineStyle=false): string { static $css_done; $css = ''; // use object dimension as dimension reference $d = &$embed['dimension']; // link to the stylesheet on first run if ($inlineStyle && !isset($css_done)) { $css = '<style>' . Theme::style() . '</style>'; $css_done = true; } ob_start(); include __DIR__ . '/Theme/theme.tpl.php'; $codeblock = ob_get_contents(); ob_end_clean(); return preg_replace('/[\t ]*[\r\n]+[\t ]*/', ' ', $css.$codeblock); }
php
public static function toHTML(array $embed, bool $inlineStyle=false): string { static $css_done; $css = ''; // use object dimension as dimension reference $d = &$embed['dimension']; // link to the stylesheet on first run if ($inlineStyle && !isset($css_done)) { $css = '<style>' . Theme::style() . '</style>'; $css_done = true; } ob_start(); include __DIR__ . '/Theme/theme.tpl.php'; $codeblock = ob_get_contents(); ob_end_clean(); return preg_replace('/[\t ]*[\r\n]+[\t ]*/', ' ', $css.$codeblock); }
[ "public", "static", "function", "toHTML", "(", "array", "$", "embed", ",", "bool", "$", "inlineStyle", "=", "false", ")", ":", "string", "{", "static", "$", "css_done", ";", "$", "css", "=", "''", ";", "// use object dimension as dimension reference", "$", "d", "=", "&", "$", "embed", "[", "'dimension'", "]", ";", "// link to the stylesheet on first run", "if", "(", "$", "inlineStyle", "&&", "!", "isset", "(", "$", "css_done", ")", ")", "{", "$", "css", "=", "'<style>'", ".", "Theme", "::", "style", "(", ")", ".", "'</style>'", ";", "$", "css_done", "=", "true", ";", "}", "ob_start", "(", ")", ";", "include", "__DIR__", ".", "'/Theme/theme.tpl.php'", ";", "$", "codeblock", "=", "ob_get_contents", "(", ")", ";", "ob_end_clean", "(", ")", ";", "return", "preg_replace", "(", "'/[\\t ]*[\\r\\n]+[\\t ]*/'", ",", "' '", ",", "$", "css", ".", "$", "codeblock", ")", ";", "}" ]
Theme the given embed information array into HTML string @param array $embed Embed information produced by Core::translate function. @param boolean $inlineStyle Whether the returned string should include default stylesheet. Default to be false. @return string
[ "Theme", "the", "given", "embed", "information", "array", "into", "HTML", "string" ]
train
https://github.com/phata/widgetfy/blob/00102c35ec5267b42c627f1e34b8e64a7dd3590c/src/Theme.php#L148-L167
bytic/autoloader
src/Loaders/ClassMap.php
ClassMap.getClassMapLocation
protected function getClassMapLocation($class, $retry = true) { $this->checkMapInit(); if (in_array($class, array_keys($this->getMap()))) { return $this->map[$class]; } if ($this->isRetry() === false) { return false; } if ($retry === true && !$this->isMaxRetries()) { $this->generateMap(); $this->increaseRetries(); return $this->getClassMapLocation($class, false); } return null; }
php
protected function getClassMapLocation($class, $retry = true) { $this->checkMapInit(); if (in_array($class, array_keys($this->getMap()))) { return $this->map[$class]; } if ($this->isRetry() === false) { return false; } if ($retry === true && !$this->isMaxRetries()) { $this->generateMap(); $this->increaseRetries(); return $this->getClassMapLocation($class, false); } return null; }
[ "protected", "function", "getClassMapLocation", "(", "$", "class", ",", "$", "retry", "=", "true", ")", "{", "$", "this", "->", "checkMapInit", "(", ")", ";", "if", "(", "in_array", "(", "$", "class", ",", "array_keys", "(", "$", "this", "->", "getMap", "(", ")", ")", ")", ")", "{", "return", "$", "this", "->", "map", "[", "$", "class", "]", ";", "}", "if", "(", "$", "this", "->", "isRetry", "(", ")", "===", "false", ")", "{", "return", "false", ";", "}", "if", "(", "$", "retry", "===", "true", "&&", "!", "$", "this", "->", "isMaxRetries", "(", ")", ")", "{", "$", "this", "->", "generateMap", "(", ")", ";", "$", "this", "->", "increaseRetries", "(", ")", ";", "return", "$", "this", "->", "getClassMapLocation", "(", "$", "class", ",", "false", ")", ";", "}", "return", "null", ";", "}" ]
@param $class @param bool $retry @return null|string
[ "@param", "$class", "@param", "bool", "$retry" ]
train
https://github.com/bytic/autoloader/blob/5b34e887432917cd3eadde1e4bf73b9b3e761f7a/src/Loaders/ClassMap.php#L65-L85
bytic/autoloader
src/Loaders/ClassMap.php
ClassMap.getCachePath
protected function getCachePath($dir) { $filepath = $this->getCacheName($dir); return $this->getAutoLoader()->getCachePath() . $filepath; }
php
protected function getCachePath($dir) { $filepath = $this->getCacheName($dir); return $this->getAutoLoader()->getCachePath() . $filepath; }
[ "protected", "function", "getCachePath", "(", "$", "dir", ")", "{", "$", "filepath", "=", "$", "this", "->", "getCacheName", "(", "$", "dir", ")", ";", "return", "$", "this", "->", "getAutoLoader", "(", ")", "->", "getCachePath", "(", ")", ".", "$", "filepath", ";", "}" ]
@param $dir @return string
[ "@param", "$dir" ]
train
https://github.com/bytic/autoloader/blob/5b34e887432917cd3eadde1e4bf73b9b3e761f7a/src/Loaders/ClassMap.php#L120-L125
bytic/autoloader
src/Loaders/ClassMap.php
ClassMap.readCacheFile
protected function readCacheFile($filePath) { if (file_exists($filePath)) { /** @noinspection PhpIncludeInspection */ $map = require $filePath; if (is_array($map)) { $this->map = array_merge($this->map, $map); } return true; } return false; }
php
protected function readCacheFile($filePath) { if (file_exists($filePath)) { /** @noinspection PhpIncludeInspection */ $map = require $filePath; if (is_array($map)) { $this->map = array_merge($this->map, $map); } return true; } return false; }
[ "protected", "function", "readCacheFile", "(", "$", "filePath", ")", "{", "if", "(", "file_exists", "(", "$", "filePath", ")", ")", "{", "/** @noinspection PhpIncludeInspection */", "$", "map", "=", "require", "$", "filePath", ";", "if", "(", "is_array", "(", "$", "map", ")", ")", "{", "$", "this", "->", "map", "=", "array_merge", "(", "$", "this", "->", "map", ",", "$", "map", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
@param string $filePath @return bool
[ "@param", "string", "$filePath" ]
train
https://github.com/bytic/autoloader/blob/5b34e887432917cd3eadde1e4bf73b9b3e761f7a/src/Loaders/ClassMap.php#L142-L155
bytic/autoloader
src/Loaders/ClassMap.php
ClassMap.generateMapDir
public function generateMapDir($dir) { $filepath = $this->getCachePath($dir); if (Generator::dump($dir, $filepath) == false) { throw new Exception("Error writing cache to " . $filepath); } }
php
public function generateMapDir($dir) { $filepath = $this->getCachePath($dir); if (Generator::dump($dir, $filepath) == false) { throw new Exception("Error writing cache to " . $filepath); } }
[ "public", "function", "generateMapDir", "(", "$", "dir", ")", "{", "$", "filepath", "=", "$", "this", "->", "getCachePath", "(", "$", "dir", ")", ";", "if", "(", "Generator", "::", "dump", "(", "$", "dir", ",", "$", "filepath", ")", "==", "false", ")", "{", "throw", "new", "Exception", "(", "\"Error writing cache to \"", ".", "$", "filepath", ")", ";", "}", "}" ]
@param $dir @throws Exception
[ "@param", "$dir" ]
train
https://github.com/bytic/autoloader/blob/5b34e887432917cd3eadde1e4bf73b9b3e761f7a/src/Loaders/ClassMap.php#L162-L168
PenoaksDev/Milky-Framework
src/Milky/Annotations/DocParser.php
DocParser.findInitialTokenPosition
private function findInitialTokenPosition( $input ) { $pos = 0; // search for first valid annotation while ( ( $pos = strpos( $input, '@', $pos ) ) !== false ) { // if the @ is preceded by a space or * it is valid if ( $pos === 0 || $input[$pos - 1] === ' ' || $input[$pos - 1] === '*' ) return $pos; $pos++; } return null; }
php
private function findInitialTokenPosition( $input ) { $pos = 0; // search for first valid annotation while ( ( $pos = strpos( $input, '@', $pos ) ) !== false ) { // if the @ is preceded by a space or * it is valid if ( $pos === 0 || $input[$pos - 1] === ' ' || $input[$pos - 1] === '*' ) return $pos; $pos++; } return null; }
[ "private", "function", "findInitialTokenPosition", "(", "$", "input", ")", "{", "$", "pos", "=", "0", ";", "// search for first valid annotation", "while", "(", "(", "$", "pos", "=", "strpos", "(", "$", "input", ",", "'@'", ",", "$", "pos", ")", ")", "!==", "false", ")", "{", "// if the @ is preceded by a space or * it is valid", "if", "(", "$", "pos", "===", "0", "||", "$", "input", "[", "$", "pos", "-", "1", "]", "===", "' '", "||", "$", "input", "[", "$", "pos", "-", "1", "]", "===", "'*'", ")", "return", "$", "pos", ";", "$", "pos", "++", ";", "}", "return", "null", ";", "}" ]
Finds the first valid annotation @param string $input The docblock string to parse @return int|null
[ "Finds", "the", "first", "valid", "annotation" ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Annotations/DocParser.php#L253-L268
PenoaksDev/Milky-Framework
src/Milky/Annotations/DocParser.php
DocParser.syntaxError
private function syntaxError( $expected, $token = null ) { if ( $token === null ) $token = $this->lexer->lookahead; $message = sprintf( 'Expected %s, got ', $expected ); $message .= ( $this->lexer->lookahead === null ) ? 'end of string' : sprintf( "'%s' at position %s", $token['value'], $token['position'] ); if ( strlen( $this->context ) ) $message .= ' in ' . $this->context; $message .= '.'; throw AnnotationException::syntaxError( $message ); }
php
private function syntaxError( $expected, $token = null ) { if ( $token === null ) $token = $this->lexer->lookahead; $message = sprintf( 'Expected %s, got ', $expected ); $message .= ( $this->lexer->lookahead === null ) ? 'end of string' : sprintf( "'%s' at position %s", $token['value'], $token['position'] ); if ( strlen( $this->context ) ) $message .= ' in ' . $this->context; $message .= '.'; throw AnnotationException::syntaxError( $message ); }
[ "private", "function", "syntaxError", "(", "$", "expected", ",", "$", "token", "=", "null", ")", "{", "if", "(", "$", "token", "===", "null", ")", "$", "token", "=", "$", "this", "->", "lexer", "->", "lookahead", ";", "$", "message", "=", "sprintf", "(", "'Expected %s, got '", ",", "$", "expected", ")", ";", "$", "message", ".=", "(", "$", "this", "->", "lexer", "->", "lookahead", "===", "null", ")", "?", "'end of string'", ":", "sprintf", "(", "\"'%s' at position %s\"", ",", "$", "token", "[", "'value'", "]", ",", "$", "token", "[", "'position'", "]", ")", ";", "if", "(", "strlen", "(", "$", "this", "->", "context", ")", ")", "$", "message", ".=", "' in '", ".", "$", "this", "->", "context", ";", "$", "message", ".=", "'.'", ";", "throw", "AnnotationException", "::", "syntaxError", "(", "$", "message", ")", ";", "}" ]
Generates a new syntax error. @param string $expected Expected string. @param array|null $token Optional token. @return void @throws AnnotationException
[ "Generates", "a", "new", "syntax", "error", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Annotations/DocParser.php#L298-L312