repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
netgen/site-bundle
bundle/ContextProvider/SessionContextProvider.php
SessionContextProvider.updateUserContext
public function updateUserContext(UserContext $context): void { if ($this->session->isStarted()) { $context->addParameter('sessionId', $this->session->getId()); } }
php
public function updateUserContext(UserContext $context): void { if ($this->session->isStarted()) { $context->addParameter('sessionId', $this->session->getId()); } }
[ "public", "function", "updateUserContext", "(", "UserContext", "$", "context", ")", ":", "void", "{", "if", "(", "$", "this", "->", "session", "->", "isStarted", "(", ")", ")", "{", "$", "context", "->", "addParameter", "(", "'sessionId'", ",", "$", "thi...
If the session is started, adds the session ID to user context. This allows varying the cache per session.
[ "If", "the", "session", "is", "started", "adds", "the", "session", "ID", "to", "user", "context", ".", "This", "allows", "varying", "the", "cache", "per", "session", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/ContextProvider/SessionContextProvider.php#L27-L32
train
smartboxgroup/integration-framework-bundle
Core/Processors/Routing/Multicast.php
Multicast.doProcess
protected function doProcess(Exchange $mainExchange, SerializableArray $processingContext) { foreach ($this->itineraries as $itinerary) { $exchange = new Exchange(); // Set headers if (!empty($mainExchange->getHeaders())) { $exchange->setHeaders($mainExchange->getHeaders()); } $exchange->setHeader(Exchange::HEADER_HANDLER, $mainExchange->getHeader(Exchange::HEADER_HANDLER)); $exchange->setHeader(Exchange::HEADER_PARENT_EXCHANGE, $mainExchange->getId()); $exchange->setHeader(Exchange::HEADER_FROM, $mainExchange->getHeader(Exchange::HEADER_FROM)); // Set Itinerary $exchange->getItinerary()->prepend($itinerary); $exchange->getItinerary()->setName('Multicast from "'.$mainExchange->getItinerary()->getName().'"'); // Set Message $msgCopy = unserialize(serialize($mainExchange->getIn())); $exchange->setIn($msgCopy); $event = new NewExchangeEvent($exchange); $event->setTimestampToCurrent(); $this->eventDispatcher->dispatch(NewExchangeEvent::TYPE_NEW_EXCHANGE_EVENT, $event); } }
php
protected function doProcess(Exchange $mainExchange, SerializableArray $processingContext) { foreach ($this->itineraries as $itinerary) { $exchange = new Exchange(); // Set headers if (!empty($mainExchange->getHeaders())) { $exchange->setHeaders($mainExchange->getHeaders()); } $exchange->setHeader(Exchange::HEADER_HANDLER, $mainExchange->getHeader(Exchange::HEADER_HANDLER)); $exchange->setHeader(Exchange::HEADER_PARENT_EXCHANGE, $mainExchange->getId()); $exchange->setHeader(Exchange::HEADER_FROM, $mainExchange->getHeader(Exchange::HEADER_FROM)); // Set Itinerary $exchange->getItinerary()->prepend($itinerary); $exchange->getItinerary()->setName('Multicast from "'.$mainExchange->getItinerary()->getName().'"'); // Set Message $msgCopy = unserialize(serialize($mainExchange->getIn())); $exchange->setIn($msgCopy); $event = new NewExchangeEvent($exchange); $event->setTimestampToCurrent(); $this->eventDispatcher->dispatch(NewExchangeEvent::TYPE_NEW_EXCHANGE_EVENT, $event); } }
[ "protected", "function", "doProcess", "(", "Exchange", "$", "mainExchange", ",", "SerializableArray", "$", "processingContext", ")", "{", "foreach", "(", "$", "this", "->", "itineraries", "as", "$", "itinerary", ")", "{", "$", "exchange", "=", "new", "Exchange...
The current implementation assumes the existence of only one aggregation strategy which ignores the child exchanges. @param Exchange $mainExchange
[ "The", "current", "implementation", "assumes", "the", "existence", "of", "only", "one", "aggregation", "strategy", "which", "ignores", "the", "child", "exchanges", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Core/Processors/Routing/Multicast.php#L89-L115
train
netgen/site-bundle
bundle/Controller/PartsController.php
PartsController.viewRelatedItems
public function viewRelatedItems(Request $request, Content $content, string $fieldDefinitionIdentifier, string $template): Response { return $this->render( $template, [ 'content' => $content, 'location' => $content->mainLocation, 'field_identifier' => $fieldDefinitionIdentifier, 'related_items' => $this->locationResolver->loadRelations($content->mainLocation, $fieldDefinitionIdentifier), 'view_type' => $request->attributes->get('viewType') ?? 'line', ] ); }
php
public function viewRelatedItems(Request $request, Content $content, string $fieldDefinitionIdentifier, string $template): Response { return $this->render( $template, [ 'content' => $content, 'location' => $content->mainLocation, 'field_identifier' => $fieldDefinitionIdentifier, 'related_items' => $this->locationResolver->loadRelations($content->mainLocation, $fieldDefinitionIdentifier), 'view_type' => $request->attributes->get('viewType') ?? 'line', ] ); }
[ "public", "function", "viewRelatedItems", "(", "Request", "$", "request", ",", "Content", "$", "content", ",", "string", "$", "fieldDefinitionIdentifier", ",", "string", "$", "template", ")", ":", "Response", "{", "return", "$", "this", "->", "render", "(", ...
Action for rendering related items of a provided content.
[ "Action", "for", "rendering", "related", "items", "of", "a", "provided", "content", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/PartsController.php#L36-L48
train
dereuromark/cakephp-markup
src/View/Helper/HighlighterHelper.php
HighlighterHelper.highlight
public function highlight($text, array $options = []) { if ($this->_config['debug']) { $this->_startTimer(); } $highlightedText = $this->_getHighlighter()->highlight($text, $options); if ($this->_config['debug']) { $highlightedText .= $this->_timeElapsedFormatted($this->_endTimer()); } return $highlightedText; }
php
public function highlight($text, array $options = []) { if ($this->_config['debug']) { $this->_startTimer(); } $highlightedText = $this->_getHighlighter()->highlight($text, $options); if ($this->_config['debug']) { $highlightedText .= $this->_timeElapsedFormatted($this->_endTimer()); } return $highlightedText; }
[ "public", "function", "highlight", "(", "$", "text", ",", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "_config", "[", "'debug'", "]", ")", "{", "$", "this", "->", "_startTimer", "(", ")", ";", "}", "$", "highli...
Highlight a string. Options, depending on the specific highlighter class used: - templates - escape (defaults to true) - tabToSpaces (defaults to 4) - prefix (defaults to `language-`) @param string $text @param array $options @return string
[ "Highlight", "a", "string", "." ]
658c52b05b1e800b5640fceda77dce94eba90c2c
https://github.com/dereuromark/cakephp-markup/blob/658c52b05b1e800b5640fceda77dce94eba90c2c/src/View/Helper/HighlighterHelper.php#L58-L67
train
netgen/site-bundle
bundle/Menu/RelationListMenuBuilder.php
RelationListMenuBuilder.createRelationListMenu
public function createRelationListMenu(string $fieldIdentifier, $contentId = null): ItemInterface { $content = $contentId !== null ? $this->loadService->loadContent($contentId) : $this->siteInfoHelper->getSiteInfoContent(); $menu = $this->factory->createItem('root'); $menu->setAttribute('location-id', $content->mainLocationId); $menu->setExtra('ezlocation', $content->mainLocation); if (!$content->hasField($fieldIdentifier)) { return $menu; } $field = $content->getField($fieldIdentifier); if (!$field->value instanceof RelationListValue || $field->isEmpty()) { return $menu; } foreach ($field->value->destinationLocationIds as $locationId) { if (empty($locationId)) { $this->logger->error(sprintf('Empty location ID in RelationList field "%s" for content #%s', $fieldIdentifier, $content->id)); continue; } try { $location = $this->loadService->loadLocation($locationId); } catch (Throwable $t) { $this->logger->error($t->getMessage()); continue; } $menu->addChild(null, ['ezlocation' => $location]); } return $menu; }
php
public function createRelationListMenu(string $fieldIdentifier, $contentId = null): ItemInterface { $content = $contentId !== null ? $this->loadService->loadContent($contentId) : $this->siteInfoHelper->getSiteInfoContent(); $menu = $this->factory->createItem('root'); $menu->setAttribute('location-id', $content->mainLocationId); $menu->setExtra('ezlocation', $content->mainLocation); if (!$content->hasField($fieldIdentifier)) { return $menu; } $field = $content->getField($fieldIdentifier); if (!$field->value instanceof RelationListValue || $field->isEmpty()) { return $menu; } foreach ($field->value->destinationLocationIds as $locationId) { if (empty($locationId)) { $this->logger->error(sprintf('Empty location ID in RelationList field "%s" for content #%s', $fieldIdentifier, $content->id)); continue; } try { $location = $this->loadService->loadLocation($locationId); } catch (Throwable $t) { $this->logger->error($t->getMessage()); continue; } $menu->addChild(null, ['ezlocation' => $location]); } return $menu; }
[ "public", "function", "createRelationListMenu", "(", "string", "$", "fieldIdentifier", ",", "$", "contentId", "=", "null", ")", ":", "ItemInterface", "{", "$", "content", "=", "$", "contentId", "!==", "null", "?", "$", "this", "->", "loadService", "->", "loa...
Creates the KNP menu from provided content and field identifier. @param mixed|null $contentId
[ "Creates", "the", "KNP", "menu", "from", "provided", "content", "and", "field", "identifier", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Menu/RelationListMenuBuilder.php#L55-L94
train
IconoCoders/otp-simple-sdk
Source/SimpleLiveUpdate.php
SimpleLiveUpdate.createHtmlForm
public function createHtmlForm($formName = 'SimplePayForm', $submitElement = 'button', $submitElementText = 'Start Payment') { if (count($this->errorMessage) > 0) { return false; } if (!$this->prepareFields("ORDER_HASH")) { $this->errorMessage[] = 'HASH FIELD: Missing hash field name'; return false; } $logString = ""; $this->luForm = "\n<form action='" . $this->baseUrl . $this->targetUrl . "' method='POST' id='" . $formName . "' accept-charset='UTF-8'>"; foreach ($this->formData as $name => $field) { if (is_array($field)) { foreach ($field as $subField) { $this->luForm .= $this->createHiddenField($name . "[]", $subField); $logString .= $name . '=' . $subField . "\n"; } } elseif (!is_array($field)) { if ($name == "BACK_REF" or $name == "TIMEOUT_URL") { $concat = '?'; if (strpos($field, '?') !== false) { $concat = '&'; } $field .= $concat . 'order_ref=' . $this->fieldData['ORDER_REF'] . '&order_currency=' . $this->fieldData['PRICES_CURRENCY']; $field = $this->protocol . '://' . $field; } $this->luForm .= $this->createHiddenField($name, $field); $logString .= $name . '=' . $field . "\n"; } } $this->luForm .= $this->createHiddenField("SDK_VERSION", $this->sdkVersion); $this->luForm .= $this->formSubmitElement($formName, $submitElement, $submitElementText); $this->luForm .= "\n</form>"; $this->logFunc("LiveUpdate", $this->formData, $this->formData['ORDER_REF']); $this->debugMessage[] = 'HASH CODE: ' . $this->hashCode; return $this->luForm; }
php
public function createHtmlForm($formName = 'SimplePayForm', $submitElement = 'button', $submitElementText = 'Start Payment') { if (count($this->errorMessage) > 0) { return false; } if (!$this->prepareFields("ORDER_HASH")) { $this->errorMessage[] = 'HASH FIELD: Missing hash field name'; return false; } $logString = ""; $this->luForm = "\n<form action='" . $this->baseUrl . $this->targetUrl . "' method='POST' id='" . $formName . "' accept-charset='UTF-8'>"; foreach ($this->formData as $name => $field) { if (is_array($field)) { foreach ($field as $subField) { $this->luForm .= $this->createHiddenField($name . "[]", $subField); $logString .= $name . '=' . $subField . "\n"; } } elseif (!is_array($field)) { if ($name == "BACK_REF" or $name == "TIMEOUT_URL") { $concat = '?'; if (strpos($field, '?') !== false) { $concat = '&'; } $field .= $concat . 'order_ref=' . $this->fieldData['ORDER_REF'] . '&order_currency=' . $this->fieldData['PRICES_CURRENCY']; $field = $this->protocol . '://' . $field; } $this->luForm .= $this->createHiddenField($name, $field); $logString .= $name . '=' . $field . "\n"; } } $this->luForm .= $this->createHiddenField("SDK_VERSION", $this->sdkVersion); $this->luForm .= $this->formSubmitElement($formName, $submitElement, $submitElementText); $this->luForm .= "\n</form>"; $this->logFunc("LiveUpdate", $this->formData, $this->formData['ORDER_REF']); $this->debugMessage[] = 'HASH CODE: ' . $this->hashCode; return $this->luForm; }
[ "public", "function", "createHtmlForm", "(", "$", "formName", "=", "'SimplePayForm'", ",", "$", "submitElement", "=", "'button'", ",", "$", "submitElementText", "=", "'Start Payment'", ")", "{", "if", "(", "count", "(", "$", "this", "->", "errorMessage", ")", ...
Generates a ready-to-insert HTML FORM @param string $formName The ID parameter of the form @param string $submitElement The type of the submit element ('button' or 'link') @param string $submitElementText The label for the submit element @return string HTML form
[ "Generates", "a", "ready", "-", "to", "-", "insert", "HTML", "FORM" ]
d2808bf52e8d34be69414b444a00f1a9c8564930
https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleLiveUpdate.php#L154-L191
train
IconoCoders/otp-simple-sdk
Source/SimpleLiveUpdate.php
SimpleLiveUpdate.formSubmitElement
protected function formSubmitElement($formName = '', $submitElement = 'button', $submitElementText = '') { switch ($submitElement) { case 'link': $element = "\n<a href='javascript:document.getElementById(\"" . $formName ."\").submit()'>" . addslashes($submitElementText) . "</a>"; break; case 'button': $element = "\n<button type='submit'>" . addslashes($submitElementText) . "</button>"; break; case 'auto': $element = "\n<button type='submit'>" . addslashes($submitElementText) . "</button>"; $element .= "\n<script language=\"javascript\" type=\"text/javascript\">document.getElementById(\"" . $formName . "\").submit();</script>"; break; default : $element = "\n<button type='submit'>" . addslashes($submitElementText) . "</button>"; break; } return $element; }
php
protected function formSubmitElement($formName = '', $submitElement = 'button', $submitElementText = '') { switch ($submitElement) { case 'link': $element = "\n<a href='javascript:document.getElementById(\"" . $formName ."\").submit()'>" . addslashes($submitElementText) . "</a>"; break; case 'button': $element = "\n<button type='submit'>" . addslashes($submitElementText) . "</button>"; break; case 'auto': $element = "\n<button type='submit'>" . addslashes($submitElementText) . "</button>"; $element .= "\n<script language=\"javascript\" type=\"text/javascript\">document.getElementById(\"" . $formName . "\").submit();</script>"; break; default : $element = "\n<button type='submit'>" . addslashes($submitElementText) . "</button>"; break; } return $element; }
[ "protected", "function", "formSubmitElement", "(", "$", "formName", "=", "''", ",", "$", "submitElement", "=", "'button'", ",", "$", "submitElementText", "=", "''", ")", "{", "switch", "(", "$", "submitElement", ")", "{", "case", "'link'", ":", "$", "eleme...
Generates HTML submit element @param string $formName The ID parameter of the form @param string $submitElement The type of the submit element ('button' or 'link') @param string $submitElementText The lebel for the submit element @return string HTML submit
[ "Generates", "HTML", "submit", "element" ]
d2808bf52e8d34be69414b444a00f1a9c8564930
https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleLiveUpdate.php#L204-L222
train
IconoCoders/otp-simple-sdk
Source/SimpleIpn.php
SimpleIpn.validateReceived
public function validateReceived() { $this->debugMessage[] = 'IPN VALIDATION: START'; if (!$this->ipnPostDataCheck()) { $this->debugMessage[] = 'IPN VALIDATION: END'; return false; } //'ORDERSTATUS' $this->logFunc("IPN", $this->postData, @$this->postData['REFNOEXT']); if (!in_array(trim($this->postData['ORDERSTATUS']), $this->successfulStatus)) { $this->errorMessage[] = 'INVALID IPN ORDER STATUS: ' . $this->postData['ORDERSTATUS']; $this->debugMessage[] = 'IPN VALIDATION: END'; return false; } $validationResult = false; $calculatedHashString = $this->createHashString($this->flatArray($this->postData, array("HASH"))); if ($calculatedHashString == $this->postData['HASH']) { $validationResult = true; } if ($validationResult) { $this->debugMessage[] = 'IPN VALIDATION: ' . 'SUCCESSFUL'; $this->debugMessage[] = 'IPN CALCULATED HASH: ' . $calculatedHashString; $this->debugMessage[] = 'IPN HASH: ' . $this->postData['HASH']; $this->debugMessage[] = 'IPN VALIDATION: END'; return true; } elseif (!$validationResult) { $this->errorMessage[] = 'IPN VALIDATION: ' . 'FAILED'; $this->errorMessage[] = 'IPN CALCULATED HASH: ' . $calculatedHashString; $this->errorMessage[] = 'IPN RECEIVED HASH: ' . $this->postData['HASH']; $this->debugMessage[] = 'IPN VALIDATION: END'; return false; } return false; }
php
public function validateReceived() { $this->debugMessage[] = 'IPN VALIDATION: START'; if (!$this->ipnPostDataCheck()) { $this->debugMessage[] = 'IPN VALIDATION: END'; return false; } //'ORDERSTATUS' $this->logFunc("IPN", $this->postData, @$this->postData['REFNOEXT']); if (!in_array(trim($this->postData['ORDERSTATUS']), $this->successfulStatus)) { $this->errorMessage[] = 'INVALID IPN ORDER STATUS: ' . $this->postData['ORDERSTATUS']; $this->debugMessage[] = 'IPN VALIDATION: END'; return false; } $validationResult = false; $calculatedHashString = $this->createHashString($this->flatArray($this->postData, array("HASH"))); if ($calculatedHashString == $this->postData['HASH']) { $validationResult = true; } if ($validationResult) { $this->debugMessage[] = 'IPN VALIDATION: ' . 'SUCCESSFUL'; $this->debugMessage[] = 'IPN CALCULATED HASH: ' . $calculatedHashString; $this->debugMessage[] = 'IPN HASH: ' . $this->postData['HASH']; $this->debugMessage[] = 'IPN VALIDATION: END'; return true; } elseif (!$validationResult) { $this->errorMessage[] = 'IPN VALIDATION: ' . 'FAILED'; $this->errorMessage[] = 'IPN CALCULATED HASH: ' . $calculatedHashString; $this->errorMessage[] = 'IPN RECEIVED HASH: ' . $this->postData['HASH']; $this->debugMessage[] = 'IPN VALIDATION: END'; return false; } return false; }
[ "public", "function", "validateReceived", "(", ")", "{", "$", "this", "->", "debugMessage", "[", "]", "=", "'IPN VALIDATION: START'", ";", "if", "(", "!", "$", "this", "->", "ipnPostDataCheck", "(", ")", ")", "{", "$", "this", "->", "debugMessage", "[", ...
Validate recceived data against HMAC HASH @return boolean
[ "Validate", "recceived", "data", "against", "HMAC", "HASH" ]
d2808bf52e8d34be69414b444a00f1a9c8564930
https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleIpn.php#L81-L115
train
IconoCoders/otp-simple-sdk
Source/SimpleIpn.php
SimpleIpn.confirmReceived
public function confirmReceived() { $this->debugMessage[] = 'IPN CONFIRM: START'; if (!$this->ipnPostDataCheck()) { $this->debugMessage[] = 'IPN CONFIRM: END'; return false; } $serverDate = @date("YmdHis"); $hashArray = array( $this->postData['IPN_PID'][0], $this->postData['IPN_PNAME'][0], $this->postData['IPN_DATE'], $serverDate ); $hash = $this->createHashString($hashArray); $string = "<EPAYMENT>" . $serverDate . "|" . $hash . "</EPAYMENT>"; $this->debugMessage[] = 'IPN CONFIRM EPAYMENT: ' . $string; $this->debugMessage[] = 'IPN CONFIRM: END'; if ($this->echo) { echo $string; } return $string; }
php
public function confirmReceived() { $this->debugMessage[] = 'IPN CONFIRM: START'; if (!$this->ipnPostDataCheck()) { $this->debugMessage[] = 'IPN CONFIRM: END'; return false; } $serverDate = @date("YmdHis"); $hashArray = array( $this->postData['IPN_PID'][0], $this->postData['IPN_PNAME'][0], $this->postData['IPN_DATE'], $serverDate ); $hash = $this->createHashString($hashArray); $string = "<EPAYMENT>" . $serverDate . "|" . $hash . "</EPAYMENT>"; $this->debugMessage[] = 'IPN CONFIRM EPAYMENT: ' . $string; $this->debugMessage[] = 'IPN CONFIRM: END'; if ($this->echo) { echo $string; } return $string; }
[ "public", "function", "confirmReceived", "(", ")", "{", "$", "this", "->", "debugMessage", "[", "]", "=", "'IPN CONFIRM: START'", ";", "if", "(", "!", "$", "this", "->", "ipnPostDataCheck", "(", ")", ")", "{", "$", "this", "->", "debugMessage", "[", "]",...
Creates INLINE string for corfirmation @return string $string <EPAYMENT> tag
[ "Creates", "INLINE", "string", "for", "corfirmation" ]
d2808bf52e8d34be69414b444a00f1a9c8564930
https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleIpn.php#L123-L146
train
IconoCoders/otp-simple-sdk
Source/SimpleIpn.php
SimpleIpn.ipnPostDataCheck
protected function ipnPostDataCheck() { if (count($this->postData) < 1 || !array_key_exists('REFNOEXT', $this->postData)) { $this->debugMessage[] = 'IPN POST: MISSING CONTENT'; $this->errorMessage[] = 'IPN POST: MISSING CONTENT'; return false; } return true; }
php
protected function ipnPostDataCheck() { if (count($this->postData) < 1 || !array_key_exists('REFNOEXT', $this->postData)) { $this->debugMessage[] = 'IPN POST: MISSING CONTENT'; $this->errorMessage[] = 'IPN POST: MISSING CONTENT'; return false; } return true; }
[ "protected", "function", "ipnPostDataCheck", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "postData", ")", "<", "1", "||", "!", "array_key_exists", "(", "'REFNOEXT'", ",", "$", "this", "->", "postData", ")", ")", "{", "$", "this", "->", ...
Check post data if contains REFNOEXT variable @return boolean
[ "Check", "post", "data", "if", "contains", "REFNOEXT", "variable" ]
d2808bf52e8d34be69414b444a00f1a9c8564930
https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleIpn.php#L154-L162
train
netgen/site-bundle
bundle/DependencyInjection/Compiler/XslRegisterPass.php
XslRegisterPass.process
public function process(ContainerBuilder $container): void { $scopes = array_merge( [ConfigResolver::SCOPE_DEFAULT], $container->getParameter('ezpublish.siteaccess.list') ); // Adding ezxml_tags.xsl to all scopes foreach ($scopes as $scope) { if (!$container->hasParameter("ezsettings.${scope}.fieldtypes.ezxml.custom_xsl")) { continue; } $xslConfig = $container->getParameter("ezsettings.${scope}.fieldtypes.ezxml.custom_xsl"); $xslConfig[] = ['path' => __DIR__ . '/../../Resources/xsl/ezxml_tags.xsl', 'priority' => 5000]; $container->setParameter("ezsettings.${scope}.fieldtypes.ezxml.custom_xsl", $xslConfig); } }
php
public function process(ContainerBuilder $container): void { $scopes = array_merge( [ConfigResolver::SCOPE_DEFAULT], $container->getParameter('ezpublish.siteaccess.list') ); // Adding ezxml_tags.xsl to all scopes foreach ($scopes as $scope) { if (!$container->hasParameter("ezsettings.${scope}.fieldtypes.ezxml.custom_xsl")) { continue; } $xslConfig = $container->getParameter("ezsettings.${scope}.fieldtypes.ezxml.custom_xsl"); $xslConfig[] = ['path' => __DIR__ . '/../../Resources/xsl/ezxml_tags.xsl', 'priority' => 5000]; $container->setParameter("ezsettings.${scope}.fieldtypes.ezxml.custom_xsl", $xslConfig); } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "scopes", "=", "array_merge", "(", "[", "ConfigResolver", "::", "SCOPE_DEFAULT", "]", ",", "$", "container", "->", "getParameter", "(", "'ezpublish.siteaccess...
Registers ezxml_tags.xsl as custom XSL stylesheet for ezxmltext field type.
[ "Registers", "ezxml_tags", ".", "xsl", "as", "custom", "XSL", "stylesheet", "for", "ezxmltext", "field", "type", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/DependencyInjection/Compiler/XslRegisterPass.php#L16-L33
train
alaxos/cakephp3-libs
src/View/Helper/AlaxosHtmlHelper.php
AlaxosHtmlHelper.encodeEmail
public function encodeEmail($email) { $this->includeAlaxosEncodeJS(); $js_code = '<script type="text/javascript">'; $email_id = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 1) . intval(mt_rand()); //valid XHTML tag id can not start with a number $js_code .= 'alaxos_' . $email_id . '='; for($i = 0; $i < strlen($email); $i++) { $char = strtolower($email[$i]); switch($char) { case '.': $js_code .= 'l_dot.charAt(0)'; break; case '_': $js_code .= 'l_under.charAt(0)'; break; case '-': $js_code .= 'l_dash.charAt(0)'; break; case '@': $js_code .= 'l_at.charAt(0)'; break; default: $js_code .= 'l_' . $char . '.charAt(0)'; break; } $js_code .= ($i < strlen($email) - 1) ? '+' : ''; } if(!$this->getView()->getRequest()->is('ajax')) { $js_code .= ';' . $this->getConfig('jquery_variable') . '(document).ready(function(){ ' . $this->getConfig('jquery_variable') . '("#' . $email_id . '").attr("href", "mailto:" + alaxos_' . $email_id . ');' . $this->getConfig('jquery_variable') . '("#' . $email_id . '").html(alaxos_' . $email_id . '); });</script><a id="' . $email_id . '"><em>missing email</em></a>'; } else { $js_code .= ';' . $this->getConfig('jquery_variable') . '("#' . $email_id . '").attr("href", "mailto:" + alaxos_' . $email_id . ');' . $this->getConfig('jquery_variable') . '("#' . $email_id . '").html(alaxos_' . $email_id . ');</script><a id="' . $email_id . '"><em>missing email</em></a>'; } return $js_code; }
php
public function encodeEmail($email) { $this->includeAlaxosEncodeJS(); $js_code = '<script type="text/javascript">'; $email_id = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 1) . intval(mt_rand()); //valid XHTML tag id can not start with a number $js_code .= 'alaxos_' . $email_id . '='; for($i = 0; $i < strlen($email); $i++) { $char = strtolower($email[$i]); switch($char) { case '.': $js_code .= 'l_dot.charAt(0)'; break; case '_': $js_code .= 'l_under.charAt(0)'; break; case '-': $js_code .= 'l_dash.charAt(0)'; break; case '@': $js_code .= 'l_at.charAt(0)'; break; default: $js_code .= 'l_' . $char . '.charAt(0)'; break; } $js_code .= ($i < strlen($email) - 1) ? '+' : ''; } if(!$this->getView()->getRequest()->is('ajax')) { $js_code .= ';' . $this->getConfig('jquery_variable') . '(document).ready(function(){ ' . $this->getConfig('jquery_variable') . '("#' . $email_id . '").attr("href", "mailto:" + alaxos_' . $email_id . ');' . $this->getConfig('jquery_variable') . '("#' . $email_id . '").html(alaxos_' . $email_id . '); });</script><a id="' . $email_id . '"><em>missing email</em></a>'; } else { $js_code .= ';' . $this->getConfig('jquery_variable') . '("#' . $email_id . '").attr("href", "mailto:" + alaxos_' . $email_id . ');' . $this->getConfig('jquery_variable') . '("#' . $email_id . '").html(alaxos_' . $email_id . ');</script><a id="' . $email_id . '"><em>missing email</em></a>'; } return $js_code; }
[ "public", "function", "encodeEmail", "(", "$", "email", ")", "{", "$", "this", "->", "includeAlaxosEncodeJS", "(", ")", ";", "$", "js_code", "=", "'<script type=\"text/javascript\">'", ";", "$", "email_id", "=", "substr", "(", "str_shuffle", "(", "'abcdefghijklm...
Return a string that is a JS encoded email address. Printing this JS string instead of the plain email text should reduce the probability to get the email harvested by spamming robots. Note: The returned string is made of a <script> block and a <a> block. @param $email
[ "Return", "a", "string", "that", "is", "a", "JS", "encoded", "email", "address", "." ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/View/Helper/AlaxosHtmlHelper.php#L242-L287
train
alaxos/cakephp3-libs
src/Model/Behavior/TimezonedBehavior.php
TimezonedBehavior.prepareTimezonedDatetimeValuesForSaving
public function prepareTimezonedDatetimeValuesForSaving(\ArrayObject $data) { $display_timezone = null; if(Configure::check('display_timezone')) { $display_timezone = Configure::read('display_timezone'); } elseif(Configure::check('default_display_timezone')) { $display_timezone = Configure::read('default_display_timezone'); } $server_default_timezone = date_default_timezone_get(); if(!empty($display_timezone) && !empty($server_default_timezone)) { foreach($data as $field => $value) { if(isset($value) && !empty($value)) { $fieldtype = $this->_table->getSchema()->getColumn($field)['type']; if($fieldtype == 'datetime') { if(is_string($value)) { $data[$field] = Time::parse($value, $display_timezone)->setTimezone($server_default_timezone); } elseif(is_a($value, 'Cake\I18n\Time')) { $value->setTimezone($server_default_timezone); } } elseif($fieldtype == 'date') { if(is_string($value)) { $data[$field] = Time::parse($value, $display_timezone); } } } } } }
php
public function prepareTimezonedDatetimeValuesForSaving(\ArrayObject $data) { $display_timezone = null; if(Configure::check('display_timezone')) { $display_timezone = Configure::read('display_timezone'); } elseif(Configure::check('default_display_timezone')) { $display_timezone = Configure::read('default_display_timezone'); } $server_default_timezone = date_default_timezone_get(); if(!empty($display_timezone) && !empty($server_default_timezone)) { foreach($data as $field => $value) { if(isset($value) && !empty($value)) { $fieldtype = $this->_table->getSchema()->getColumn($field)['type']; if($fieldtype == 'datetime') { if(is_string($value)) { $data[$field] = Time::parse($value, $display_timezone)->setTimezone($server_default_timezone); } elseif(is_a($value, 'Cake\I18n\Time')) { $value->setTimezone($server_default_timezone); } } elseif($fieldtype == 'date') { if(is_string($value)) { $data[$field] = Time::parse($value, $display_timezone); } } } } } }
[ "public", "function", "prepareTimezonedDatetimeValuesForSaving", "(", "\\", "ArrayObject", "$", "data", ")", "{", "$", "display_timezone", "=", "null", ";", "if", "(", "Configure", "::", "check", "(", "'display_timezone'", ")", ")", "{", "$", "display_timezone", ...
Convert datetime strings that are entered in the display time zone to UTC Time objects that will allow to save datetime in UTC @param \ArrayObject $data
[ "Convert", "datetime", "strings", "that", "are", "entered", "in", "the", "display", "time", "zone", "to", "UTC", "Time", "objects", "that", "will", "allow", "to", "save", "datetime", "in", "UTC" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Model/Behavior/TimezonedBehavior.php#L27-L71
train
netgen/site-bundle
bundle/EventListener/User/PostActivateEventListener.php
PostActivateEventListener.onPostActivate
public function onPostActivate(PostActivateEvent $event): void { $user = $event->getUser(); $this->ezUserAccountKeyRepository->removeByUserId($user->id); $this->ngUserSettingRepository->activateUser($user->id); $this->mailHelper ->sendMail( [$user->email => $this->getUserName($user)], 'ngsite.user.welcome.subject', $this->configResolver->getParameter('template.user.mail.welcome', 'ngsite'), [ 'user' => $user, ] ); }
php
public function onPostActivate(PostActivateEvent $event): void { $user = $event->getUser(); $this->ezUserAccountKeyRepository->removeByUserId($user->id); $this->ngUserSettingRepository->activateUser($user->id); $this->mailHelper ->sendMail( [$user->email => $this->getUserName($user)], 'ngsite.user.welcome.subject', $this->configResolver->getParameter('template.user.mail.welcome', 'ngsite'), [ 'user' => $user, ] ); }
[ "public", "function", "onPostActivate", "(", "PostActivateEvent", "$", "event", ")", ":", "void", "{", "$", "user", "=", "$", "event", "->", "getUser", "(", ")", ";", "$", "this", "->", "ezUserAccountKeyRepository", "->", "removeByUserId", "(", "$", "user", ...
Listens to the event triggered after the user activation has been finished. Event contains information about activated user.
[ "Listens", "to", "the", "event", "triggered", "after", "the", "user", "activation", "has", "been", "finished", ".", "Event", "contains", "information", "about", "activated", "user", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/EventListener/User/PostActivateEventListener.php#L30-L46
train
nilportugues/php-api-transformer
src/Transformer/Helpers/RecursiveFormatterHelper.php
RecursiveFormatterHelper.namespaceAsArrayKey
public static function namespaceAsArrayKey(string $key) : string { $keys = \explode('\\', $key); $className = \end($keys); return self::camelCaseToUnderscore($className); }
php
public static function namespaceAsArrayKey(string $key) : string { $keys = \explode('\\', $key); $className = \end($keys); return self::camelCaseToUnderscore($className); }
[ "public", "static", "function", "namespaceAsArrayKey", "(", "string", "$", "key", ")", ":", "string", "{", "$", "keys", "=", "\\", "explode", "(", "'\\\\'", ",", "$", "key", ")", ";", "$", "className", "=", "\\", "end", "(", "$", "keys", ")", ";", ...
Given a class name will return its name without the namespace and in under_score to be used as a key in an array. @param string $key @return string
[ "Given", "a", "class", "name", "will", "return", "its", "name", "without", "the", "namespace", "and", "in", "under_score", "to", "be", "used", "as", "a", "key", "in", "an", "array", "." ]
a9f20fbe1580d98e3d462a0ebe13fb7595cbd683
https://github.com/nilportugues/php-api-transformer/blob/a9f20fbe1580d98e3d462a0ebe13fb7595cbd683/src/Transformer/Helpers/RecursiveFormatterHelper.php#L26-L32
train
nilportugues/php-api-transformer
src/Transformer/Helpers/RecursiveFormatterHelper.php
RecursiveFormatterHelper.camelCaseToUnderscore
public static function camelCaseToUnderscore(string $camel, string $splitter = '_') : string { $camel = \preg_replace( '/(?!^)[[:upper:]][[:lower:]]/', '$0', \preg_replace('/(?!^)[[:upper:]]+/', $splitter.'$0', $camel) ); return \strtolower($camel); }
php
public static function camelCaseToUnderscore(string $camel, string $splitter = '_') : string { $camel = \preg_replace( '/(?!^)[[:upper:]][[:lower:]]/', '$0', \preg_replace('/(?!^)[[:upper:]]+/', $splitter.'$0', $camel) ); return \strtolower($camel); }
[ "public", "static", "function", "camelCaseToUnderscore", "(", "string", "$", "camel", ",", "string", "$", "splitter", "=", "'_'", ")", ":", "string", "{", "$", "camel", "=", "\\", "preg_replace", "(", "'/(?!^)[[:upper:]][[:lower:]]/'", ",", "'$0'", ",", "\\", ...
Transforms a given string from camelCase to under_score style. @param string $camel @param string $splitter @return string
[ "Transforms", "a", "given", "string", "from", "camelCase", "to", "under_score", "style", "." ]
a9f20fbe1580d98e3d462a0ebe13fb7595cbd683
https://github.com/nilportugues/php-api-transformer/blob/a9f20fbe1580d98e3d462a0ebe13fb7595cbd683/src/Transformer/Helpers/RecursiveFormatterHelper.php#L42-L51
train
netgen/site-bundle
bundle/Entity/Repository/EzUserAccountKeyRepository.php
EzUserAccountKeyRepository.create
public function create($userId): EzUserAccountKey { $this->removeByUserId($userId); $randomBytes = false; if (function_exists('openssl_random_pseudo_bytes')) { $randomBytes = openssl_random_pseudo_bytes(32); } if ($randomBytes === false) { $randomBytes = mt_rand(); } $hash = md5($userId . ':' . microtime() . ':' . $randomBytes); $userAccount = new EzUserAccountKey(); $userAccount->setHash($hash); $userAccount->setTime(time()); $userAccount->setUserId($userId); $this->getEntityManager()->persist($userAccount); $this->getEntityManager()->flush(); return $userAccount; }
php
public function create($userId): EzUserAccountKey { $this->removeByUserId($userId); $randomBytes = false; if (function_exists('openssl_random_pseudo_bytes')) { $randomBytes = openssl_random_pseudo_bytes(32); } if ($randomBytes === false) { $randomBytes = mt_rand(); } $hash = md5($userId . ':' . microtime() . ':' . $randomBytes); $userAccount = new EzUserAccountKey(); $userAccount->setHash($hash); $userAccount->setTime(time()); $userAccount->setUserId($userId); $this->getEntityManager()->persist($userAccount); $this->getEntityManager()->flush(); return $userAccount; }
[ "public", "function", "create", "(", "$", "userId", ")", ":", "EzUserAccountKey", "{", "$", "this", "->", "removeByUserId", "(", "$", "userId", ")", ";", "$", "randomBytes", "=", "false", ";", "if", "(", "function_exists", "(", "'openssl_random_pseudo_bytes'",...
Creates a user account key. @param mixed $userId @return \Netgen\Bundle\SiteBundle\Entity\EzUserAccountKey
[ "Creates", "a", "user", "account", "key", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Entity/Repository/EzUserAccountKeyRepository.php#L19-L44
train
netgen/site-bundle
bundle/Entity/Repository/EzUserAccountKeyRepository.php
EzUserAccountKeyRepository.removeByHash
public function removeByHash(string $hash): void { $results = $this->findBy(['hashKey' => $hash]); foreach ($results as $result) { $this->getEntityManager()->remove($result); } $this->getEntityManager()->flush(); }
php
public function removeByHash(string $hash): void { $results = $this->findBy(['hashKey' => $hash]); foreach ($results as $result) { $this->getEntityManager()->remove($result); } $this->getEntityManager()->flush(); }
[ "public", "function", "removeByHash", "(", "string", "$", "hash", ")", ":", "void", "{", "$", "results", "=", "$", "this", "->", "findBy", "(", "[", "'hashKey'", "=>", "$", "hash", "]", ")", ";", "foreach", "(", "$", "results", "as", "$", "result", ...
Removes user account key by user hash. @param string $hash
[ "Removes", "user", "account", "key", "by", "user", "hash", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Entity/Repository/EzUserAccountKeyRepository.php#L79-L88
train
spiral/core
src/ContainerScope.php
ContainerScope.runScope
public static function runScope(ContainerInterface $container, callable $scope) { list ($previous, self::$container) = [self::$container, $container]; try { return $scope(); } catch (\Throwable $e) { throw $e; } finally { self::$container = $previous; } }
php
public static function runScope(ContainerInterface $container, callable $scope) { list ($previous, self::$container) = [self::$container, $container]; try { return $scope(); } catch (\Throwable $e) { throw $e; } finally { self::$container = $previous; } }
[ "public", "static", "function", "runScope", "(", "ContainerInterface", "$", "container", ",", "callable", "$", "scope", ")", "{", "list", "(", "$", "previous", ",", "self", "::", "$", "container", ")", "=", "[", "self", "::", "$", "container", ",", "$", ...
Invokes given closure or function withing global IoC scope. @param ContainerInterface $container @param callable $scope @return mixed @throws \Throwable
[ "Invokes", "given", "closure", "or", "function", "withing", "global", "IoC", "scope", "." ]
02580dff7f1fcbc5e74caa1f78ea84c0e4c0d92e
https://github.com/spiral/core/blob/02580dff7f1fcbc5e74caa1f78ea84c0e4c0d92e/src/ContainerScope.php#L44-L54
train
smartboxgroup/integration-framework-bundle
Components/FileService/Csv/CsvConfigurableStepsProvider.php
CsvConfigurableStepsProvider.getFileHandle
protected function getFileHandle($fullPath, $mode) { $key = md5($fullPath.$mode); if (array_key_exists($key, $this->openFileHandles)) { $handle = $this->openFileHandles[$key]; } else { $handle = fopen($fullPath, $mode); $this->openFileHandles[$key] = $handle; } if ('stream' !== get_resource_type($handle)) { throw new \Exception('The file handle is not a file stream!'); } if (false !== strpos($mode, 'w')) { if ('stream' === !is_writeable($fullPath)) { throw new \Exception('The file handle in the context is not writeable!'); } } return $handle; }
php
protected function getFileHandle($fullPath, $mode) { $key = md5($fullPath.$mode); if (array_key_exists($key, $this->openFileHandles)) { $handle = $this->openFileHandles[$key]; } else { $handle = fopen($fullPath, $mode); $this->openFileHandles[$key] = $handle; } if ('stream' !== get_resource_type($handle)) { throw new \Exception('The file handle is not a file stream!'); } if (false !== strpos($mode, 'w')) { if ('stream' === !is_writeable($fullPath)) { throw new \Exception('The file handle in the context is not writeable!'); } } return $handle; }
[ "protected", "function", "getFileHandle", "(", "$", "fullPath", ",", "$", "mode", ")", "{", "$", "key", "=", "md5", "(", "$", "fullPath", ".", "$", "mode", ")", ";", "if", "(", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "openFileHan...
Open a file handle and store the hash so we can reuse it. @param $fullPath @param $mode @return resource @throws \Exception
[ "Open", "a", "file", "handle", "and", "store", "the", "hash", "so", "we", "can", "reuse", "it", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/FileService/Csv/CsvConfigurableStepsProvider.php#L69-L90
train
smartboxgroup/integration-framework-bundle
Components/FileService/Csv/CsvConfigurableStepsProvider.php
CsvConfigurableStepsProvider.writeToFile
protected function writeToFile(array &$stepActionParams, array &$endpointOptions, array &$context) { $stepParamsResolver = new OptionsResolver(); $stepParamsResolver->setRequired([ self::PARAM_FILE_NAME, self::PARAM_CSV_ROWS, ]); $params = $stepParamsResolver->resolve($stepActionParams); $filePath = $params[self::PARAM_FILE_NAME]; $fullPath = $this->getRootPath($endpointOptions).DIRECTORY_SEPARATOR.$filePath; $rows = $params[self::PARAM_CSV_ROWS]; //open the file, reset the pointer to zero, create it if not already created $fileHandle = fopen($fullPath, 'w'); foreach ($rows as $row) { if (!is_array($row)) { $type = gettype($row); throw new \InvalidArgumentException("Row in Rows is not an array, {$type} given."); } fputcsv($fileHandle, $row, $endpointOptions[CsvConfigurableProtocol::OPTION_DELIMITER], $endpointOptions[CsvConfigurableProtocol::OPTION_ENCLOSURE], $endpointOptions[CsvConfigurableProtocol::OPTION_ESCAPE_CHAR]); } fclose($fileHandle); }
php
protected function writeToFile(array &$stepActionParams, array &$endpointOptions, array &$context) { $stepParamsResolver = new OptionsResolver(); $stepParamsResolver->setRequired([ self::PARAM_FILE_NAME, self::PARAM_CSV_ROWS, ]); $params = $stepParamsResolver->resolve($stepActionParams); $filePath = $params[self::PARAM_FILE_NAME]; $fullPath = $this->getRootPath($endpointOptions).DIRECTORY_SEPARATOR.$filePath; $rows = $params[self::PARAM_CSV_ROWS]; //open the file, reset the pointer to zero, create it if not already created $fileHandle = fopen($fullPath, 'w'); foreach ($rows as $row) { if (!is_array($row)) { $type = gettype($row); throw new \InvalidArgumentException("Row in Rows is not an array, {$type} given."); } fputcsv($fileHandle, $row, $endpointOptions[CsvConfigurableProtocol::OPTION_DELIMITER], $endpointOptions[CsvConfigurableProtocol::OPTION_ENCLOSURE], $endpointOptions[CsvConfigurableProtocol::OPTION_ESCAPE_CHAR]); } fclose($fileHandle); }
[ "protected", "function", "writeToFile", "(", "array", "&", "$", "stepActionParams", ",", "array", "&", "$", "endpointOptions", ",", "array", "&", "$", "context", ")", "{", "$", "stepParamsResolver", "=", "new", "OptionsResolver", "(", ")", ";", "$", "stepPar...
Write rows out to a csv file. Required Params: - CsvConfigurableProducer::PARAM_CSV_ROWS Optional Params: - CsvConfigurableProducer::PARAM_FILE_NAME @param array $stepActionParams @param array $endpointOptions @param array $context
[ "Write", "rows", "out", "to", "a", "csv", "file", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/FileService/Csv/CsvConfigurableStepsProvider.php#L191-L218
train
smartboxgroup/integration-framework-bundle
Components/FileService/Csv/CsvConfigurableStepsProvider.php
CsvConfigurableStepsProvider.appendLines
protected function appendLines(array &$stepActionParams, array &$endpointOptions, array &$context) { $stepParamsResolver = new OptionsResolver(); $stepParamsResolver->setRequired([ self::PARAM_CSV_ROWS, ]); $stepParamsResolver->setDefault(self::PARAM_FILE_NAME, $endpointOptions[CsvConfigurableProtocol::OPTION_PATH]); $stepParamsResolver->setDefault(self::PARAM_HEADERS, null); $params = $stepParamsResolver->resolve($stepActionParams); $filePath = $params[self::PARAM_FILE_NAME]; $fullPath = $this->getRootPath($endpointOptions).DIRECTORY_SEPARATOR.$filePath; $rows = $params[self::PARAM_CSV_ROWS]; $headers = $params[self::PARAM_HEADERS]; if (is_array($headers) && !file_exists($fullPath)) { $rows = array_merge([$headers], $rows); } $fileHandle = $this->getFileHandle($fullPath, 'a'); foreach ($rows as $row) { if (!is_array($row)) { $type = gettype($row); throw new \InvalidArgumentException("Row in Rows is not an array, {$type} given."); } fputcsv($fileHandle, $row, $endpointOptions[CsvConfigurableProtocol::OPTION_DELIMITER], $endpointOptions[CsvConfigurableProtocol::OPTION_ENCLOSURE], $endpointOptions[CsvConfigurableProtocol::OPTION_ESCAPE_CHAR]); } }
php
protected function appendLines(array &$stepActionParams, array &$endpointOptions, array &$context) { $stepParamsResolver = new OptionsResolver(); $stepParamsResolver->setRequired([ self::PARAM_CSV_ROWS, ]); $stepParamsResolver->setDefault(self::PARAM_FILE_NAME, $endpointOptions[CsvConfigurableProtocol::OPTION_PATH]); $stepParamsResolver->setDefault(self::PARAM_HEADERS, null); $params = $stepParamsResolver->resolve($stepActionParams); $filePath = $params[self::PARAM_FILE_NAME]; $fullPath = $this->getRootPath($endpointOptions).DIRECTORY_SEPARATOR.$filePath; $rows = $params[self::PARAM_CSV_ROWS]; $headers = $params[self::PARAM_HEADERS]; if (is_array($headers) && !file_exists($fullPath)) { $rows = array_merge([$headers], $rows); } $fileHandle = $this->getFileHandle($fullPath, 'a'); foreach ($rows as $row) { if (!is_array($row)) { $type = gettype($row); throw new \InvalidArgumentException("Row in Rows is not an array, {$type} given."); } fputcsv($fileHandle, $row, $endpointOptions[CsvConfigurableProtocol::OPTION_DELIMITER], $endpointOptions[CsvConfigurableProtocol::OPTION_ENCLOSURE], $endpointOptions[CsvConfigurableProtocol::OPTION_ESCAPE_CHAR]); } }
[ "protected", "function", "appendLines", "(", "array", "&", "$", "stepActionParams", ",", "array", "&", "$", "endpointOptions", ",", "array", "&", "$", "context", ")", "{", "$", "stepParamsResolver", "=", "new", "OptionsResolver", "(", ")", ";", "$", "stepPar...
Write an array of lines to a csv file in to a context variable it is assumed the file handle is in the context. Required Params: - CsvConfigurableProducer::PARAM_CSV_ROWS @param array $stepActionParams @param array $endpointOptions @param array $context
[ "Write", "an", "array", "of", "lines", "to", "a", "csv", "file", "in", "to", "a", "context", "variable", "it", "is", "assumed", "the", "file", "handle", "is", "in", "the", "context", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/FileService/Csv/CsvConfigurableStepsProvider.php#L231-L261
train
smartboxgroup/integration-framework-bundle
Components/FileService/Csv/CsvConfigurableStepsProvider.php
CsvConfigurableStepsProvider.readFile
protected function readFile(array &$stepActionParams, array &$endpointOptions, array &$context) { $stepParamsResolver = new OptionsResolver(); $stepParamsResolver->setRequired([ self::PARAM_FILE_NAME, self::PARAM_CONTEXT_RESULT_NAME, ]); $params = $stepParamsResolver->resolve($stepActionParams); $filePath = $params[self::PARAM_FILE_NAME]; $fullPath = $this->getRootPath($endpointOptions).DIRECTORY_SEPARATOR.$filePath; $contextResultName = $params[self::PARAM_CONTEXT_RESULT_NAME]; $maxLineLength = $endpointOptions[CsvConfigurableProtocol::OPTION_MAX_LENGTH]; //open the file, reset the pointer to zero $fileHandle = fopen($fullPath, 'r'); $rows = []; while (false !== ($row = fgetcsv($fileHandle, $maxLineLength, $endpointOptions[CsvConfigurableProtocol::OPTION_DELIMITER]))) { $rows[] = $row; } fclose($fileHandle); $context[$contextResultName] = $rows; }
php
protected function readFile(array &$stepActionParams, array &$endpointOptions, array &$context) { $stepParamsResolver = new OptionsResolver(); $stepParamsResolver->setRequired([ self::PARAM_FILE_NAME, self::PARAM_CONTEXT_RESULT_NAME, ]); $params = $stepParamsResolver->resolve($stepActionParams); $filePath = $params[self::PARAM_FILE_NAME]; $fullPath = $this->getRootPath($endpointOptions).DIRECTORY_SEPARATOR.$filePath; $contextResultName = $params[self::PARAM_CONTEXT_RESULT_NAME]; $maxLineLength = $endpointOptions[CsvConfigurableProtocol::OPTION_MAX_LENGTH]; //open the file, reset the pointer to zero $fileHandle = fopen($fullPath, 'r'); $rows = []; while (false !== ($row = fgetcsv($fileHandle, $maxLineLength, $endpointOptions[CsvConfigurableProtocol::OPTION_DELIMITER]))) { $rows[] = $row; } fclose($fileHandle); $context[$contextResultName] = $rows; }
[ "protected", "function", "readFile", "(", "array", "&", "$", "stepActionParams", ",", "array", "&", "$", "endpointOptions", ",", "array", "&", "$", "context", ")", "{", "$", "stepParamsResolver", "=", "new", "OptionsResolver", "(", ")", ";", "$", "stepParams...
Read a csv file in to a context variable. Required Params: - CsvConfigurableProducer::PARAM_CONTEXT_RESULT_NAME Optional Params: - CsvConfigurableProducer::PARAM_FILE_NAME @param array $stepActionParams @param array $endpointOptions @param array $context
[ "Read", "a", "csv", "file", "in", "to", "a", "context", "variable", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/FileService/Csv/CsvConfigurableStepsProvider.php#L275-L302
train
smartboxgroup/integration-framework-bundle
Components/FileService/Csv/CsvConfigurableStepsProvider.php
CsvConfigurableStepsProvider.readLines
protected function readLines(array &$stepActionParams, array &$endpointOptions, array &$context) { $stepParamsResolver = new OptionsResolver(); $stepParamsResolver->setRequired([ self::PARAM_CONTEXT_RESULT_NAME, ]); $stepParamsResolver->setDefault(self::PARAM_MAX_LINES, 1); $stepParamsResolver->setDefault(self::PARAM_FILE_NAME, null); $params = $stepParamsResolver->resolve($stepActionParams); $fullPath = $this->getRootPath($endpointOptions); if (null !== $params[self::PARAM_FILE_NAME]) { if (DIRECTORY_SEPARATOR !== substr($fullPath, -1)) { $fullPath .= DIRECTORY_SEPARATOR; } $fullPath .= $params[self::PARAM_FILE_NAME]; } $fileHandle = $this->getFileHandle($fullPath, 'r'); $contextResultName = $params[self::PARAM_CONTEXT_RESULT_NAME]; $maxLines = $params[self::PARAM_MAX_LINES]; $maxLineLength = $endpointOptions[CsvConfigurableProtocol::OPTION_MAX_LENGTH]; $rows = []; $i = 0; while ($i < $maxLines) { $row = fgetcsv($fileHandle, $maxLineLength, $endpointOptions[CsvConfigurableProtocol::OPTION_DELIMITER]); if (false === $row) { break; } $rows[] = $row; ++$i; } if (0 === count($rows)) { throw new NoResultsException("No more results from $fullPath"); } $context[self::KEY_RESULTS][$contextResultName] = $rows; }
php
protected function readLines(array &$stepActionParams, array &$endpointOptions, array &$context) { $stepParamsResolver = new OptionsResolver(); $stepParamsResolver->setRequired([ self::PARAM_CONTEXT_RESULT_NAME, ]); $stepParamsResolver->setDefault(self::PARAM_MAX_LINES, 1); $stepParamsResolver->setDefault(self::PARAM_FILE_NAME, null); $params = $stepParamsResolver->resolve($stepActionParams); $fullPath = $this->getRootPath($endpointOptions); if (null !== $params[self::PARAM_FILE_NAME]) { if (DIRECTORY_SEPARATOR !== substr($fullPath, -1)) { $fullPath .= DIRECTORY_SEPARATOR; } $fullPath .= $params[self::PARAM_FILE_NAME]; } $fileHandle = $this->getFileHandle($fullPath, 'r'); $contextResultName = $params[self::PARAM_CONTEXT_RESULT_NAME]; $maxLines = $params[self::PARAM_MAX_LINES]; $maxLineLength = $endpointOptions[CsvConfigurableProtocol::OPTION_MAX_LENGTH]; $rows = []; $i = 0; while ($i < $maxLines) { $row = fgetcsv($fileHandle, $maxLineLength, $endpointOptions[CsvConfigurableProtocol::OPTION_DELIMITER]); if (false === $row) { break; } $rows[] = $row; ++$i; } if (0 === count($rows)) { throw new NoResultsException("No more results from $fullPath"); } $context[self::KEY_RESULTS][$contextResultName] = $rows; }
[ "protected", "function", "readLines", "(", "array", "&", "$", "stepActionParams", ",", "array", "&", "$", "endpointOptions", ",", "array", "&", "$", "context", ")", "{", "$", "stepParamsResolver", "=", "new", "OptionsResolver", "(", ")", ";", "$", "stepParam...
Read a line from a csv file in to a context variable it is assumed the file handle is in the context. Required Params: - CsvConfigurableProducer::PARAM_CONTEXT_RESULT_NAME Optional Params: - CsvConfigurableProducer::PARAM_MAX_LINES Defaults to 1 @param array $stepActionParams @param array $endpointOptions @param array $context @throws NoResultsException if there are no more lines to consume
[ "Read", "a", "line", "from", "a", "csv", "file", "in", "to", "a", "context", "variable", "it", "is", "assumed", "the", "file", "handle", "is", "in", "the", "context", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/FileService/Csv/CsvConfigurableStepsProvider.php#L319-L363
train
smartboxgroup/integration-framework-bundle
Components/FileService/Csv/CsvConfigurableStepsProvider.php
CsvConfigurableStepsProvider.copyFile
protected function copyFile(array &$stepActionParams, array &$endpointOptions, array &$context) { $rootPath = $this->getRootPath($endpointOptions, $stepActionParams); $stepParamsResolver = new OptionsResolver(); $stepParamsResolver->setRequired([ self::PARAM_FILE_NAME, self::PARAM_NEW_FILE_PATH, ]); $params = $stepParamsResolver->resolve($stepActionParams); $newFilePath = $params[self::PARAM_NEW_FILE_PATH]; $newFullPath = $rootPath.DIRECTORY_SEPARATOR.$newFilePath; $originalFilePath = $params[self::PARAM_FILE_NAME]; $originalFullPath = $rootPath.DIRECTORY_SEPARATOR.$originalFilePath; copy($originalFullPath, $newFullPath); }
php
protected function copyFile(array &$stepActionParams, array &$endpointOptions, array &$context) { $rootPath = $this->getRootPath($endpointOptions, $stepActionParams); $stepParamsResolver = new OptionsResolver(); $stepParamsResolver->setRequired([ self::PARAM_FILE_NAME, self::PARAM_NEW_FILE_PATH, ]); $params = $stepParamsResolver->resolve($stepActionParams); $newFilePath = $params[self::PARAM_NEW_FILE_PATH]; $newFullPath = $rootPath.DIRECTORY_SEPARATOR.$newFilePath; $originalFilePath = $params[self::PARAM_FILE_NAME]; $originalFullPath = $rootPath.DIRECTORY_SEPARATOR.$originalFilePath; copy($originalFullPath, $newFullPath); }
[ "protected", "function", "copyFile", "(", "array", "&", "$", "stepActionParams", ",", "array", "&", "$", "endpointOptions", ",", "array", "&", "$", "context", ")", "{", "$", "rootPath", "=", "$", "this", "->", "getRootPath", "(", "$", "endpointOptions", ",...
Copy a file for this producer. Required Params: - CsvConfigurableProducer::PARAM_NEW_FILE_PATH Optional Params: - CsvConfigurableProducer::PARAM_FILE_NAME @param array $stepActionParams @param array $endpointOptions @param array $context
[ "Copy", "a", "file", "for", "this", "producer", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/FileService/Csv/CsvConfigurableStepsProvider.php#L424-L442
train
smartboxgroup/integration-framework-bundle
Components/FileService/Csv/CsvConfigurableStepsProvider.php
CsvConfigurableStepsProvider.createFile
protected function createFile(array &$stepActionParams, array &$endpointOptions, array &$context) { $fullPath = $this->getFullPath($endpointOptions, $stepActionParams); $fileHandle = fopen($fullPath, 'w'); fclose($fileHandle); }
php
protected function createFile(array &$stepActionParams, array &$endpointOptions, array &$context) { $fullPath = $this->getFullPath($endpointOptions, $stepActionParams); $fileHandle = fopen($fullPath, 'w'); fclose($fileHandle); }
[ "protected", "function", "createFile", "(", "array", "&", "$", "stepActionParams", ",", "array", "&", "$", "endpointOptions", ",", "array", "&", "$", "context", ")", "{", "$", "fullPath", "=", "$", "this", "->", "getFullPath", "(", "$", "endpointOptions", ...
Create a new blank file. Required Params: - CsvConfigurableProducer::PARAM_NEW_FILE_PATH Optional Params: - CsvConfigurableProducer::PARAM_FILE_NAME @param array $stepActionParams @param array $endpointOptions @param array $context
[ "Create", "a", "new", "blank", "file", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/FileService/Csv/CsvConfigurableStepsProvider.php#L456-L462
train
smartboxgroup/integration-framework-bundle
Components/FileService/Csv/CsvConfigurableStepsProvider.php
CsvConfigurableStepsProvider.getFilePath
protected function getFilePath(array $endpointOptions, $stepActionParams) { if (array_key_exists(self::PARAM_FILE_NAME, $stepActionParams)) { return $stepActionParams[self::PARAM_FILE_NAME]; } else { return $endpointOptions[CsvConfigurableProtocol::OPTION_PATH]; } }
php
protected function getFilePath(array $endpointOptions, $stepActionParams) { if (array_key_exists(self::PARAM_FILE_NAME, $stepActionParams)) { return $stepActionParams[self::PARAM_FILE_NAME]; } else { return $endpointOptions[CsvConfigurableProtocol::OPTION_PATH]; } }
[ "protected", "function", "getFilePath", "(", "array", "$", "endpointOptions", ",", "$", "stepActionParams", ")", "{", "if", "(", "array_key_exists", "(", "self", "::", "PARAM_FILE_NAME", ",", "$", "stepActionParams", ")", ")", "{", "return", "$", "stepActionPara...
Resolve the file path from the configuration use the configured default path if none is set. @param array $endpointOptions @param array $stepActionParams @return string The file path to the file as in the configuration
[ "Resolve", "the", "file", "path", "from", "the", "configuration", "use", "the", "configured", "default", "path", "if", "none", "is", "set", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/FileService/Csv/CsvConfigurableStepsProvider.php#L485-L492
train
smartboxgroup/integration-framework-bundle
Components/FileService/Csv/CsvConfigurableStepsProvider.php
CsvConfigurableStepsProvider.getFullPath
protected function getFullPath(array $endpointOptions, $stepActionParams) { return $this->getRootPath($endpointOptions).DIRECTORY_SEPARATOR.$this->getFilePath($endpointOptions, $stepActionParams); }
php
protected function getFullPath(array $endpointOptions, $stepActionParams) { return $this->getRootPath($endpointOptions).DIRECTORY_SEPARATOR.$this->getFilePath($endpointOptions, $stepActionParams); }
[ "protected", "function", "getFullPath", "(", "array", "$", "endpointOptions", ",", "$", "stepActionParams", ")", "{", "return", "$", "this", "->", "getRootPath", "(", "$", "endpointOptions", ")", ".", "DIRECTORY_SEPARATOR", ".", "$", "this", "->", "getFilePath",...
resolve the full path to the file in the configuration. @param array $endpointOptions @param array $stepActionParams @return string A full path to the file from the configuration
[ "resolve", "the", "full", "path", "to", "the", "file", "in", "the", "configuration", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/FileService/Csv/CsvConfigurableStepsProvider.php#L502-L505
train
netgen/site-bundle
bundle/EventListener/NoViewTemplateEventListener.php
NoViewTemplateEventListener.getController
public function getController(FilterControllerEvent $event): void { if (!$this->enabled || $event->getRequestType() !== Kernel::MASTER_REQUEST) { return; } $request = $event->getRequest(); $view = $request->attributes->get('view'); if (!$view instanceof View || $view->getViewType() !== 'full') { return; } if (is_string($view->getTemplateIdentifier())) { return; } $event->setController( function (): RedirectResponse { $rootLocationId = $this->configResolver->getParameter('content.tree_root.location_id'); return new RedirectResponse( $this->urlGenerator->generate('ez_urlalias', ['locationId' => $rootLocationId]), RedirectResponse::HTTP_MOVED_PERMANENTLY ); } ); }
php
public function getController(FilterControllerEvent $event): void { if (!$this->enabled || $event->getRequestType() !== Kernel::MASTER_REQUEST) { return; } $request = $event->getRequest(); $view = $request->attributes->get('view'); if (!$view instanceof View || $view->getViewType() !== 'full') { return; } if (is_string($view->getTemplateIdentifier())) { return; } $event->setController( function (): RedirectResponse { $rootLocationId = $this->configResolver->getParameter('content.tree_root.location_id'); return new RedirectResponse( $this->urlGenerator->generate('ez_urlalias', ['locationId' => $rootLocationId]), RedirectResponse::HTTP_MOVED_PERMANENTLY ); } ); }
[ "public", "function", "getController", "(", "FilterControllerEvent", "$", "event", ")", ":", "void", "{", "if", "(", "!", "$", "this", "->", "enabled", "||", "$", "event", "->", "getRequestType", "(", ")", "!==", "Kernel", "::", "MASTER_REQUEST", ")", "{",...
Redirects to the frontpage for any full view that does not have a template configured.
[ "Redirects", "to", "the", "frontpage", "for", "any", "full", "view", "that", "does", "not", "have", "a", "template", "configured", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/EventListener/NoViewTemplateEventListener.php#L56-L83
train
spiral/router
src/UriHandler.php
UriHandler.match
public function match(UriInterface $uri, array $defaults): ?array { if (!$this->isCompiled()) { $this->compile(); } $matches = []; if (!preg_match($this->compiled, $this->fetchTarget($uri), $matches)) { return null; } $matches = array_intersect_key($matches, $this->options); return array_merge($this->options, $defaults, $matches); }
php
public function match(UriInterface $uri, array $defaults): ?array { if (!$this->isCompiled()) { $this->compile(); } $matches = []; if (!preg_match($this->compiled, $this->fetchTarget($uri), $matches)) { return null; } $matches = array_intersect_key($matches, $this->options); return array_merge($this->options, $defaults, $matches); }
[ "public", "function", "match", "(", "UriInterface", "$", "uri", ",", "array", "$", "defaults", ")", ":", "?", "array", "{", "if", "(", "!", "$", "this", "->", "isCompiled", "(", ")", ")", "{", "$", "this", "->", "compile", "(", ")", ";", "}", "$"...
Match given url against compiled template and return matches array or null if pattern does not match. @param UriInterface $uri @param array $defaults @return array|null
[ "Match", "given", "url", "against", "compiled", "template", "and", "return", "matches", "array", "or", "null", "if", "pattern", "does", "not", "match", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/UriHandler.php#L116-L130
train
spiral/router
src/UriHandler.php
UriHandler.uri
public function uri($parameters = [], array $defaults = []): UriInterface { if (!$this->isCompiled()) { $this->compile(); } $parameters = array_merge( $this->options, $defaults, $this->fetchOptions($parameters, $query) ); foreach ($this->constrains as $key => $values) { if (empty($parameters[$key])) { throw new UriHandlerException("Unable to generate Uri, parameter `{$key}` is missing."); } } //Uri without empty blocks (pretty stupid implementation) $path = $this->interpolate($this->template, $parameters); //Uri with added prefix $uri = new Uri(($this->matchHost ? '' : $this->prefix) . trim($path, '/')); return empty($query) ? $uri : $uri->withQuery(http_build_query($query)); }
php
public function uri($parameters = [], array $defaults = []): UriInterface { if (!$this->isCompiled()) { $this->compile(); } $parameters = array_merge( $this->options, $defaults, $this->fetchOptions($parameters, $query) ); foreach ($this->constrains as $key => $values) { if (empty($parameters[$key])) { throw new UriHandlerException("Unable to generate Uri, parameter `{$key}` is missing."); } } //Uri without empty blocks (pretty stupid implementation) $path = $this->interpolate($this->template, $parameters); //Uri with added prefix $uri = new Uri(($this->matchHost ? '' : $this->prefix) . trim($path, '/')); return empty($query) ? $uri : $uri->withQuery(http_build_query($query)); }
[ "public", "function", "uri", "(", "$", "parameters", "=", "[", "]", ",", "array", "$", "defaults", "=", "[", "]", ")", ":", "UriInterface", "{", "if", "(", "!", "$", "this", "->", "isCompiled", "(", ")", ")", "{", "$", "this", "->", "compile", "(...
Generate Uri for a given parameters and default values. @param array|\Traversable $parameters @param array $defaults @return UriInterface
[ "Generate", "Uri", "for", "a", "given", "parameters", "and", "default", "values", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/UriHandler.php#L139-L164
train
spiral/router
src/UriHandler.php
UriHandler.fetchOptions
private function fetchOptions($parameters, &$query): array { $allowed = array_keys($this->options); $result = []; foreach ($parameters as $key => $parameter) { if (is_numeric($key) && isset($allowed[$key])) { // this segment fetched keys from given parameters either by name or by position $key = $allowed[$key]; } elseif (!array_key_exists($key, $this->options) && is_array($parameters)) { // all additional parameters given in array form can be glued to query string $query[$key] = $parameter; continue; } //String must be normalized here if (is_string($parameter) && !preg_match('/^[a-z\-_0-9]+$/i', $parameter)) { $result[$key] = $this->slugify->slugify($parameter); continue; } $result[$key] = (string)$parameter; } return $result; }
php
private function fetchOptions($parameters, &$query): array { $allowed = array_keys($this->options); $result = []; foreach ($parameters as $key => $parameter) { if (is_numeric($key) && isset($allowed[$key])) { // this segment fetched keys from given parameters either by name or by position $key = $allowed[$key]; } elseif (!array_key_exists($key, $this->options) && is_array($parameters)) { // all additional parameters given in array form can be glued to query string $query[$key] = $parameter; continue; } //String must be normalized here if (is_string($parameter) && !preg_match('/^[a-z\-_0-9]+$/i', $parameter)) { $result[$key] = $this->slugify->slugify($parameter); continue; } $result[$key] = (string)$parameter; } return $result; }
[ "private", "function", "fetchOptions", "(", "$", "parameters", ",", "&", "$", "query", ")", ":", "array", "{", "$", "allowed", "=", "array_keys", "(", "$", "this", "->", "options", ")", ";", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "...
Fetch uri segments and query parameters. @param \Traversable|array $parameters @param array|null $query Query parameters. @return array
[ "Fetch", "uri", "segments", "and", "query", "parameters", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/UriHandler.php#L173-L198
train
spiral/router
src/UriHandler.php
UriHandler.fetchTarget
private function fetchTarget(UriInterface $uri): string { $path = $uri->getPath(); if (empty($path) || $path[0] !== '/') { $path = '/' . $path; } if ($this->matchHost) { $uri = $uri->getHost() . $path; } else { $uri = substr($path, strlen($this->prefix)); } return trim($uri, '/'); }
php
private function fetchTarget(UriInterface $uri): string { $path = $uri->getPath(); if (empty($path) || $path[0] !== '/') { $path = '/' . $path; } if ($this->matchHost) { $uri = $uri->getHost() . $path; } else { $uri = substr($path, strlen($this->prefix)); } return trim($uri, '/'); }
[ "private", "function", "fetchTarget", "(", "UriInterface", "$", "uri", ")", ":", "string", "{", "$", "path", "=", "$", "uri", "->", "getPath", "(", ")", ";", "if", "(", "empty", "(", "$", "path", ")", "||", "$", "path", "[", "0", "]", "!==", "'/'...
Part of uri path which is being matched. @param UriInterface $uri @return string
[ "Part", "of", "uri", "path", "which", "is", "being", "matched", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/UriHandler.php#L206-L221
train
spiral/router
src/UriHandler.php
UriHandler.compile
private function compile() { $options = $replaces = []; $pattern = rtrim(ltrim($this->pattern, ':/'), '/'); // correct [/ first occurrence] if (strpos($pattern, '[/') === 0) { $pattern = '[' . substr($pattern, 2); } if (preg_match_all('/<(\w+):?(.*?)?>/', $pattern, $matches)) { $variables = array_combine($matches[1], $matches[2]); foreach ($variables as $key => $segment) { $segment = $this->prepareSegment($key, $segment); $replaces["<$key>"] = "(?P<$key>$segment)"; $options[] = $key; } } $template = preg_replace('/<(\w+):?.*?>/', '<\1>', $pattern); $options = array_fill_keys($options, null); foreach ($this->constrains as $key => $value) { if ($value instanceof Autofill) { // only forces value replacement, not required to be presented as parameter continue; } if (!array_key_exists($key, $options)) { throw new ConstrainException(sprintf( "Route `%s` does not define routing parameter `<%s>`.", $this->pattern, $key )); } } $this->compiled = '/^' . strtr($template, $replaces + self::PATTERN_REPLACES) . '$/iu'; $this->template = stripslashes(str_replace('?', '', $template)); $this->options = $options; }
php
private function compile() { $options = $replaces = []; $pattern = rtrim(ltrim($this->pattern, ':/'), '/'); // correct [/ first occurrence] if (strpos($pattern, '[/') === 0) { $pattern = '[' . substr($pattern, 2); } if (preg_match_all('/<(\w+):?(.*?)?>/', $pattern, $matches)) { $variables = array_combine($matches[1], $matches[2]); foreach ($variables as $key => $segment) { $segment = $this->prepareSegment($key, $segment); $replaces["<$key>"] = "(?P<$key>$segment)"; $options[] = $key; } } $template = preg_replace('/<(\w+):?.*?>/', '<\1>', $pattern); $options = array_fill_keys($options, null); foreach ($this->constrains as $key => $value) { if ($value instanceof Autofill) { // only forces value replacement, not required to be presented as parameter continue; } if (!array_key_exists($key, $options)) { throw new ConstrainException(sprintf( "Route `%s` does not define routing parameter `<%s>`.", $this->pattern, $key )); } } $this->compiled = '/^' . strtr($template, $replaces + self::PATTERN_REPLACES) . '$/iu'; $this->template = stripslashes(str_replace('?', '', $template)); $this->options = $options; }
[ "private", "function", "compile", "(", ")", "{", "$", "options", "=", "$", "replaces", "=", "[", "]", ";", "$", "pattern", "=", "rtrim", "(", "ltrim", "(", "$", "this", "->", "pattern", ",", "':/'", ")", ",", "'/'", ")", ";", "// correct [/ first occ...
Compile route matcher into regexp.
[ "Compile", "route", "matcher", "into", "regexp", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/UriHandler.php#L226-L267
train
spiral/router
src/UriHandler.php
UriHandler.interpolate
private function interpolate(string $string, array $values): string { $replaces = []; foreach ($values as $key => $value) { $value = (is_array($value) || $value instanceof \Closure) ? '' : $value; $replaces["<{$key}>"] = is_object($value) ? (string)$value : $value; } return strtr($string, $replaces + self::URI_FIXERS); }
php
private function interpolate(string $string, array $values): string { $replaces = []; foreach ($values as $key => $value) { $value = (is_array($value) || $value instanceof \Closure) ? '' : $value; $replaces["<{$key}>"] = is_object($value) ? (string)$value : $value; } return strtr($string, $replaces + self::URI_FIXERS); }
[ "private", "function", "interpolate", "(", "string", "$", "string", ",", "array", "$", "values", ")", ":", "string", "{", "$", "replaces", "=", "[", "]", ";", "foreach", "(", "$", "values", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "valu...
Interpolate string with given values. @param string $string @param array $values @return string
[ "Interpolate", "string", "with", "given", "values", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/UriHandler.php#L276-L285
train
spiral/router
src/UriHandler.php
UriHandler.prepareSegment
private function prepareSegment(string $name, string $segment): string { if (!empty($segment)) { return $this->filterSegment($segment); } if (!isset($this->constrains[$name])) { return self::DEFAULT_SEGMENT; } if (is_array($this->constrains[$name])) { $values = array_map([$this, 'filterSegment'], $this->constrains[$name]); return join('|', $values); } return $this->filterSegment((string)$this->constrains[$name]); }
php
private function prepareSegment(string $name, string $segment): string { if (!empty($segment)) { return $this->filterSegment($segment); } if (!isset($this->constrains[$name])) { return self::DEFAULT_SEGMENT; } if (is_array($this->constrains[$name])) { $values = array_map([$this, 'filterSegment'], $this->constrains[$name]); return join('|', $values); } return $this->filterSegment((string)$this->constrains[$name]); }
[ "private", "function", "prepareSegment", "(", "string", "$", "name", ",", "string", "$", "segment", ")", ":", "string", "{", "if", "(", "!", "empty", "(", "$", "segment", ")", ")", "{", "return", "$", "this", "->", "filterSegment", "(", "$", "segment",...
Prepares segment pattern with given constrains. @param string $name @param string $segment @return string
[ "Prepares", "segment", "pattern", "with", "given", "constrains", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/UriHandler.php#L294-L311
train
adminarchitect/options
src/Terranet/Options/Drivers/EloquentOptionsDriver.php
EloquentOptionsDriver.find
public function find($name, $default = null) { return ($options = $this->fetchAll()->lists('value', 'key')) && $options->has($name) ? $options->get($name) : $default; }
php
public function find($name, $default = null) { return ($options = $this->fetchAll()->lists('value', 'key')) && $options->has($name) ? $options->get($name) : $default; }
[ "public", "function", "find", "(", "$", "name", ",", "$", "default", "=", "null", ")", "{", "return", "(", "$", "options", "=", "$", "this", "->", "fetchAll", "(", ")", "->", "lists", "(", "'value'", ",", "'key'", ")", ")", "&&", "$", "options", ...
Find an option by name. @param $name @param $default @return mixed
[ "Find", "an", "option", "by", "name", "." ]
b3b43dc3bfc34710143c8e34a79603e925f07fd2
https://github.com/adminarchitect/options/blob/b3b43dc3bfc34710143c8e34a79603e925f07fd2/src/Terranet/Options/Drivers/EloquentOptionsDriver.php#L34-L39
train
adminarchitect/options
src/Terranet/Options/Drivers/EloquentOptionsDriver.php
EloquentOptionsDriver.create
public function create($key, $value, $group = Manager::DEFAULT_GROUP) { return $this->createModel()->create([ 'key' => $key, 'value' => $value, 'group' => $group, ]); }
php
public function create($key, $value, $group = Manager::DEFAULT_GROUP) { return $this->createModel()->create([ 'key' => $key, 'value' => $value, 'group' => $group, ]); }
[ "public", "function", "create", "(", "$", "key", ",", "$", "value", ",", "$", "group", "=", "Manager", "::", "DEFAULT_GROUP", ")", "{", "return", "$", "this", "->", "createModel", "(", ")", "->", "create", "(", "[", "'key'", "=>", "$", "key", ",", ...
Create new option. @param string $key @param string $value @param string $group @return \Illuminate\Database\Eloquent\Model|$this
[ "Create", "new", "option", "." ]
b3b43dc3bfc34710143c8e34a79603e925f07fd2
https://github.com/adminarchitect/options/blob/b3b43dc3bfc34710143c8e34a79603e925f07fd2/src/Terranet/Options/Drivers/EloquentOptionsDriver.php#L103-L110
train
netgen/site-bundle
bundle/EventListener/User/PostRegisterEventListener.php
PostRegisterEventListener.onUserRegistered
public function onUserRegistered(PostRegisterEvent $event): void { $user = $event->getUser(); if ($user->enabled) { $this->mailHelper ->sendMail( [$user->email => $this->getUserName($user)], 'ngsite.user.welcome.subject', $this->configResolver->getParameter('template.user.mail.welcome', 'ngsite'), [ 'user' => $user, ] ); return; } $accountKey = $this->ezUserAccountKeyRepository->create($user->id); if ($this->configResolver->getParameter('user.require_admin_activation', 'ngsite')) { $this->mailHelper ->sendMail( [$user->email => $this->getUserName($user)], 'ngsite.user.activate.admin_activation_pending.subject', $this->configResolver->getParameter('template.user.mail.activate_admin_activation_pending', 'ngsite'), [ 'user' => $user, ] ); $adminEmail = $this->configResolver->getParameter('user.mail.admin_email', 'ngsite'); $adminName = $this->configResolver->getParameter('user.mail.admin_name', 'ngsite'); if (!empty($adminEmail)) { $this->mailHelper ->sendMail( !empty($adminName) ? [$adminEmail => $adminName] : [$adminEmail], 'ngsite.user.activate.admin_activation_required.subject', $this->configResolver->getParameter('template.user.mail.activate_admin_activation_required', 'ngsite'), [ 'user' => $user, ] ); } return; } $this->mailHelper ->sendMail( [$user->email => $this->getUserName($user)], 'ngsite.user.activate.subject', $this->configResolver->getParameter('template.user.mail.activate', 'ngsite'), [ 'user' => $user, 'hash' => $accountKey->getHash(), ] ); }
php
public function onUserRegistered(PostRegisterEvent $event): void { $user = $event->getUser(); if ($user->enabled) { $this->mailHelper ->sendMail( [$user->email => $this->getUserName($user)], 'ngsite.user.welcome.subject', $this->configResolver->getParameter('template.user.mail.welcome', 'ngsite'), [ 'user' => $user, ] ); return; } $accountKey = $this->ezUserAccountKeyRepository->create($user->id); if ($this->configResolver->getParameter('user.require_admin_activation', 'ngsite')) { $this->mailHelper ->sendMail( [$user->email => $this->getUserName($user)], 'ngsite.user.activate.admin_activation_pending.subject', $this->configResolver->getParameter('template.user.mail.activate_admin_activation_pending', 'ngsite'), [ 'user' => $user, ] ); $adminEmail = $this->configResolver->getParameter('user.mail.admin_email', 'ngsite'); $adminName = $this->configResolver->getParameter('user.mail.admin_name', 'ngsite'); if (!empty($adminEmail)) { $this->mailHelper ->sendMail( !empty($adminName) ? [$adminEmail => $adminName] : [$adminEmail], 'ngsite.user.activate.admin_activation_required.subject', $this->configResolver->getParameter('template.user.mail.activate_admin_activation_required', 'ngsite'), [ 'user' => $user, ] ); } return; } $this->mailHelper ->sendMail( [$user->email => $this->getUserName($user)], 'ngsite.user.activate.subject', $this->configResolver->getParameter('template.user.mail.activate', 'ngsite'), [ 'user' => $user, 'hash' => $accountKey->getHash(), ] ); }
[ "public", "function", "onUserRegistered", "(", "PostRegisterEvent", "$", "event", ")", ":", "void", "{", "$", "user", "=", "$", "event", "->", "getUser", "(", ")", ";", "if", "(", "$", "user", "->", "enabled", ")", "{", "$", "this", "->", "mailHelper",...
Listens to the event triggered after the user has been registered. The event contains information about registered user.
[ "Listens", "to", "the", "event", "triggered", "after", "the", "user", "has", "been", "registered", ".", "The", "event", "contains", "information", "about", "registered", "user", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/EventListener/User/PostRegisterEventListener.php#L30-L89
train
netgen/site-bundle
bundle/Routing/SiteLocationUrlAliasRouter.php
SiteLocationUrlAliasRouter.generate
public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH): string { if (!$name instanceof Location) { throw new RouteNotFoundException('Could not match route'); } return $this->generator->generate( $name->innerLocation, $parameters, $referenceType ); }
php
public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH): string { if (!$name instanceof Location) { throw new RouteNotFoundException('Could not match route'); } return $this->generator->generate( $name->innerLocation, $parameters, $referenceType ); }
[ "public", "function", "generate", "(", "$", "name", ",", "$", "parameters", "=", "[", "]", ",", "$", "referenceType", "=", "self", "::", "ABSOLUTE_PATH", ")", ":", "string", "{", "if", "(", "!", "$", "name", "instanceof", "Location", ")", "{", "throw",...
Generates a URL for Site API Location object, from the given parameters. @param mixed $name @param mixed $parameters @param mixed $referenceType
[ "Generates", "a", "URL", "for", "Site", "API", "Location", "object", "from", "the", "given", "parameters", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Routing/SiteLocationUrlAliasRouter.php#L50-L61
train
spiral/core
src/Container.php
Container.hasInjector
public function hasInjector(\ReflectionClass $reflection): bool { if (isset($this->injectors[$reflection->getName()])) { return true; } //Auto injection! return $reflection->isSubclassOf(InjectableInterface::class); }
php
public function hasInjector(\ReflectionClass $reflection): bool { if (isset($this->injectors[$reflection->getName()])) { return true; } //Auto injection! return $reflection->isSubclassOf(InjectableInterface::class); }
[ "public", "function", "hasInjector", "(", "\\", "ReflectionClass", "$", "reflection", ")", ":", "bool", "{", "if", "(", "isset", "(", "$", "this", "->", "injectors", "[", "$", "reflection", "->", "getName", "(", ")", "]", ")", ")", "{", "return", "true...
Check if given class has associated injector. @param \ReflectionClass $reflection @return bool
[ "Check", "if", "given", "class", "has", "associated", "injector", "." ]
02580dff7f1fcbc5e74caa1f78ea84c0e4c0d92e
https://github.com/spiral/core/blob/02580dff7f1fcbc5e74caa1f78ea84c0e4c0d92e/src/Container.php#L338-L346
train
spiral/core
src/Container.php
Container.registerInstance
protected function registerInstance($instance, array $parameters) { //Declarative singletons (only when class received via direct get) if (empty($parameters) && $instance instanceof SingletonInterface) { $alias = get_class($instance); if (!isset($this->bindings[$alias])) { $this->bindings[$alias] = $instance; } } //Your code can go here (for example LoggerAwareInterface, custom hydration and etc) return $instance; }
php
protected function registerInstance($instance, array $parameters) { //Declarative singletons (only when class received via direct get) if (empty($parameters) && $instance instanceof SingletonInterface) { $alias = get_class($instance); if (!isset($this->bindings[$alias])) { $this->bindings[$alias] = $instance; } } //Your code can go here (for example LoggerAwareInterface, custom hydration and etc) return $instance; }
[ "protected", "function", "registerInstance", "(", "$", "instance", ",", "array", "$", "parameters", ")", "{", "//Declarative singletons (only when class received via direct get)", "if", "(", "empty", "(", "$", "parameters", ")", "&&", "$", "instance", "instanceof", "S...
Register instance in container, might perform methods like auto-singletons, log populations and etc. Can be extended. @param object $instance Created object. @param array $parameters Parameters which been passed with created instance. @return object
[ "Register", "instance", "in", "container", "might", "perform", "methods", "like", "auto", "-", "singletons", "log", "populations", "and", "etc", ".", "Can", "be", "extended", "." ]
02580dff7f1fcbc5e74caa1f78ea84c0e4c0d92e
https://github.com/spiral/core/blob/02580dff7f1fcbc5e74caa1f78ea84c0e4c0d92e/src/Container.php#L436-L450
train
spiral/core
src/Container.php
Container.getInjector
private function getInjector(\ReflectionClass $reflection): InjectorInterface { if (isset($this->injectors[$reflection->getName()])) { //Stated directly $injector = $this->get($this->injectors[$reflection->getName()]); } else { //Auto-injection! $injector = $this->get($reflection->getConstant('INJECTOR')); } if (!$injector instanceof InjectorInterface) { throw new InjectionException(sprintf( "Class '%s' must be an instance of InjectorInterface for '%s'", get_class($injector), $reflection->getName() )); } return $injector; }
php
private function getInjector(\ReflectionClass $reflection): InjectorInterface { if (isset($this->injectors[$reflection->getName()])) { //Stated directly $injector = $this->get($this->injectors[$reflection->getName()]); } else { //Auto-injection! $injector = $this->get($reflection->getConstant('INJECTOR')); } if (!$injector instanceof InjectorInterface) { throw new InjectionException(sprintf( "Class '%s' must be an instance of InjectorInterface for '%s'", get_class($injector), $reflection->getName() )); } return $injector; }
[ "private", "function", "getInjector", "(", "\\", "ReflectionClass", "$", "reflection", ")", ":", "InjectorInterface", "{", "if", "(", "isset", "(", "$", "this", "->", "injectors", "[", "$", "reflection", "->", "getName", "(", ")", "]", ")", ")", "{", "//...
Get injector associated with given class. @param \ReflectionClass $reflection @return InjectorInterface
[ "Get", "injector", "associated", "with", "given", "class", "." ]
02580dff7f1fcbc5e74caa1f78ea84c0e4c0d92e
https://github.com/spiral/core/blob/02580dff7f1fcbc5e74caa1f78ea84c0e4c0d92e/src/Container.php#L570-L589
train
spiral/core
src/Container.php
Container.assertType
private function assertType( \ReflectionParameter $parameter, \ReflectionFunctionAbstract $context, $value ) { if (is_null($value)) { if ( !$parameter->isOptional() && !($parameter->isDefaultValueAvailable() && $parameter->getDefaultValue() === null) ) { throw new ArgumentException($parameter, $context); } return; } $type = $parameter->getType(); if ($type == 'array' && !is_array($value)) { throw new ArgumentException($parameter, $context); } if (($type == 'int' || $type == 'float') && !is_numeric($value)) { throw new ArgumentException($parameter, $context); } if ($type == 'bool' && !is_bool($value) && !is_numeric($value)) { throw new ArgumentException($parameter, $context); } }
php
private function assertType( \ReflectionParameter $parameter, \ReflectionFunctionAbstract $context, $value ) { if (is_null($value)) { if ( !$parameter->isOptional() && !($parameter->isDefaultValueAvailable() && $parameter->getDefaultValue() === null) ) { throw new ArgumentException($parameter, $context); } return; } $type = $parameter->getType(); if ($type == 'array' && !is_array($value)) { throw new ArgumentException($parameter, $context); } if (($type == 'int' || $type == 'float') && !is_numeric($value)) { throw new ArgumentException($parameter, $context); } if ($type == 'bool' && !is_bool($value) && !is_numeric($value)) { throw new ArgumentException($parameter, $context); } }
[ "private", "function", "assertType", "(", "\\", "ReflectionParameter", "$", "parameter", ",", "\\", "ReflectionFunctionAbstract", "$", "context", ",", "$", "value", ")", "{", "if", "(", "is_null", "(", "$", "value", ")", ")", "{", "if", "(", "!", "$", "p...
Assert that given value are matched parameter type. @param \ReflectionParameter $parameter @param \ReflectionFunctionAbstract $context @param mixed $value @throws ArgumentException
[ "Assert", "that", "given", "value", "are", "matched", "parameter", "type", "." ]
02580dff7f1fcbc5e74caa1f78ea84c0e4c0d92e
https://github.com/spiral/core/blob/02580dff7f1fcbc5e74caa1f78ea84c0e4c0d92e/src/Container.php#L600-L629
train
netgen/site-bundle
bundle/EventListener/SetCsrfEnabledEventListener.php
SetCsrfEnabledEventListener.onKernelRequest
public function onKernelRequest(GetResponseEvent $event): void { $event->getRequest()->attributes->set( 'csrf_enabled', $this->csrfTokenManager instanceof CsrfTokenManager ); }
php
public function onKernelRequest(GetResponseEvent $event): void { $event->getRequest()->attributes->set( 'csrf_enabled', $this->csrfTokenManager instanceof CsrfTokenManager ); }
[ "public", "function", "onKernelRequest", "(", "GetResponseEvent", "$", "event", ")", ":", "void", "{", "$", "event", "->", "getRequest", "(", ")", "->", "attributes", "->", "set", "(", "'csrf_enabled'", ",", "$", "this", "->", "csrfTokenManager", "instanceof",...
Sets the variable into request indicating if CSRF protection is enabled or not.
[ "Sets", "the", "variable", "into", "request", "indicating", "if", "CSRF", "protection", "is", "enabled", "or", "not", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/EventListener/SetCsrfEnabledEventListener.php#L37-L43
train
netgen/site-bundle
bundle/Helper/PathHelper.php
PathHelper.getPath
public function getPath($locationId, array $options = []): array { $optionsResolver = new OptionsResolver(); $this->configureOptions($optionsResolver); $options = $optionsResolver->resolve($options); $excludedContentTypes = []; if ( !$options['use_all_content_types'] && $this->configResolver->hasParameter('path_helper.excluded_content_types', 'ngsite') ) { $excludedContentTypes = $this->configResolver->getParameter('path_helper.excluded_content_types', 'ngsite'); if (!is_array($excludedContentTypes)) { $excludedContentTypes = []; } } // The root location can be defined at site access level $rootLocationId = (int) $this->configResolver->getParameter('content.tree_root.location_id'); $path = $this->loadService->loadLocation($locationId)->path; // Shift of location "1" from path as it is not a fully valid location and not readable by most users array_shift($path); $pathArray = []; $rootLocationFound = false; foreach ($path as $index => $pathItem) { if ((int) $pathItem === $rootLocationId) { $rootLocationFound = true; } if (!$rootLocationFound) { continue; } try { $location = $this->loadService->loadLocation($pathItem); } catch (UnauthorizedException $e) { return []; } if (!in_array($location->contentInfo->contentTypeIdentifier, $excludedContentTypes, true)) { $pathArray[] = [ 'text' => $location->contentInfo->name, 'url' => $location->id !== (int) $locationId ? $this->router->generate( $location, [], $options['absolute_url'] ? UrlGeneratorInterface::ABSOLUTE_URL : UrlGeneratorInterface::ABSOLUTE_PATH ) : false, 'location' => $location, ]; } } return $pathArray; }
php
public function getPath($locationId, array $options = []): array { $optionsResolver = new OptionsResolver(); $this->configureOptions($optionsResolver); $options = $optionsResolver->resolve($options); $excludedContentTypes = []; if ( !$options['use_all_content_types'] && $this->configResolver->hasParameter('path_helper.excluded_content_types', 'ngsite') ) { $excludedContentTypes = $this->configResolver->getParameter('path_helper.excluded_content_types', 'ngsite'); if (!is_array($excludedContentTypes)) { $excludedContentTypes = []; } } // The root location can be defined at site access level $rootLocationId = (int) $this->configResolver->getParameter('content.tree_root.location_id'); $path = $this->loadService->loadLocation($locationId)->path; // Shift of location "1" from path as it is not a fully valid location and not readable by most users array_shift($path); $pathArray = []; $rootLocationFound = false; foreach ($path as $index => $pathItem) { if ((int) $pathItem === $rootLocationId) { $rootLocationFound = true; } if (!$rootLocationFound) { continue; } try { $location = $this->loadService->loadLocation($pathItem); } catch (UnauthorizedException $e) { return []; } if (!in_array($location->contentInfo->contentTypeIdentifier, $excludedContentTypes, true)) { $pathArray[] = [ 'text' => $location->contentInfo->name, 'url' => $location->id !== (int) $locationId ? $this->router->generate( $location, [], $options['absolute_url'] ? UrlGeneratorInterface::ABSOLUTE_URL : UrlGeneratorInterface::ABSOLUTE_PATH ) : false, 'location' => $location, ]; } } return $pathArray; }
[ "public", "function", "getPath", "(", "$", "locationId", ",", "array", "$", "options", "=", "[", "]", ")", ":", "array", "{", "$", "optionsResolver", "=", "new", "OptionsResolver", "(", ")", ";", "$", "this", "->", "configureOptions", "(", "$", "optionsR...
Returns the path array for provided location ID. @param int|string $locationId
[ "Returns", "the", "path", "array", "for", "provided", "location", "ID", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Helper/PathHelper.php#L46-L106
train
netgen/site-bundle
bundle/ContextProvider/UserContextProvider.php
UserContextProvider.updateUserContext
public function updateUserContext(UserContext $context): void { $context->addParameter( 'userId', $this->repository->getPermissionResolver()->getCurrentUserReference()->getUserId() ); }
php
public function updateUserContext(UserContext $context): void { $context->addParameter( 'userId', $this->repository->getPermissionResolver()->getCurrentUserReference()->getUserId() ); }
[ "public", "function", "updateUserContext", "(", "UserContext", "$", "context", ")", ":", "void", "{", "$", "context", "->", "addParameter", "(", "'userId'", ",", "$", "this", "->", "repository", "->", "getPermissionResolver", "(", ")", "->", "getCurrentUserRefer...
Adds the current user ID to the user context. Allows varying the caches per user, without taking into the account session for example.
[ "Adds", "the", "current", "user", "ID", "to", "the", "user", "context", ".", "Allows", "varying", "the", "caches", "per", "user", "without", "taking", "into", "the", "account", "session", "for", "example", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/ContextProvider/UserContextProvider.php#L27-L33
train
netgen/site-bundle
bundle/Command/SymlinkCommand.php
SymlinkCommand.verifyAndSymlinkFile
protected function verifyAndSymlinkFile(string $source, string $destination, OutputInterface $output): void { if (!$this->fileSystem->exists(dirname($destination))) { $this->fileSystem->mkdir(dirname($destination), 0755); } if ($this->fileSystem->exists($destination) && !is_file($destination)) { $output->writeln('<comment>' . basename($destination) . '</comment> already exists in <comment>' . dirname($destination) . '/</comment> and is not a file/symlink. Skipping...'); return; } if ($this->forceSymlinks && is_link($destination)) { $this->fileSystem->remove($destination); } if (is_file($destination) && !is_link($destination)) { if ($this->fileSystem->exists($destination . '.original')) { $output->writeln('Cannot create backup file <comment>' . basename($destination) . '.original</comment> in <comment>' . dirname($destination) . '/</comment>. Skipping...'); return; } $this->fileSystem->rename($destination, $destination . '.original'); } if ($this->fileSystem->exists($destination)) { if (is_link($destination)) { $output->writeln('Skipped creating the symlink for <comment>' . basename($destination) . '</comment> in <comment>' . dirname($destination) . '/</comment>. Symlink already exists!'); } else { $output->writeln('Skipped creating the symlink for <comment>' . basename($destination) . '</comment> in <comment>' . dirname($destination) . '/</comment> due to an unknown error.'); } return; } $this->fileSystem->symlink( $this->fileSystem->makePathRelative( dirname($source), realpath(dirname($destination)) ) . basename($source), $destination ); }
php
protected function verifyAndSymlinkFile(string $source, string $destination, OutputInterface $output): void { if (!$this->fileSystem->exists(dirname($destination))) { $this->fileSystem->mkdir(dirname($destination), 0755); } if ($this->fileSystem->exists($destination) && !is_file($destination)) { $output->writeln('<comment>' . basename($destination) . '</comment> already exists in <comment>' . dirname($destination) . '/</comment> and is not a file/symlink. Skipping...'); return; } if ($this->forceSymlinks && is_link($destination)) { $this->fileSystem->remove($destination); } if (is_file($destination) && !is_link($destination)) { if ($this->fileSystem->exists($destination . '.original')) { $output->writeln('Cannot create backup file <comment>' . basename($destination) . '.original</comment> in <comment>' . dirname($destination) . '/</comment>. Skipping...'); return; } $this->fileSystem->rename($destination, $destination . '.original'); } if ($this->fileSystem->exists($destination)) { if (is_link($destination)) { $output->writeln('Skipped creating the symlink for <comment>' . basename($destination) . '</comment> in <comment>' . dirname($destination) . '/</comment>. Symlink already exists!'); } else { $output->writeln('Skipped creating the symlink for <comment>' . basename($destination) . '</comment> in <comment>' . dirname($destination) . '/</comment> due to an unknown error.'); } return; } $this->fileSystem->symlink( $this->fileSystem->makePathRelative( dirname($source), realpath(dirname($destination)) ) . basename($source), $destination ); }
[ "protected", "function", "verifyAndSymlinkFile", "(", "string", "$", "source", ",", "string", "$", "destination", ",", "OutputInterface", "$", "output", ")", ":", "void", "{", "if", "(", "!", "$", "this", "->", "fileSystem", "->", "exists", "(", "dirname", ...
Verify that source file can be symlinked to destination and do symlinking if it can.
[ "Verify", "that", "source", "file", "can", "be", "symlinked", "to", "destination", "and", "do", "symlinking", "if", "it", "can", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Command/SymlinkCommand.php#L34-L77
train
netgen/site-bundle
bundle/Command/SymlinkCommand.php
SymlinkCommand.verifyAndSymlinkDirectory
protected function verifyAndSymlinkDirectory(string $source, string $destination, OutputInterface $output): void { if ($this->fileSystem->exists($destination) && !is_link($destination)) { $output->writeln('<comment>' . basename($destination) . '</comment> already exists in <comment>' . dirname($destination) . '/</comment> and is not a symlink. Skipping...'); return; } if ($this->forceSymlinks && is_link($destination)) { $this->fileSystem->remove($destination); } if ($this->fileSystem->exists($destination)) { $output->writeln('Skipped creating the symlink for <comment>' . basename($destination) . '</comment> in <comment>' . dirname($destination) . '/</comment>. Symlink already exists!'); return; } $this->fileSystem->symlink( $this->fileSystem->makePathRelative( $source, realpath(dirname($destination)) ), $destination ); }
php
protected function verifyAndSymlinkDirectory(string $source, string $destination, OutputInterface $output): void { if ($this->fileSystem->exists($destination) && !is_link($destination)) { $output->writeln('<comment>' . basename($destination) . '</comment> already exists in <comment>' . dirname($destination) . '/</comment> and is not a symlink. Skipping...'); return; } if ($this->forceSymlinks && is_link($destination)) { $this->fileSystem->remove($destination); } if ($this->fileSystem->exists($destination)) { $output->writeln('Skipped creating the symlink for <comment>' . basename($destination) . '</comment> in <comment>' . dirname($destination) . '/</comment>. Symlink already exists!'); return; } $this->fileSystem->symlink( $this->fileSystem->makePathRelative( $source, realpath(dirname($destination)) ), $destination ); }
[ "protected", "function", "verifyAndSymlinkDirectory", "(", "string", "$", "source", ",", "string", "$", "destination", ",", "OutputInterface", "$", "output", ")", ":", "void", "{", "if", "(", "$", "this", "->", "fileSystem", "->", "exists", "(", "$", "destin...
Verify that source directory can be symlinked to destination and do symlinking if it can.
[ "Verify", "that", "source", "directory", "can", "be", "symlinked", "to", "destination", "and", "do", "symlinking", "if", "it", "can", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Command/SymlinkCommand.php#L82-L107
train
Prezent/prezent-crud-bundle
src/Templating/TemplateGuesser.php
TemplateGuesser.guessTemplateNames
public function guessTemplateNames($controller, Request $request) { if (is_object($controller) && method_exists($controller, '__invoke')) { $controller = [$controller, '__invoke']; } elseif (!is_array($controller)) { throw new \InvalidArgumentException(sprintf('First argument of %s must be an array callable or an object defining the magic method __invoke. "%s" given.', __METHOD__, gettype($controller))); } if (!is_string($controller[0])) { $controller[0] = class_exists('Doctrine\Common\Util\ClassUtils') ? ClassUtils::getClass($controller[0]) : get_class($controller[0]); } $reflClass = new \ReflectionClass($controller[0]); $templates = []; do { $controller[0] = $reflClass->getName(); if ($template = $this->guessTemplateName($controller, $request)) { $templates[] = $template; } $reflClass = $reflClass->getParentClass(); } while ($reflClass); return $templates; }
php
public function guessTemplateNames($controller, Request $request) { if (is_object($controller) && method_exists($controller, '__invoke')) { $controller = [$controller, '__invoke']; } elseif (!is_array($controller)) { throw new \InvalidArgumentException(sprintf('First argument of %s must be an array callable or an object defining the magic method __invoke. "%s" given.', __METHOD__, gettype($controller))); } if (!is_string($controller[0])) { $controller[0] = class_exists('Doctrine\Common\Util\ClassUtils') ? ClassUtils::getClass($controller[0]) : get_class($controller[0]); } $reflClass = new \ReflectionClass($controller[0]); $templates = []; do { $controller[0] = $reflClass->getName(); if ($template = $this->guessTemplateName($controller, $request)) { $templates[] = $template; } $reflClass = $reflClass->getParentClass(); } while ($reflClass); return $templates; }
[ "public", "function", "guessTemplateNames", "(", "$", "controller", ",", "Request", "$", "request", ")", "{", "if", "(", "is_object", "(", "$", "controller", ")", "&&", "method_exists", "(", "$", "controller", ",", "'__invoke'", ")", ")", "{", "$", "contro...
Guess multiple possible template names based on the controller @param callable $controller An array storing the controller object and action method @param Request $request A Request instance @param string $engine @return string[] Array of template references @throws \InvalidArgumentException
[ "Guess", "multiple", "possible", "template", "names", "based", "on", "the", "controller" ]
bb8bcf92cecc2acae08b8a672876b4972175ca24
https://github.com/Prezent/prezent-crud-bundle/blob/bb8bcf92cecc2acae08b8a672876b4972175ca24/src/Templating/TemplateGuesser.php#L54-L82
train
netgen/site-bundle
bundle/EventListener/UserEventListener.php
UserEventListener.getUserName
protected function getUserName(User $user): string { $contentInfo = $this->repository->sudo( function (Repository $repository) use ($user): ContentInfo { return $this->loadService->loadContent($user->id)->contentInfo; } ); return $contentInfo->name; }
php
protected function getUserName(User $user): string { $contentInfo = $this->repository->sudo( function (Repository $repository) use ($user): ContentInfo { return $this->loadService->loadContent($user->id)->contentInfo; } ); return $contentInfo->name; }
[ "protected", "function", "getUserName", "(", "User", "$", "user", ")", ":", "string", "{", "$", "contentInfo", "=", "$", "this", "->", "repository", "->", "sudo", "(", "function", "(", "Repository", "$", "repository", ")", "use", "(", "$", "user", ")", ...
Returns the translated user name.
[ "Returns", "the", "translated", "user", "name", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/EventListener/UserEventListener.php#L67-L76
train
spiral/router
src/Router.php
Router.matchRoute
protected function matchRoute(ServerRequestInterface $request): ?RouteInterface { foreach ($this->routes as $route) { // Matched route will return new route instance with matched parameters $matched = $route->match($request); if (!empty($matched)) { return $matched; } } if (!empty($this->default)) { return $this->default->match($request); } // unable to match any route return null; }
php
protected function matchRoute(ServerRequestInterface $request): ?RouteInterface { foreach ($this->routes as $route) { // Matched route will return new route instance with matched parameters $matched = $route->match($request); if (!empty($matched)) { return $matched; } } if (!empty($this->default)) { return $this->default->match($request); } // unable to match any route return null; }
[ "protected", "function", "matchRoute", "(", "ServerRequestInterface", "$", "request", ")", ":", "?", "RouteInterface", "{", "foreach", "(", "$", "this", "->", "routes", "as", "$", "route", ")", "{", "// Matched route will return new route instance with matched parameter...
Find route matched for given request. @param ServerRequestInterface $request @return null|RouteInterface
[ "Find", "route", "matched", "for", "given", "request", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/Router.php#L142-L159
train
spiral/router
src/Router.php
Router.configure
protected function configure(RouteInterface $route): RouteInterface { if ($route instanceof ContainerizedInterface && !$route->hasContainer()) { // isolating route in a given container $route = $route->withContainer($this->container); } return $route->withPrefix($this->basePath); }
php
protected function configure(RouteInterface $route): RouteInterface { if ($route instanceof ContainerizedInterface && !$route->hasContainer()) { // isolating route in a given container $route = $route->withContainer($this->container); } return $route->withPrefix($this->basePath); }
[ "protected", "function", "configure", "(", "RouteInterface", "$", "route", ")", ":", "RouteInterface", "{", "if", "(", "$", "route", "instanceof", "ContainerizedInterface", "&&", "!", "$", "route", "->", "hasContainer", "(", ")", ")", "{", "// isolating route in...
Configure route with needed dependencies. @param RouteInterface $route @return RouteInterface
[ "Configure", "route", "with", "needed", "dependencies", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/Router.php#L168-L176
train
spiral/router
src/CoreHandler.php
CoreHandler.withVerbActions
public function withVerbActions(bool $verbActions): CoreHandler { $handler = clone $this; $handler->verbActions = $verbActions; return $handler; }
php
public function withVerbActions(bool $verbActions): CoreHandler { $handler = clone $this; $handler->verbActions = $verbActions; return $handler; }
[ "public", "function", "withVerbActions", "(", "bool", "$", "verbActions", ")", ":", "CoreHandler", "{", "$", "handler", "=", "clone", "$", "this", ";", "$", "handler", "->", "verbActions", "=", "$", "verbActions", ";", "return", "$", "handler", ";", "}" ]
Disable or enable HTTP prefix for actions. @param bool $verbActions @return CoreHandler
[ "Disable", "or", "enable", "HTTP", "prefix", "for", "actions", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/CoreHandler.php#L79-L85
train
spiral/router
src/CoreHandler.php
CoreHandler.wrapResponse
private function wrapResponse(Response $response, $result = null, string $output = ''): Response { if ($result instanceof Response) { if (!empty($output) && $result->getBody()->isWritable()) { $result->getBody()->write($output); } return $result; } if (is_array($result) || $result instanceof \JsonSerializable) { $response = $this->writeJson($response, $result); } else { $response->getBody()->write($result); } //Always glue buffered output $response->getBody()->write($output); return $response; }
php
private function wrapResponse(Response $response, $result = null, string $output = ''): Response { if ($result instanceof Response) { if (!empty($output) && $result->getBody()->isWritable()) { $result->getBody()->write($output); } return $result; } if (is_array($result) || $result instanceof \JsonSerializable) { $response = $this->writeJson($response, $result); } else { $response->getBody()->write($result); } //Always glue buffered output $response->getBody()->write($output); return $response; }
[ "private", "function", "wrapResponse", "(", "Response", "$", "response", ",", "$", "result", "=", "null", ",", "string", "$", "output", "=", "''", ")", ":", "Response", "{", "if", "(", "$", "result", "instanceof", "Response", ")", "{", "if", "(", "!", ...
Convert endpoint result into valid response. @param Response $response Initial pipeline response. @param mixed $result Generated endpoint output. @param string $output Buffer output. @return Response
[ "Convert", "endpoint", "result", "into", "valid", "response", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/CoreHandler.php#L149-L169
train
spiral/router
src/CoreHandler.php
CoreHandler.mapException
private function mapException(ControllerException $exception): ClientException { switch ($exception->getCode()) { case ControllerException::BAD_ACTION: //no break case ControllerException::NOT_FOUND: return new NotFoundException($exception->getMessage()); case ControllerException::FORBIDDEN: return new ForbiddenException($exception->getMessage()); default: return new BadRequestException($exception->getMessage()); } }
php
private function mapException(ControllerException $exception): ClientException { switch ($exception->getCode()) { case ControllerException::BAD_ACTION: //no break case ControllerException::NOT_FOUND: return new NotFoundException($exception->getMessage()); case ControllerException::FORBIDDEN: return new ForbiddenException($exception->getMessage()); default: return new BadRequestException($exception->getMessage()); } }
[ "private", "function", "mapException", "(", "ControllerException", "$", "exception", ")", ":", "ClientException", "{", "switch", "(", "$", "exception", "->", "getCode", "(", ")", ")", "{", "case", "ControllerException", "::", "BAD_ACTION", ":", "//no break", "ca...
Converts core specific ControllerException into HTTP ClientException. @param ControllerException $exception @return ClientException
[ "Converts", "core", "specific", "ControllerException", "into", "HTTP", "ClientException", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/CoreHandler.php#L177-L189
train
Atnic/laravel-generator
app/Database/Eloquent/Concerns/HasRelationships.php
HasRelationships.belongsToOne
public function belongsToOne($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, $parentKey = null, $relatedKey = null, $relation = null) { // If no relationship name was passed, we will pull backtraces to get the // name of the calling function. We will use that function name as the // title of this relation since that is a great convention to apply. if (is_null($relation)) { $relation = $this->guessBelongsToOneRelation(); } // First, we'll need to determine the foreign key and "other key" for the // relationship. Once we have determined the keys we'll make the query // instances as well as the relationship instances we need for this. $instance = $this->newRelatedInstance($related); $foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey(); $relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey(); // If no table name was provided, we can guess it by concatenating the two // models using underscores in alphabetical order. The two model names // are transformed to snake case from their default CamelCase also. if (is_null($table)) { $table = $this->joiningTable($related); } return $this->newBelongsToOne( $instance->newQuery(), $this, $table, $foreignPivotKey, $relatedPivotKey, $parentKey ?: $this->getKeyName(), $relatedKey ?: $instance->getKeyName(), $relation ); }
php
public function belongsToOne($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null, $parentKey = null, $relatedKey = null, $relation = null) { // If no relationship name was passed, we will pull backtraces to get the // name of the calling function. We will use that function name as the // title of this relation since that is a great convention to apply. if (is_null($relation)) { $relation = $this->guessBelongsToOneRelation(); } // First, we'll need to determine the foreign key and "other key" for the // relationship. Once we have determined the keys we'll make the query // instances as well as the relationship instances we need for this. $instance = $this->newRelatedInstance($related); $foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey(); $relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey(); // If no table name was provided, we can guess it by concatenating the two // models using underscores in alphabetical order. The two model names // are transformed to snake case from their default CamelCase also. if (is_null($table)) { $table = $this->joiningTable($related); } return $this->newBelongsToOne( $instance->newQuery(), $this, $table, $foreignPivotKey, $relatedPivotKey, $parentKey ?: $this->getKeyName(), $relatedKey ?: $instance->getKeyName(), $relation ); }
[ "public", "function", "belongsToOne", "(", "$", "related", ",", "$", "table", "=", "null", ",", "$", "foreignPivotKey", "=", "null", ",", "$", "relatedPivotKey", "=", "null", ",", "$", "parentKey", "=", "null", ",", "$", "relatedKey", "=", "null", ",", ...
Define a one-to-one via pivot relationship. @param string $related @param string $table @param string $foreignPivotKey @param string $relatedPivotKey @param string $parentKey @param string $relatedKey @param string $relation @return \Atnic\LaravelGenerator\Database\Eloquent\Relations\BelongsToOne
[ "Define", "a", "one", "-", "to", "-", "one", "via", "pivot", "relationship", "." ]
7bf53837a61af566b389255784dbbf1789020018
https://github.com/Atnic/laravel-generator/blob/7bf53837a61af566b389255784dbbf1789020018/app/Database/Eloquent/Concerns/HasRelationships.php#L88-L119
train
alaxos/cakephp3-libs
src/Lib/ShellTool.php
ShellTool.color
public static function color($text, $color) { if (isset(ShellTool::$colors[$color])) { return ShellTool::$colors[$color]['start'] . $text . ShellTool::$colors[$color]['close']; } else { return $text; } }
php
public static function color($text, $color) { if (isset(ShellTool::$colors[$color])) { return ShellTool::$colors[$color]['start'] . $text . ShellTool::$colors[$color]['close']; } else { return $text; } }
[ "public", "static", "function", "color", "(", "$", "text", ",", "$", "color", ")", "{", "if", "(", "isset", "(", "ShellTool", "::", "$", "colors", "[", "$", "color", "]", ")", ")", "{", "return", "ShellTool", "::", "$", "colors", "[", "$", "color",...
Return the given text formatted in the given color @param string $text @param string $color @return string
[ "Return", "the", "given", "text", "formatted", "in", "the", "given", "color" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/ShellTool.php#L17-L24
train
nilportugues/php-api-transformer
src/Transformer/Helpers/RecursiveDeleteHelper.php
RecursiveDeleteHelper.deleteProperties
public static function deleteProperties(array &$mappings, array &$array, string $typeKey) { if (\array_key_exists(Serializer::CLASS_IDENTIFIER_KEY, $array)) { $newArray = []; self::deleteMatchedClassProperties($mappings, $array, $typeKey, $newArray); if (!empty($newArray)) { $array = $newArray; } } }
php
public static function deleteProperties(array &$mappings, array &$array, string $typeKey) { if (\array_key_exists(Serializer::CLASS_IDENTIFIER_KEY, $array)) { $newArray = []; self::deleteMatchedClassProperties($mappings, $array, $typeKey, $newArray); if (!empty($newArray)) { $array = $newArray; } } }
[ "public", "static", "function", "deleteProperties", "(", "array", "&", "$", "mappings", ",", "array", "&", "$", "array", ",", "string", "$", "typeKey", ")", "{", "if", "(", "\\", "array_key_exists", "(", "Serializer", "::", "CLASS_IDENTIFIER_KEY", ",", "$", ...
Removes a sets if keys for a given class using recursion. @param \NilPortugues\Api\Mapping\Mapping[] $mappings @param array $array Array with data @param string $typeKey Scope to do the replacement.
[ "Removes", "a", "sets", "if", "keys", "for", "a", "given", "class", "using", "recursion", "." ]
a9f20fbe1580d98e3d462a0ebe13fb7595cbd683
https://github.com/nilportugues/php-api-transformer/blob/a9f20fbe1580d98e3d462a0ebe13fb7595cbd683/src/Transformer/Helpers/RecursiveDeleteHelper.php#L79-L90
train
cedx/coveralls.php
lib/GitCommit.php
GitCommit.fromJson
static function fromJson(object $map): self { return (new static(isset($map->id) && is_string($map->id) ? $map->id : '', isset($map->message) && is_string($map->message) ? $map->message : '')) ->setAuthorEmail(isset($map->author_email) && is_string($map->author_email) ? $map->author_email : '') ->setAuthorName(isset($map->author_name) && is_string($map->author_name) ? $map->author_name : '') ->setCommitterEmail(isset($map->committer_email) && is_string($map->committer_email) ? $map->committer_email : '') ->setCommitterName(isset($map->committer_name) && is_string($map->committer_name) ? $map->committer_name : ''); }
php
static function fromJson(object $map): self { return (new static(isset($map->id) && is_string($map->id) ? $map->id : '', isset($map->message) && is_string($map->message) ? $map->message : '')) ->setAuthorEmail(isset($map->author_email) && is_string($map->author_email) ? $map->author_email : '') ->setAuthorName(isset($map->author_name) && is_string($map->author_name) ? $map->author_name : '') ->setCommitterEmail(isset($map->committer_email) && is_string($map->committer_email) ? $map->committer_email : '') ->setCommitterName(isset($map->committer_name) && is_string($map->committer_name) ? $map->committer_name : ''); }
[ "static", "function", "fromJson", "(", "object", "$", "map", ")", ":", "self", "{", "return", "(", "new", "static", "(", "isset", "(", "$", "map", "->", "id", ")", "&&", "is_string", "(", "$", "map", "->", "id", ")", "?", "$", "map", "->", "id", ...
Creates a new Git commit from the specified JSON map. @param object $map A JSON map representing a Git commit. @return static The instance corresponding to the specified JSON map.
[ "Creates", "a", "new", "Git", "commit", "from", "the", "specified", "JSON", "map", "." ]
c196de0f92e06d5143ba90ebab18c8e384316cc0
https://github.com/cedx/coveralls.php/blob/c196de0f92e06d5143ba90ebab18c8e384316cc0/lib/GitCommit.php#L40-L46
train
alaxos/cakephp3-libs
src/Lib/StringTool.php
StringTool.start_with
public static function start_with($string, $needle, $case_sensitive = true) { if(!is_string($string)) { $string = (string)$string; } if(!is_string($needle)) { $needle = (string)$needle; } if($case_sensitive) { return strpos($string, $needle) === 0; } else { return stripos($string, $needle) === 0; } }
php
public static function start_with($string, $needle, $case_sensitive = true) { if(!is_string($string)) { $string = (string)$string; } if(!is_string($needle)) { $needle = (string)$needle; } if($case_sensitive) { return strpos($string, $needle) === 0; } else { return stripos($string, $needle) === 0; } }
[ "public", "static", "function", "start_with", "(", "$", "string", ",", "$", "needle", ",", "$", "case_sensitive", "=", "true", ")", "{", "if", "(", "!", "is_string", "(", "$", "string", ")", ")", "{", "$", "string", "=", "(", "string", ")", "$", "s...
Tests if a string starts with a given string @param string @param string @return bool
[ "Tests", "if", "a", "string", "starts", "with", "a", "given", "string" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/StringTool.php#L18-L38
train
alaxos/cakephp3-libs
src/Lib/StringTool.php
StringTool.end_with
public static function end_with($string, $needle, $case_sensitive = true) { if(!is_string($string)) { $string = (string)$string; } if(!is_string($needle)) { $needle = (string)$needle; } if($case_sensitive) { return strrpos($string, $needle) === strlen($string) - strlen($needle); } else { return strripos($string, $needle) === strlen($string) - strlen($needle); } }
php
public static function end_with($string, $needle, $case_sensitive = true) { if(!is_string($string)) { $string = (string)$string; } if(!is_string($needle)) { $needle = (string)$needle; } if($case_sensitive) { return strrpos($string, $needle) === strlen($string) - strlen($needle); } else { return strripos($string, $needle) === strlen($string) - strlen($needle); } }
[ "public", "static", "function", "end_with", "(", "$", "string", ",", "$", "needle", ",", "$", "case_sensitive", "=", "true", ")", "{", "if", "(", "!", "is_string", "(", "$", "string", ")", ")", "{", "$", "string", "=", "(", "string", ")", "$", "str...
Tests if a string ends with the given string @param string @param string @return bool
[ "Tests", "if", "a", "string", "ends", "with", "the", "given", "string" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/StringTool.php#L48-L68
train
alaxos/cakephp3-libs
src/Lib/StringTool.php
StringTool.get_value_between_chars
public static function get_value_between_chars($haystack, $index = 0, $opening_char = '[', $closing_char = ']') { $offset = 0; $found = true; $value = null; for ($i = 0; $i < $index + 1; $i++) { $op_pos = strpos($haystack, $opening_char, $offset); if($op_pos !== false) { $cl_pos = strpos($haystack, $closing_char, $op_pos + strlen($opening_char)); if($cl_pos !== false) { $value = substr($haystack, $op_pos + strlen($opening_char), $cl_pos - $op_pos - strlen($opening_char)); $offset = $cl_pos + strlen($closing_char); } else { $found = false; break; } } else { $found = false; break; } } if($found) { return $value; } else { return null; } }
php
public static function get_value_between_chars($haystack, $index = 0, $opening_char = '[', $closing_char = ']') { $offset = 0; $found = true; $value = null; for ($i = 0; $i < $index + 1; $i++) { $op_pos = strpos($haystack, $opening_char, $offset); if($op_pos !== false) { $cl_pos = strpos($haystack, $closing_char, $op_pos + strlen($opening_char)); if($cl_pos !== false) { $value = substr($haystack, $op_pos + strlen($opening_char), $cl_pos - $op_pos - strlen($opening_char)); $offset = $cl_pos + strlen($closing_char); } else { $found = false; break; } } else { $found = false; break; } } if($found) { return $value; } else { return null; } }
[ "public", "static", "function", "get_value_between_chars", "(", "$", "haystack", ",", "$", "index", "=", "0", ",", "$", "opening_char", "=", "'['", ",", "$", "closing_char", "=", "']'", ")", "{", "$", "offset", "=", "0", ";", "$", "found", "=", "true",...
Return the string found between two characters. If an index is given, it returns the value at the index position @param string $opening_char @param string $closing_char @param int $index 0 based index @return string or null
[ "Return", "the", "string", "found", "between", "two", "characters", ".", "If", "an", "index", "is", "given", "it", "returns", "the", "value", "at", "the", "index", "position" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/StringTool.php#L80-L119
train
alaxos/cakephp3-libs
src/Lib/StringTool.php
StringTool.get_random_string
public static function get_random_string($length = 10, $chars) { $random_string = ''; for($i = 0; $i < $length; $i++) { $index = rand(0, strlen($chars) - 1); $random_string .= $chars{$index}; } return $random_string; }
php
public static function get_random_string($length = 10, $chars) { $random_string = ''; for($i = 0; $i < $length; $i++) { $index = rand(0, strlen($chars) - 1); $random_string .= $chars{$index}; } return $random_string; }
[ "public", "static", "function", "get_random_string", "(", "$", "length", "=", "10", ",", "$", "chars", ")", "{", "$", "random_string", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "$", "i", "++", ")", ...
Return a random string made of the given chars @param number $length The length of the string to get @param string $chars A string containing the chars that can compose the generated random string @return string
[ "Return", "a", "random", "string", "made", "of", "the", "given", "chars" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/StringTool.php#L139-L150
train
alaxos/cakephp3-libs
src/Lib/StringTool.php
StringTool.ensure_start_with
public static function ensure_start_with($string, $leading_string) { if (StringTool :: start_with($string, $leading_string)) { return $string; } else { return $leading_string . $string; } }
php
public static function ensure_start_with($string, $leading_string) { if (StringTool :: start_with($string, $leading_string)) { return $string; } else { return $leading_string . $string; } }
[ "public", "static", "function", "ensure_start_with", "(", "$", "string", ",", "$", "leading_string", ")", "{", "if", "(", "StringTool", "::", "start_with", "(", "$", "string", ",", "$", "leading_string", ")", ")", "{", "return", "$", "string", ";", "}", ...
Ensure a string starts with another given string @param $string The string that must start with a leading string @param $leading_string The string to add at the beginning of the main string if necessary @return string
[ "Ensure", "a", "string", "starts", "with", "another", "given", "string" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/StringTool.php#L159-L169
train
alaxos/cakephp3-libs
src/Lib/StringTool.php
StringTool.ensure_end_with
public static function ensure_end_with($string, $trailing_string) { if (StringTool :: end_with($string, $trailing_string)) { return $string; } else { return $string . $trailing_string; } }
php
public static function ensure_end_with($string, $trailing_string) { if (StringTool :: end_with($string, $trailing_string)) { return $string; } else { return $string . $trailing_string; } }
[ "public", "static", "function", "ensure_end_with", "(", "$", "string", ",", "$", "trailing_string", ")", "{", "if", "(", "StringTool", "::", "end_with", "(", "$", "string", ",", "$", "trailing_string", ")", ")", "{", "return", "$", "string", ";", "}", "e...
Ensure a string ends with another given string @param $string The string that must end with a trailing string @param $trailing_string The string to add at the end of the main string if necessary @return string
[ "Ensure", "a", "string", "ends", "with", "another", "given", "string" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/StringTool.php#L178-L188
train
alaxos/cakephp3-libs
src/Lib/StringTool.php
StringTool.remove_trailing
public static function remove_trailing($string, $trailing_string) { if (StringTool :: end_with($string, $trailing_string)) { return substr($string, 0, strlen($string) - strlen($trailing_string)); } else { return $string; } }
php
public static function remove_trailing($string, $trailing_string) { if (StringTool :: end_with($string, $trailing_string)) { return substr($string, 0, strlen($string) - strlen($trailing_string)); } else { return $string; } }
[ "public", "static", "function", "remove_trailing", "(", "$", "string", ",", "$", "trailing_string", ")", "{", "if", "(", "StringTool", "::", "end_with", "(", "$", "string", ",", "$", "trailing_string", ")", ")", "{", "return", "substr", "(", "$", "string",...
Remove a trailing string from a string if it exists @param $string The string that must be shortened if it ends with a trailing string @param $trailing_string The trailing string @return string
[ "Remove", "a", "trailing", "string", "from", "a", "string", "if", "it", "exists" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/StringTool.php#L197-L207
train
alaxos/cakephp3-libs
src/Lib/StringTool.php
StringTool.remove_leading
public static function remove_leading($string, $leading_string) { if (StringTool :: start_with($string, $leading_string)) { return substr($string, strlen($leading_string)); } else { return $string; } }
php
public static function remove_leading($string, $leading_string) { if (StringTool :: start_with($string, $leading_string)) { return substr($string, strlen($leading_string)); } else { return $string; } }
[ "public", "static", "function", "remove_leading", "(", "$", "string", ",", "$", "leading_string", ")", "{", "if", "(", "StringTool", "::", "start_with", "(", "$", "string", ",", "$", "leading_string", ")", ")", "{", "return", "substr", "(", "$", "string", ...
Remove a leading string from a string if it exists @param string $string The string that must be shortened if it starts with a leading string @param string $leading_string The leading string @return string
[ "Remove", "a", "leading", "string", "from", "a", "string", "if", "it", "exists" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/StringTool.php#L215-L225
train
alaxos/cakephp3-libs
src/Lib/StringTool.php
StringTool.last_replace
public static function last_replace($search, $replace, $string) { $pos = strrpos($string, $search); if($pos !== false) { return substr_replace($string, $replace, $pos, strlen($search)); } else { return $string; } }
php
public static function last_replace($search, $replace, $string) { $pos = strrpos($string, $search); if($pos !== false) { return substr_replace($string, $replace, $pos, strlen($search)); } else { return $string; } }
[ "public", "static", "function", "last_replace", "(", "$", "search", ",", "$", "replace", ",", "$", "string", ")", "{", "$", "pos", "=", "strrpos", "(", "$", "string", ",", "$", "search", ")", ";", "if", "(", "$", "pos", "!==", "false", ")", "{", ...
Replace the last occurence of a substring in a string @param string $search @param string $replace @param string $string
[ "Replace", "the", "last", "occurence", "of", "a", "substring", "in", "a", "string" ]
685e9f17a3fbe3550c59a03a65c4d75df763e804
https://github.com/alaxos/cakephp3-libs/blob/685e9f17a3fbe3550c59a03a65c4d75df763e804/src/Lib/StringTool.php#L296-L308
train
smartboxgroup/integration-framework-bundle
Core/Consumers/AbstractConsumer.php
AbstractConsumer.dispatchConsumerTimingEvent
protected function dispatchConsumerTimingEvent($intervalMs, MessageInterface $message) { $event = new TimingEvent(TimingEvent::CONSUMER_TIMING); $event->setIntervalMs($intervalMs); $event->setMessage($message); if (null !== ($dispatcher = $this->getEventDispatcher())) { $dispatcher->dispatch(TimingEvent::CONSUMER_TIMING, $event); } }
php
protected function dispatchConsumerTimingEvent($intervalMs, MessageInterface $message) { $event = new TimingEvent(TimingEvent::CONSUMER_TIMING); $event->setIntervalMs($intervalMs); $event->setMessage($message); if (null !== ($dispatcher = $this->getEventDispatcher())) { $dispatcher->dispatch(TimingEvent::CONSUMER_TIMING, $event); } }
[ "protected", "function", "dispatchConsumerTimingEvent", "(", "$", "intervalMs", ",", "MessageInterface", "$", "message", ")", "{", "$", "event", "=", "new", "TimingEvent", "(", "TimingEvent", "::", "CONSUMER_TIMING", ")", ";", "$", "event", "->", "setIntervalMs", ...
This function dispatchs a timing event with the amount of time it took to consume a message. @param $intervalMs int the timing interval that we would like to emanate @param MessageInterface $message @return mixed
[ "This", "function", "dispatchs", "a", "timing", "event", "with", "the", "amount", "of", "time", "it", "took", "to", "consume", "a", "message", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Core/Consumers/AbstractConsumer.php#L135-L144
train
smartboxgroup/integration-framework-bundle
Core/Consumers/AbstractConsumer.php
AbstractConsumer.logConsumeMessage
protected function logConsumeMessage() { if ($this->logger) { $now = DateTimeCreator::getNowDateTime(); $this->logger->info( 'A message was consumed on {date}', [ 'date' => $now->format('Y-m-d H:i:s.u'), ] ); } }
php
protected function logConsumeMessage() { if ($this->logger) { $now = DateTimeCreator::getNowDateTime(); $this->logger->info( 'A message was consumed on {date}', [ 'date' => $now->format('Y-m-d H:i:s.u'), ] ); } }
[ "protected", "function", "logConsumeMessage", "(", ")", "{", "if", "(", "$", "this", "->", "logger", ")", "{", "$", "now", "=", "DateTimeCreator", "::", "getNowDateTime", "(", ")", ";", "$", "this", "->", "logger", "->", "info", "(", "'A message was consum...
Log the moment a message was consumed.
[ "Log", "the", "moment", "a", "message", "was", "consumed", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Core/Consumers/AbstractConsumer.php#L149-L160
train
smartboxgroup/integration-framework-bundle
Components/Queues/QueueManager.php
QueueManager.connect
public function connect(bool $shuffle = true) { if (!$this->isConnected()) { if (empty($this->connections)) { throw new \InvalidArgumentException('You have to specify at least one connection.'); } if ($shuffle) { shuffle($this->connections); } $this->connection = null; $tested = []; foreach ($this->connections as $connection) { try { $connection->connect(); $this->connection = $connection; break; } catch (\AMQPConnectionException $e) { $tested[] = "{$connection->getHost()}: {$e->getMessage()}"; } } if (!$this->connection) { throw new \RuntimeException(sprintf('Unable to connect to any of the following hosts:%s%s', PHP_EOL, implode(PHP_EOL, $tested))); } //Create and declare channel $this->channel = new \AMQPChannel($this->connection); $this->channel->setPrefetchCount(1); //AMQPC Exchange is the publishing mechanism $this->exchange = new \AMQPExchange($this->channel); } }
php
public function connect(bool $shuffle = true) { if (!$this->isConnected()) { if (empty($this->connections)) { throw new \InvalidArgumentException('You have to specify at least one connection.'); } if ($shuffle) { shuffle($this->connections); } $this->connection = null; $tested = []; foreach ($this->connections as $connection) { try { $connection->connect(); $this->connection = $connection; break; } catch (\AMQPConnectionException $e) { $tested[] = "{$connection->getHost()}: {$e->getMessage()}"; } } if (!$this->connection) { throw new \RuntimeException(sprintf('Unable to connect to any of the following hosts:%s%s', PHP_EOL, implode(PHP_EOL, $tested))); } //Create and declare channel $this->channel = new \AMQPChannel($this->connection); $this->channel->setPrefetchCount(1); //AMQPC Exchange is the publishing mechanism $this->exchange = new \AMQPExchange($this->channel); } }
[ "public", "function", "connect", "(", "bool", "$", "shuffle", "=", "true", ")", "{", "if", "(", "!", "$", "this", "->", "isConnected", "(", ")", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "connections", ")", ")", "{", "throw", "new", "...
Opens a connection with a queuing system. @param bool $shuffle Shuffle connections to avoid connecting to the seame endpoint everytime @throws \AMQPException
[ "Opens", "a", "connection", "with", "a", "queuing", "system", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/Queues/QueueManager.php#L53-L88
train
netgen/site-bundle
bundle/Templating/Twig/Extension/TopicUrlRuntime.php
TopicUrlRuntime.getTopicUrl
public function getTopicUrl(Tag $tag, array $parameters = [], bool $schemeRelative = false): string { return $this->topicUrlGenerator->generate( $tag, $parameters, $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL ); }
php
public function getTopicUrl(Tag $tag, array $parameters = [], bool $schemeRelative = false): string { return $this->topicUrlGenerator->generate( $tag, $parameters, $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL ); }
[ "public", "function", "getTopicUrl", "(", "Tag", "$", "tag", ",", "array", "$", "parameters", "=", "[", "]", ",", "bool", "$", "schemeRelative", "=", "false", ")", ":", "string", "{", "return", "$", "this", "->", "topicUrlGenerator", "->", "generate", "(...
Returns the URL for the topic specified by provided tag.
[ "Returns", "the", "URL", "for", "the", "topic", "specified", "by", "provided", "tag", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Templating/Twig/Extension/TopicUrlRuntime.php#L40-L49
train
IconoCoders/otp-simple-sdk
Source/SimpleIdn.php
SimpleIdn.nameData
protected function nameData($data = array()) { return array( "ORDER_REF" => (isset($data[0])) ? $data[0] : 'N/A', "RESPONSE_CODE" => (isset($data[1])) ? $data[1] : 'N/A', "RESPONSE_MSG" => (isset($data[2])) ? $data[2] : 'N/A', "IDN_DATE" => (isset($data[3])) ? $data[3] : 'N/A', "ORDER_HASH" => (isset($data[4])) ? $data[4] : 'N/A', ); }
php
protected function nameData($data = array()) { return array( "ORDER_REF" => (isset($data[0])) ? $data[0] : 'N/A', "RESPONSE_CODE" => (isset($data[1])) ? $data[1] : 'N/A', "RESPONSE_MSG" => (isset($data[2])) ? $data[2] : 'N/A', "IDN_DATE" => (isset($data[3])) ? $data[3] : 'N/A', "ORDER_HASH" => (isset($data[4])) ? $data[4] : 'N/A', ); }
[ "protected", "function", "nameData", "(", "$", "data", "=", "array", "(", ")", ")", "{", "return", "array", "(", "\"ORDER_REF\"", "=>", "(", "isset", "(", "$", "data", "[", "0", "]", ")", ")", "?", "$", "data", "[", "0", "]", ":", "'N/A'", ",", ...
Creates associative array for the received data @param array $data Processed data @return void
[ "Creates", "associative", "array", "for", "the", "received", "data" ]
d2808bf52e8d34be69414b444a00f1a9c8564930
https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleIdn.php#L96-L105
train
IconoCoders/otp-simple-sdk
Source/SimpleIdn.php
SimpleIdn.requestIdn
public function requestIdn($data = array()) { if (count($data) == 0) { $this->errorMessage[] = 'IDN DATA: EMPTY'; return $this->nameData(); } $data['MERCHANT'] = $this->merchantId; $this->refnoext = $data['REFNOEXT']; unset($data['REFNOEXT']); foreach ($this->hashFields as $fieldKey) { $data2[$fieldKey] = $data[$fieldKey]; } $irnHash = $this->createHashString($data2); $data2['ORDER_HASH'] = $irnHash; $this->idnRequest = $data2; $this->logFunc("IDN", $this->idnRequest, $this->refnoext); $result = $this->startRequest($this->targetUrl, $this->idnRequest, 'POST'); $this->debugMessage[] = 'IDN RESULT: ' . $result; if (is_string($result)) { $processed = $this->processResponse($result); $this->logFunc("IDN", $processed, $this->refnoext); return $processed; } $this->debugMessage[] = 'IDN RESULT: NOT STRING'; return false; }
php
public function requestIdn($data = array()) { if (count($data) == 0) { $this->errorMessage[] = 'IDN DATA: EMPTY'; return $this->nameData(); } $data['MERCHANT'] = $this->merchantId; $this->refnoext = $data['REFNOEXT']; unset($data['REFNOEXT']); foreach ($this->hashFields as $fieldKey) { $data2[$fieldKey] = $data[$fieldKey]; } $irnHash = $this->createHashString($data2); $data2['ORDER_HASH'] = $irnHash; $this->idnRequest = $data2; $this->logFunc("IDN", $this->idnRequest, $this->refnoext); $result = $this->startRequest($this->targetUrl, $this->idnRequest, 'POST'); $this->debugMessage[] = 'IDN RESULT: ' . $result; if (is_string($result)) { $processed = $this->processResponse($result); $this->logFunc("IDN", $processed, $this->refnoext); return $processed; } $this->debugMessage[] = 'IDN RESULT: NOT STRING'; return false; }
[ "public", "function", "requestIdn", "(", "$", "data", "=", "array", "(", ")", ")", "{", "if", "(", "count", "(", "$", "data", ")", "==", "0", ")", "{", "$", "this", "->", "errorMessage", "[", "]", "=", "'IDN DATA: EMPTY'", ";", "return", "$", "this...
Sends notification via cURL @param array $data Data array to be sent @return array $this->nameData() Result
[ "Sends", "notification", "via", "cURL" ]
d2808bf52e8d34be69414b444a00f1a9c8564930
https://github.com/IconoCoders/otp-simple-sdk/blob/d2808bf52e8d34be69414b444a00f1a9c8564930/Source/SimpleIdn.php#L115-L143
train
netgen/site-bundle
bundle/Controller/UserController.php
UserController.activationForm
public function activationForm(Request $request): Response { $form = $this->createActivationForm(); $form->handleRequest($request); if (!$form->isValid()) { return $this->render( $this->getConfigResolver()->getParameter('template.user.activate', 'ngsite'), [ 'form' => $form->createView(), ] ); } $users = $this->userService->loadUsersByEmail($form->get('email')->getData()); $activationRequestEvent = new UserEvents\ActivationRequestEvent( $form->get('email')->getData(), $users[0] ?? null ); $this->eventDispatcher->dispatch(SiteEvents::USER_ACTIVATION_REQUEST, $activationRequestEvent); return $this->render( $this->getConfigResolver()->getParameter('template.user.activate_sent', 'ngsite') ); }
php
public function activationForm(Request $request): Response { $form = $this->createActivationForm(); $form->handleRequest($request); if (!$form->isValid()) { return $this->render( $this->getConfigResolver()->getParameter('template.user.activate', 'ngsite'), [ 'form' => $form->createView(), ] ); } $users = $this->userService->loadUsersByEmail($form->get('email')->getData()); $activationRequestEvent = new UserEvents\ActivationRequestEvent( $form->get('email')->getData(), $users[0] ?? null ); $this->eventDispatcher->dispatch(SiteEvents::USER_ACTIVATION_REQUEST, $activationRequestEvent); return $this->render( $this->getConfigResolver()->getParameter('template.user.activate_sent', 'ngsite') ); }
[ "public", "function", "activationForm", "(", "Request", "$", "request", ")", ":", "Response", "{", "$", "form", "=", "$", "this", "->", "createActivationForm", "(", ")", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "if", "(", ...
Displays and validates the form for sending an activation mail.
[ "Displays", "and", "validates", "the", "form", "for", "sending", "an", "activation", "mail", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/UserController.php#L172-L198
train
netgen/site-bundle
bundle/Controller/UserController.php
UserController.activate
public function activate(string $hash): Response { $accountKey = $this->accountKeyRepository->getByHash($hash); if (!$accountKey instanceof EzUserAccountKey) { throw new NotFoundHttpException(); } if (time() - $accountKey->getTime() > $this->getConfigResolver()->getParameter('user.activate_hash_validity_time', 'ngsite')) { $this->accountKeyRepository->removeByHash($hash); return $this->render( $this->getConfigResolver()->getParameter('template.user.activate_done', 'ngsite'), [ 'error' => 'hash_expired', ] ); } try { $user = $this->userService->loadUser($accountKey->getUserId()); } catch (NotFoundException $e) { throw new NotFoundHttpException(); } $userUpdateStruct = $this->userService->newUserUpdateStruct(); $userUpdateStruct->enabled = true; $preActivateEvent = new UserEvents\PreActivateEvent($user, $userUpdateStruct); $this->eventDispatcher->dispatch(SiteEvents::USER_PRE_ACTIVATE, $preActivateEvent); $userUpdateStruct = $preActivateEvent->getUserUpdateStruct(); $user = $this->getRepository()->sudo( static function (Repository $repository) use ($user, $userUpdateStruct): User { return $repository->getUserService()->updateUser($user, $userUpdateStruct); } ); $postActivateEvent = new UserEvents\PostActivateEvent($user); $this->eventDispatcher->dispatch(SiteEvents::USER_POST_ACTIVATE, $postActivateEvent); return $this->render( $this->getConfigResolver()->getParameter('template.user.activate_done', 'ngsite') ); }
php
public function activate(string $hash): Response { $accountKey = $this->accountKeyRepository->getByHash($hash); if (!$accountKey instanceof EzUserAccountKey) { throw new NotFoundHttpException(); } if (time() - $accountKey->getTime() > $this->getConfigResolver()->getParameter('user.activate_hash_validity_time', 'ngsite')) { $this->accountKeyRepository->removeByHash($hash); return $this->render( $this->getConfigResolver()->getParameter('template.user.activate_done', 'ngsite'), [ 'error' => 'hash_expired', ] ); } try { $user = $this->userService->loadUser($accountKey->getUserId()); } catch (NotFoundException $e) { throw new NotFoundHttpException(); } $userUpdateStruct = $this->userService->newUserUpdateStruct(); $userUpdateStruct->enabled = true; $preActivateEvent = new UserEvents\PreActivateEvent($user, $userUpdateStruct); $this->eventDispatcher->dispatch(SiteEvents::USER_PRE_ACTIVATE, $preActivateEvent); $userUpdateStruct = $preActivateEvent->getUserUpdateStruct(); $user = $this->getRepository()->sudo( static function (Repository $repository) use ($user, $userUpdateStruct): User { return $repository->getUserService()->updateUser($user, $userUpdateStruct); } ); $postActivateEvent = new UserEvents\PostActivateEvent($user); $this->eventDispatcher->dispatch(SiteEvents::USER_POST_ACTIVATE, $postActivateEvent); return $this->render( $this->getConfigResolver()->getParameter('template.user.activate_done', 'ngsite') ); }
[ "public", "function", "activate", "(", "string", "$", "hash", ")", ":", "Response", "{", "$", "accountKey", "=", "$", "this", "->", "accountKeyRepository", "->", "getByHash", "(", "$", "hash", ")", ";", "if", "(", "!", "$", "accountKey", "instanceof", "E...
Activates the user by hash key. @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException If hash key does not exist
[ "Activates", "the", "user", "by", "hash", "key", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/UserController.php#L205-L249
train
netgen/site-bundle
bundle/Controller/UserController.php
UserController.forgotPassword
public function forgotPassword(Request $request): Response { $form = $this->createForgotPasswordForm(); $form->handleRequest($request); if (!$form->isValid()) { return $this->render( $this->getConfigResolver()->getParameter('template.user.forgot_password', 'ngsite'), [ 'form' => $form->createView(), ] ); } $users = $this->userService->loadUsersByEmail($form->get('email')->getData()); $passwordResetRequestEvent = new UserEvents\PasswordResetRequestEvent( $form->get('email')->getData(), $users[0] ?? null ); $this->eventDispatcher->dispatch(SiteEvents::USER_PASSWORD_RESET_REQUEST, $passwordResetRequestEvent); return $this->render( $this->getConfigResolver()->getParameter('template.user.forgot_password_sent', 'ngsite') ); }
php
public function forgotPassword(Request $request): Response { $form = $this->createForgotPasswordForm(); $form->handleRequest($request); if (!$form->isValid()) { return $this->render( $this->getConfigResolver()->getParameter('template.user.forgot_password', 'ngsite'), [ 'form' => $form->createView(), ] ); } $users = $this->userService->loadUsersByEmail($form->get('email')->getData()); $passwordResetRequestEvent = new UserEvents\PasswordResetRequestEvent( $form->get('email')->getData(), $users[0] ?? null ); $this->eventDispatcher->dispatch(SiteEvents::USER_PASSWORD_RESET_REQUEST, $passwordResetRequestEvent); return $this->render( $this->getConfigResolver()->getParameter('template.user.forgot_password_sent', 'ngsite') ); }
[ "public", "function", "forgotPassword", "(", "Request", "$", "request", ")", ":", "Response", "{", "$", "form", "=", "$", "this", "->", "createForgotPasswordForm", "(", ")", ";", "$", "form", "->", "handleRequest", "(", "$", "request", ")", ";", "if", "(...
Displays and validates the forgot password form.
[ "Displays", "and", "validates", "the", "forgot", "password", "form", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/UserController.php#L254-L280
train
netgen/site-bundle
bundle/Controller/UserController.php
UserController.resetPassword
public function resetPassword(Request $request, string $hash): Response { $accountKey = $this->accountKeyRepository->getByHash($hash); if (!$accountKey instanceof EzUserAccountKey) { throw new NotFoundHttpException(); } if (time() - $accountKey->getTime() > $this->getConfigResolver()->getParameter('user.forgot_password_hash_validity_time', 'ngsite')) { $this->accountKeyRepository->removeByHash($hash); return $this->render( $this->getConfigResolver()->getParameter('template.user.reset_password_done', 'ngsite'), [ 'error' => 'hash_expired', ] ); } try { $user = $this->userService->loadUser($accountKey->getUserId()); } catch (NotFoundException $e) { throw new NotFoundHttpException(); } $form = $this->createResetPasswordForm(); $form->handleRequest($request); if (!$form->isValid()) { return $this->render( $this->getConfigResolver()->getParameter('template.user.reset_password', 'ngsite'), [ 'form' => $form->createView(), ] ); } $data = $form->getData(); $userUpdateStruct = $this->userService->newUserUpdateStruct(); $userUpdateStruct->password = $data['password']; $prePasswordResetEvent = new UserEvents\PrePasswordResetEvent($user, $userUpdateStruct); $this->eventDispatcher->dispatch(SiteEvents::USER_PRE_PASSWORD_RESET, $prePasswordResetEvent); $userUpdateStruct = $prePasswordResetEvent->getUserUpdateStruct(); $user = $this->getRepository()->sudo( static function (Repository $repository) use ($user, $userUpdateStruct): User { return $repository->getUserService()->updateUser($user, $userUpdateStruct); } ); $postPasswordResetEvent = new UserEvents\PostPasswordResetEvent($user); $this->eventDispatcher->dispatch(SiteEvents::USER_POST_PASSWORD_RESET, $postPasswordResetEvent); return $this->render( $this->getConfigResolver()->getParameter('template.user.reset_password_done', 'ngsite') ); }
php
public function resetPassword(Request $request, string $hash): Response { $accountKey = $this->accountKeyRepository->getByHash($hash); if (!$accountKey instanceof EzUserAccountKey) { throw new NotFoundHttpException(); } if (time() - $accountKey->getTime() > $this->getConfigResolver()->getParameter('user.forgot_password_hash_validity_time', 'ngsite')) { $this->accountKeyRepository->removeByHash($hash); return $this->render( $this->getConfigResolver()->getParameter('template.user.reset_password_done', 'ngsite'), [ 'error' => 'hash_expired', ] ); } try { $user = $this->userService->loadUser($accountKey->getUserId()); } catch (NotFoundException $e) { throw new NotFoundHttpException(); } $form = $this->createResetPasswordForm(); $form->handleRequest($request); if (!$form->isValid()) { return $this->render( $this->getConfigResolver()->getParameter('template.user.reset_password', 'ngsite'), [ 'form' => $form->createView(), ] ); } $data = $form->getData(); $userUpdateStruct = $this->userService->newUserUpdateStruct(); $userUpdateStruct->password = $data['password']; $prePasswordResetEvent = new UserEvents\PrePasswordResetEvent($user, $userUpdateStruct); $this->eventDispatcher->dispatch(SiteEvents::USER_PRE_PASSWORD_RESET, $prePasswordResetEvent); $userUpdateStruct = $prePasswordResetEvent->getUserUpdateStruct(); $user = $this->getRepository()->sudo( static function (Repository $repository) use ($user, $userUpdateStruct): User { return $repository->getUserService()->updateUser($user, $userUpdateStruct); } ); $postPasswordResetEvent = new UserEvents\PostPasswordResetEvent($user); $this->eventDispatcher->dispatch(SiteEvents::USER_POST_PASSWORD_RESET, $postPasswordResetEvent); return $this->render( $this->getConfigResolver()->getParameter('template.user.reset_password_done', 'ngsite') ); }
[ "public", "function", "resetPassword", "(", "Request", "$", "request", ",", "string", "$", "hash", ")", ":", "Response", "{", "$", "accountKey", "=", "$", "this", "->", "accountKeyRepository", "->", "getByHash", "(", "$", "hash", ")", ";", "if", "(", "!"...
Displays and validates the reset password form. @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException If hash key does not exist
[ "Displays", "and", "validates", "the", "reset", "password", "form", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/UserController.php#L287-L345
train
netgen/site-bundle
bundle/Controller/UserController.php
UserController.createActivationForm
protected function createActivationForm(): FormInterface { return $this->createFormBuilder(null, ['translation_domain' => 'ngsite_user']) ->add( 'email', EmailType::class, [ 'constraints' => [ new Constraints\Email(), new Constraints\NotBlank(), ], ] )->getForm(); }
php
protected function createActivationForm(): FormInterface { return $this->createFormBuilder(null, ['translation_domain' => 'ngsite_user']) ->add( 'email', EmailType::class, [ 'constraints' => [ new Constraints\Email(), new Constraints\NotBlank(), ], ] )->getForm(); }
[ "protected", "function", "createActivationForm", "(", ")", ":", "FormInterface", "{", "return", "$", "this", "->", "createFormBuilder", "(", "null", ",", "[", "'translation_domain'", "=>", "'ngsite_user'", "]", ")", "->", "add", "(", "'email'", ",", "EmailType",...
Creates activation form.
[ "Creates", "activation", "form", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/UserController.php#L350-L363
train
netgen/site-bundle
bundle/Controller/UserController.php
UserController.createResetPasswordForm
protected function createResetPasswordForm(): FormInterface { $minLength = (int) $this->getParameter('netgen.ezforms.form.type.fieldtype.ezuser.parameters.min_password_length'); $passwordConstraints = [ new Constraints\NotBlank(), ]; if ($minLength > 0) { $passwordConstraints[] = new Constraints\Length( [ 'min' => $minLength, ] ); } $passwordOptions = [ 'type' => PasswordType::class, 'required' => true, 'options' => [ 'constraints' => $passwordConstraints, ], ]; return $this->createFormBuilder(null, ['translation_domain' => 'ngsite_user']) ->add('password', RepeatedType::class, $passwordOptions) ->getForm(); }
php
protected function createResetPasswordForm(): FormInterface { $minLength = (int) $this->getParameter('netgen.ezforms.form.type.fieldtype.ezuser.parameters.min_password_length'); $passwordConstraints = [ new Constraints\NotBlank(), ]; if ($minLength > 0) { $passwordConstraints[] = new Constraints\Length( [ 'min' => $minLength, ] ); } $passwordOptions = [ 'type' => PasswordType::class, 'required' => true, 'options' => [ 'constraints' => $passwordConstraints, ], ]; return $this->createFormBuilder(null, ['translation_domain' => 'ngsite_user']) ->add('password', RepeatedType::class, $passwordOptions) ->getForm(); }
[ "protected", "function", "createResetPasswordForm", "(", ")", ":", "FormInterface", "{", "$", "minLength", "=", "(", "int", ")", "$", "this", "->", "getParameter", "(", "'netgen.ezforms.form.type.fieldtype.ezuser.parameters.min_password_length'", ")", ";", "$", "passwor...
Creates reset password form.
[ "Creates", "reset", "password", "form", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Controller/UserController.php#L386-L413
train
netgen/site-bundle
bundle/DependencyInjection/Compiler/LocationFactoryPass.php
LocationFactoryPass.process
public function process(ContainerBuilder $container): void { if (!$container->has('ngsite.menu.factory.location')) { return; } $factory = $container->findDefinition('ngsite.menu.factory.location'); $extensions = []; foreach ($container->findTaggedServiceIds('ngsite.menu.factory.location.extension') as $extension => $tags) { foreach ($tags as $tag) { $priority = (int) ($tag[0]['priority'] ?? 0); $extensions[$priority][] = new Reference($extension); } } krsort($extensions); $extensions = array_merge(...$extensions); $factory->replaceArgument(2, $extensions); }
php
public function process(ContainerBuilder $container): void { if (!$container->has('ngsite.menu.factory.location')) { return; } $factory = $container->findDefinition('ngsite.menu.factory.location'); $extensions = []; foreach ($container->findTaggedServiceIds('ngsite.menu.factory.location.extension') as $extension => $tags) { foreach ($tags as $tag) { $priority = (int) ($tag[0]['priority'] ?? 0); $extensions[$priority][] = new Reference($extension); } } krsort($extensions); $extensions = array_merge(...$extensions); $factory->replaceArgument(2, $extensions); }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "if", "(", "!", "$", "container", "->", "has", "(", "'ngsite.menu.factory.location'", ")", ")", "{", "return", ";", "}", "$", "factory", "=", "$", "container...
Injects location factory extensions into the factory.
[ "Injects", "location", "factory", "extensions", "into", "the", "factory", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/DependencyInjection/Compiler/LocationFactoryPass.php#L16-L37
train
cedx/coveralls.php
RoboFile.php
RoboFile.upgrade
function upgrade(): Result { $composer = PHP_OS_FAMILY == 'Windows' ? 'php '.escapeshellarg('C:\Program Files\PHP\share\composer.phar') : 'composer'; return $this->taskExecStack() ->exec('git reset --hard') ->exec('git fetch --all --prune') ->exec('git pull --rebase') ->exec("$composer update --no-interaction") ->run(); }
php
function upgrade(): Result { $composer = PHP_OS_FAMILY == 'Windows' ? 'php '.escapeshellarg('C:\Program Files\PHP\share\composer.phar') : 'composer'; return $this->taskExecStack() ->exec('git reset --hard') ->exec('git fetch --all --prune') ->exec('git pull --rebase') ->exec("$composer update --no-interaction") ->run(); }
[ "function", "upgrade", "(", ")", ":", "Result", "{", "$", "composer", "=", "PHP_OS_FAMILY", "==", "'Windows'", "?", "'php '", ".", "escapeshellarg", "(", "'C:\\Program Files\\PHP\\share\\composer.phar'", ")", ":", "'composer'", ";", "return", "$", "this", "->", ...
Upgrades the project to the latest revision. @return Result The task result.
[ "Upgrades", "the", "project", "to", "the", "latest", "revision", "." ]
c196de0f92e06d5143ba90ebab18c8e384316cc0
https://github.com/cedx/coveralls.php/blob/c196de0f92e06d5143ba90ebab18c8e384316cc0/RoboFile.php#L85-L93
train
cedx/coveralls.php
RoboFile.php
RoboFile.watch
function watch(): Result { $this->build(); return $this->taskWatch() ->monitor('lib', function() { $this->build(); }) ->monitor('test', function() { $this->test(); }) ->run(); }
php
function watch(): Result { $this->build(); return $this->taskWatch() ->monitor('lib', function() { $this->build(); }) ->monitor('test', function() { $this->test(); }) ->run(); }
[ "function", "watch", "(", ")", ":", "Result", "{", "$", "this", "->", "build", "(", ")", ";", "return", "$", "this", "->", "taskWatch", "(", ")", "->", "monitor", "(", "'lib'", ",", "function", "(", ")", "{", "$", "this", "->", "build", "(", ")",...
Watches for file changes. @return Result The task result.
[ "Watches", "for", "file", "changes", "." ]
c196de0f92e06d5143ba90ebab18c8e384316cc0
https://github.com/cedx/coveralls.php/blob/c196de0f92e06d5143ba90ebab18c8e384316cc0/RoboFile.php#L108-L114
train
smartboxgroup/integration-framework-bundle
Components/Queues/Drivers/AmqpQueueDriver.php
AmqpQueueDriver.receiveNoWait
public function receiveNoWait() { if ($this->currentEnvelope) { throw new \RuntimeException( 'AmqpQueueDriver: This driver has a message that was not acknowledged yet. A message must be processed and acknowledged before receiving new messages.' ); } $this->dequeueingTimeMs = 0; $this->currentEnvelope = $this->queue->get(); $msg = null; if (!$this->currentEnvelope) { return null; } $start = microtime(true); $deserializationContext = new DeserializationContext(); /** @var QueueMessageInterface $msg */ $msg = $this->getSerializer()->deserialize($this->currentEnvelope->getBody(), SerializableInterface::class, $this->format, $deserializationContext); foreach ($this->currentEnvelope->getHeaders() as $header => $value) { $msg->setHeader($header, $value); } // Calculate how long it took to deserilize the message $this->dequeueingTimeMs = (int) ((microtime(true) - $start) * 1000); return $msg; }
php
public function receiveNoWait() { if ($this->currentEnvelope) { throw new \RuntimeException( 'AmqpQueueDriver: This driver has a message that was not acknowledged yet. A message must be processed and acknowledged before receiving new messages.' ); } $this->dequeueingTimeMs = 0; $this->currentEnvelope = $this->queue->get(); $msg = null; if (!$this->currentEnvelope) { return null; } $start = microtime(true); $deserializationContext = new DeserializationContext(); /** @var QueueMessageInterface $msg */ $msg = $this->getSerializer()->deserialize($this->currentEnvelope->getBody(), SerializableInterface::class, $this->format, $deserializationContext); foreach ($this->currentEnvelope->getHeaders() as $header => $value) { $msg->setHeader($header, $value); } // Calculate how long it took to deserilize the message $this->dequeueingTimeMs = (int) ((microtime(true) - $start) * 1000); return $msg; }
[ "public", "function", "receiveNoWait", "(", ")", "{", "if", "(", "$", "this", "->", "currentEnvelope", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'AmqpQueueDriver: This driver has a message that was not acknowledged yet. A message must be processed and acknowledg...
Returns One Serializable object from the queue. It requires to subscribe previously to a specific queue @throws \Exception @return \Smartbox\Integration\FrameworkBundle\Components\Queues\QueueMessageInterface|null
[ "Returns", "One", "Serializable", "object", "from", "the", "queue", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/Queues/Drivers/AmqpQueueDriver.php#L223-L255
train
netgen/site-bundle
bundle/DependencyInjection/Compiler/ImagineIOResolverPass.php
ImagineIOResolverPass.process
public function process(ContainerBuilder $container): void { if ($container->has('ezpublish.image_alias.imagine.cache_resolver')) { $container ->findDefinition('ezpublish.image_alias.imagine.cache_resolver') ->setClass(IORepositoryResolver::class); } }
php
public function process(ContainerBuilder $container): void { if ($container->has('ezpublish.image_alias.imagine.cache_resolver')) { $container ->findDefinition('ezpublish.image_alias.imagine.cache_resolver') ->setClass(IORepositoryResolver::class); } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "if", "(", "$", "container", "->", "has", "(", "'ezpublish.image_alias.imagine.cache_resolver'", ")", ")", "{", "$", "container", "->", "findDefinition", "(", "'ez...
Overrides the IO resolver to disable generating absolute URIs to images.
[ "Overrides", "the", "IO", "resolver", "to", "disable", "generating", "absolute", "URIs", "to", "images", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/DependencyInjection/Compiler/ImagineIOResolverPass.php#L16-L23
train
netgen/site-bundle
bundle/Helper/MailHelper.php
MailHelper.sendMail
public function sendMail($receivers, string $subject, string $template, array $templateParameters = [], $sender = null): int { try { $sender = $this->getSender($sender); } catch (InvalidArgumentException $e) { $this->logger->error($e->getMessage()); return -1; } $body = $this->twig->render($template, $templateParameters + $this->getDefaultTemplateParameters()); $subject = $this->translator->trans($subject, [], 'ngsite_mail'); $message = new Swift_Message(); $message ->setTo($receivers) ->setSubject($this->siteName . ': ' . $subject) ->setBody($body, 'text/html'); $message->setSender($sender); $message->setFrom($sender); return $this->mailer->send($message); }
php
public function sendMail($receivers, string $subject, string $template, array $templateParameters = [], $sender = null): int { try { $sender = $this->getSender($sender); } catch (InvalidArgumentException $e) { $this->logger->error($e->getMessage()); return -1; } $body = $this->twig->render($template, $templateParameters + $this->getDefaultTemplateParameters()); $subject = $this->translator->trans($subject, [], 'ngsite_mail'); $message = new Swift_Message(); $message ->setTo($receivers) ->setSubject($this->siteName . ': ' . $subject) ->setBody($body, 'text/html'); $message->setSender($sender); $message->setFrom($sender); return $this->mailer->send($message); }
[ "public", "function", "sendMail", "(", "$", "receivers", ",", "string", "$", "subject", ",", "string", "$", "template", ",", "array", "$", "templateParameters", "=", "[", "]", ",", "$", "sender", "=", "null", ")", ":", "int", "{", "try", "{", "$", "s...
Sends an mail. Receivers can be: a string: info@netgen.hr or: array( 'info@netgen.hr' => 'Netgen Site' ) or array( 'info@netgen.hr', 'example@netgen.hr' ) or array( 'info@netgen.hr' => 'Netgen Site', 'example@netgen.hr' => 'Example' ) Sender can be: a string: info@netgen.hr an array: array( 'info@netgen.hr' => 'Netgen Site' ) @param mixed $receivers @param mixed|null $sender
[ "Sends", "an", "mail", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Helper/MailHelper.php#L99-L124
train
netgen/site-bundle
bundle/Helper/MailHelper.php
MailHelper.getDefaultTemplateParameters
protected function getDefaultTemplateParameters(): array { if ($this->siteUrl === null) { $this->siteUrl = $this->urlGenerator->generate( 'ez_urlalias', [ 'locationId' => $this->configResolver->getParameter('content.tree_root.location_id'), ], UrlGeneratorInterface::ABSOLUTE_URL ); } if ($this->siteName === null) { $this->siteName = trim($this->siteInfoHelper->getSiteInfoContent()->getField('site_name')->value->text); } return [ 'site_url' => $this->siteUrl, 'site_name' => $this->siteName, ]; }
php
protected function getDefaultTemplateParameters(): array { if ($this->siteUrl === null) { $this->siteUrl = $this->urlGenerator->generate( 'ez_urlalias', [ 'locationId' => $this->configResolver->getParameter('content.tree_root.location_id'), ], UrlGeneratorInterface::ABSOLUTE_URL ); } if ($this->siteName === null) { $this->siteName = trim($this->siteInfoHelper->getSiteInfoContent()->getField('site_name')->value->text); } return [ 'site_url' => $this->siteUrl, 'site_name' => $this->siteName, ]; }
[ "protected", "function", "getDefaultTemplateParameters", "(", ")", ":", "array", "{", "if", "(", "$", "this", "->", "siteUrl", "===", "null", ")", "{", "$", "this", "->", "siteUrl", "=", "$", "this", "->", "urlGenerator", "->", "generate", "(", "'ez_urlali...
Returns an array of parameters that will be passed to every mail template.
[ "Returns", "an", "array", "of", "parameters", "that", "will", "be", "passed", "to", "every", "mail", "template", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/Helper/MailHelper.php#L129-L149
train
netgen/ngsymfonytools
classes/ngsymfonytoolsapicontentconverter.php
NgSymfonyToolsApiContentConverter.instance
public static function instance() { if ( self::$instance === null ) { $serviceContainer = ezpKernel::instance()->getServiceContainer(); self::$instance = new self( $serviceContainer->get( 'ezpublish.api.repository' ) ); } return self::$instance; }
php
public static function instance() { if ( self::$instance === null ) { $serviceContainer = ezpKernel::instance()->getServiceContainer(); self::$instance = new self( $serviceContainer->get( 'ezpublish.api.repository' ) ); } return self::$instance; }
[ "public", "static", "function", "instance", "(", ")", "{", "if", "(", "self", "::", "$", "instance", "===", "null", ")", "{", "$", "serviceContainer", "=", "ezpKernel", "::", "instance", "(", ")", "->", "getServiceContainer", "(", ")", ";", "self", "::",...
Instantiates the class object @return NgSymfonyToolsApiContentConverter
[ "Instantiates", "the", "class", "object" ]
58abf97996ddd1d4f969d8c64ce6998b9d1a5c27
https://github.com/netgen/ngsymfonytools/blob/58abf97996ddd1d4f969d8c64ce6998b9d1a5c27/classes/ngsymfonytoolsapicontentconverter.php#L22-L31
train
netgen/ngsymfonytools
classes/ngsymfonytoolsapicontentconverter.php
NgSymfonyToolsApiContentConverter.convert
public function convert( $object ) { if ( $object instanceof eZContentObject ) { return $this->repository->getContentService()->loadContent( $object->attribute( 'id' ) ); } else if ( $object instanceof eZContentObjectTreeNode ) { return $this->repository->getLocationService()->loadLocation( $object->attribute( 'node_id' ) ); } return $object; }
php
public function convert( $object ) { if ( $object instanceof eZContentObject ) { return $this->repository->getContentService()->loadContent( $object->attribute( 'id' ) ); } else if ( $object instanceof eZContentObjectTreeNode ) { return $this->repository->getLocationService()->loadLocation( $object->attribute( 'node_id' ) ); } return $object; }
[ "public", "function", "convert", "(", "$", "object", ")", "{", "if", "(", "$", "object", "instanceof", "eZContentObject", ")", "{", "return", "$", "this", "->", "repository", "->", "getContentService", "(", ")", "->", "loadContent", "(", "$", "object", "->...
Converts eZ Publish legacy objects and nodes to content and locations @param mixed $object @return mixed
[ "Converts", "eZ", "Publish", "legacy", "objects", "and", "nodes", "to", "content", "and", "locations" ]
58abf97996ddd1d4f969d8c64ce6998b9d1a5c27
https://github.com/netgen/ngsymfonytools/blob/58abf97996ddd1d4f969d8c64ce6998b9d1a5c27/classes/ngsymfonytoolsapicontentconverter.php#L59-L71
train
netgen/site-bundle
bundle/DependencyInjection/Compiler/RelationListFieldTypePass.php
RelationListFieldTypePass.process
public function process(ContainerBuilder $container): void { if ($container->has('ezpublish.fieldType.ezobjectrelationlist')) { $container ->findDefinition('ezpublish.fieldType.ezobjectrelationlist') ->setClass(Type::class); } if ($container->has('ezpublish.fieldType.ezobjectrelationlist.converter')) { $container ->findDefinition('ezpublish.fieldType.ezobjectrelationlist.converter') ->setClass(RelationListConverter::class); } }
php
public function process(ContainerBuilder $container): void { if ($container->has('ezpublish.fieldType.ezobjectrelationlist')) { $container ->findDefinition('ezpublish.fieldType.ezobjectrelationlist') ->setClass(Type::class); } if ($container->has('ezpublish.fieldType.ezobjectrelationlist.converter')) { $container ->findDefinition('ezpublish.fieldType.ezobjectrelationlist.converter') ->setClass(RelationListConverter::class); } }
[ "public", "function", "process", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "if", "(", "$", "container", "->", "has", "(", "'ezpublish.fieldType.ezobjectrelationlist'", ")", ")", "{", "$", "container", "->", "findDefinition", "(", "'ezpubl...
Overrides ezrelationlist field type with own implementations.
[ "Overrides", "ezrelationlist", "field", "type", "with", "own", "implementations", "." ]
4198c8412ffdb6692b80d35e05c8ba331365b746
https://github.com/netgen/site-bundle/blob/4198c8412ffdb6692b80d35e05c8ba331365b746/bundle/DependencyInjection/Compiler/RelationListFieldTypePass.php#L17-L30
train
spiral/router
src/Traits/VerbsTrait.php
VerbsTrait.withVerbs
public function withVerbs(string ...$verbs): RouteInterface { foreach ($verbs as &$verb) { $verb = strtoupper($verb); if (!in_array($verb, RouteInterface::VERBS)) { throw new RouteException("Invalid HTTP verb `{$verb}`."); } unset($verb); } $route = clone $this; $route->verbs = $verbs; return $route; }
php
public function withVerbs(string ...$verbs): RouteInterface { foreach ($verbs as &$verb) { $verb = strtoupper($verb); if (!in_array($verb, RouteInterface::VERBS)) { throw new RouteException("Invalid HTTP verb `{$verb}`."); } unset($verb); } $route = clone $this; $route->verbs = $verbs; return $route; }
[ "public", "function", "withVerbs", "(", "string", "...", "$", "verbs", ")", ":", "RouteInterface", "{", "foreach", "(", "$", "verbs", "as", "&", "$", "verb", ")", "{", "$", "verb", "=", "strtoupper", "(", "$", "verb", ")", ";", "if", "(", "!", "in_...
Attach specific list of HTTP verbs to the route. @param string ...$verbs @return RouteInterface|$this @throws RouteException
[ "Attach", "specific", "list", "of", "HTTP", "verbs", "to", "the", "route", "." ]
35721d06231d5650402eb93ac7f3ade00cd1b640
https://github.com/spiral/router/blob/35721d06231d5650402eb93ac7f3ade00cd1b640/src/Traits/VerbsTrait.php#L29-L44
train
Prezent/prezent-crud-bundle
src/Controller/CrudController.php
CrudController.editAction
public function editAction(Request $request, $id) { $configuration = $this->getConfiguration($request); $dispatcher = $configuration->getEventDispatcher(); $om = $this->getObjectManager(); if (!$configuration->getFormType()) { throw new \RuntimeException('You must set the formType on the CRUD configuration'); } $object = $this->findObject($request, $id); $form = $this->createForm($configuration->getFormType(), $object, $configuration->getFormOptions()); $event = new PreSubmitEvent($configuration, $request, $object, $form); $dispatcher->dispatch(CrudEvents::PRE_SUBMIT, $event); if ($event->hasResponse()) { return $event->getResponse(); } $form->handleRequest($request); if ($form->isSubmitted()) { if ($form->isValid()) { $om->persist($object); $event = new PreFlushEvent($configuration, $request, $object); $dispatcher->dispatch(CrudEvents::PRE_FLUSH, $event); if ($event->hasResponse()) { return $event->getResponse(); } $event = new PostFlushEvent($configuration, $request, $object); try { $om->flush(); $this->addFlash('success', sprintf('flash.%s.edit.success', $configuration->getName())); } catch (\Exception $e) { $event->setException($e); $this->addFlash('error', sprintf('flash.%s.edit.error', $configuration->getName())); } $dispatcher->dispatch(CrudEvents::POST_FLUSH, $event); if ($event->hasResponse()) { return $event->getResponse(); } return $this->redirectToRoute( $configuration->getRoutePrefix() . 'index', $configuration->getRouteParameters() ); } else { $event = new ValidationFailedEvent($configuration, $request, $object, $form); $dispatcher->dispatch(CrudEvents::VALIDATION_FAILED, $event); if ($event->hasResponse()) { return $response; } } } return $this->render($this->getTemplate($request, 'edit'), array_merge([ 'base_template' => $this->getTemplate($request, 'base'), 'config' => $configuration, 'form' => $form->createView(), 'object' => $object, ], $configuration->getTemplateVariables())); }
php
public function editAction(Request $request, $id) { $configuration = $this->getConfiguration($request); $dispatcher = $configuration->getEventDispatcher(); $om = $this->getObjectManager(); if (!$configuration->getFormType()) { throw new \RuntimeException('You must set the formType on the CRUD configuration'); } $object = $this->findObject($request, $id); $form = $this->createForm($configuration->getFormType(), $object, $configuration->getFormOptions()); $event = new PreSubmitEvent($configuration, $request, $object, $form); $dispatcher->dispatch(CrudEvents::PRE_SUBMIT, $event); if ($event->hasResponse()) { return $event->getResponse(); } $form->handleRequest($request); if ($form->isSubmitted()) { if ($form->isValid()) { $om->persist($object); $event = new PreFlushEvent($configuration, $request, $object); $dispatcher->dispatch(CrudEvents::PRE_FLUSH, $event); if ($event->hasResponse()) { return $event->getResponse(); } $event = new PostFlushEvent($configuration, $request, $object); try { $om->flush(); $this->addFlash('success', sprintf('flash.%s.edit.success', $configuration->getName())); } catch (\Exception $e) { $event->setException($e); $this->addFlash('error', sprintf('flash.%s.edit.error', $configuration->getName())); } $dispatcher->dispatch(CrudEvents::POST_FLUSH, $event); if ($event->hasResponse()) { return $event->getResponse(); } return $this->redirectToRoute( $configuration->getRoutePrefix() . 'index', $configuration->getRouteParameters() ); } else { $event = new ValidationFailedEvent($configuration, $request, $object, $form); $dispatcher->dispatch(CrudEvents::VALIDATION_FAILED, $event); if ($event->hasResponse()) { return $response; } } } return $this->render($this->getTemplate($request, 'edit'), array_merge([ 'base_template' => $this->getTemplate($request, 'base'), 'config' => $configuration, 'form' => $form->createView(), 'object' => $object, ], $configuration->getTemplateVariables())); }
[ "public", "function", "editAction", "(", "Request", "$", "request", ",", "$", "id", ")", "{", "$", "configuration", "=", "$", "this", "->", "getConfiguration", "(", "$", "request", ")", ";", "$", "dispatcher", "=", "$", "configuration", "->", "getEventDisp...
Edit an object @Route("/edit/{id}") @param Request $request @param $id @return RedirectResponse|Response
[ "Edit", "an", "object" ]
bb8bcf92cecc2acae08b8a672876b4972175ca24
https://github.com/Prezent/prezent-crud-bundle/blob/bb8bcf92cecc2acae08b8a672876b4972175ca24/src/Controller/CrudController.php#L175-L244
train
Prezent/prezent-crud-bundle
src/Controller/CrudController.php
CrudController.findObject
protected function findObject(Request $request, $id) { $configuration = $this->getConfiguration($request); if (!($object = $this->getRepository()->find($id))) { throw $this->createNotFoundException( sprintf('Object %s(%s) not found', $configuration->getEntityClass(), $id) ); } return $object; }
php
protected function findObject(Request $request, $id) { $configuration = $this->getConfiguration($request); if (!($object = $this->getRepository()->find($id))) { throw $this->createNotFoundException( sprintf('Object %s(%s) not found', $configuration->getEntityClass(), $id) ); } return $object; }
[ "protected", "function", "findObject", "(", "Request", "$", "request", ",", "$", "id", ")", "{", "$", "configuration", "=", "$", "this", "->", "getConfiguration", "(", "$", "request", ")", ";", "if", "(", "!", "(", "$", "object", "=", "$", "this", "-...
Find an object by ID @param mixed $id @return object @throws NotFoundHttpException
[ "Find", "an", "object", "by", "ID" ]
bb8bcf92cecc2acae08b8a672876b4972175ca24
https://github.com/Prezent/prezent-crud-bundle/blob/bb8bcf92cecc2acae08b8a672876b4972175ca24/src/Controller/CrudController.php#L340-L351
train
Prezent/prezent-crud-bundle
src/Controller/CrudController.php
CrudController.getTemplate
protected function getTemplate(Request $request, $action) { $templates = $this->get('prezent_crud.template_guesser')->guessTemplateNames([$this, $action], $request); foreach ($templates as $template) { if ($this->get('twig')->getLoader()->exists($template)) { return $template; } } return array_shift($templates); // This ensures a proper error message about a missing template }
php
protected function getTemplate(Request $request, $action) { $templates = $this->get('prezent_crud.template_guesser')->guessTemplateNames([$this, $action], $request); foreach ($templates as $template) { if ($this->get('twig')->getLoader()->exists($template)) { return $template; } } return array_shift($templates); // This ensures a proper error message about a missing template }
[ "protected", "function", "getTemplate", "(", "Request", "$", "request", ",", "$", "action", ")", "{", "$", "templates", "=", "$", "this", "->", "get", "(", "'prezent_crud.template_guesser'", ")", "->", "guessTemplateNames", "(", "[", "$", "this", ",", "$", ...
Get the template for an action @param Request $request @param string $action @return string
[ "Get", "the", "template", "for", "an", "action" ]
bb8bcf92cecc2acae08b8a672876b4972175ca24
https://github.com/Prezent/prezent-crud-bundle/blob/bb8bcf92cecc2acae08b8a672876b4972175ca24/src/Controller/CrudController.php#L371-L382
train
smartboxgroup/integration-framework-bundle
Components/DB/DBConfigurableConsumer.php
DBConfigurableConsumer.readMessage
protected function readMessage(EndpointInterface $endpoint) { $options = $endpoint->getOptions(); $method = $options[NoSQLConfigurableProtocol::OPTION_METHOD]; $config = $this->methodsConfiguration[$method]; $steps = $config[ConfigurableConsumerInterface::CONFIG_QUERY_STEPS]; $context = $this->getConfHelper()->createContext($options); try { $this->configurableStepsProvider->executeSteps($steps, $options, $context); $result = $this->getConfHelper()->resolve( $config[ConfigurableConsumerInterface::CONFIG_QUERY_RESULT], $context ); } catch (NoResultsException $exception) { $result = null; if ($options[ConfigurableDbalProtocol::OPTION_STOP_ON_NO_RESULTS]) { $this->stop(); } } if (null == $result) { return null; } elseif (is_array($result)) { $result = new SerializableArray($result); } $context = new Context([ Context::FLOWS_VERSION => $this->getFlowsVersion(), Context::TRANSACTION_ID => uniqid('', true), Context::ORIGINAL_FROM => $endpoint->getURI(), ]); return $this->smartesbHelper->getMessageFactory()->createMessage($result, [], $context); }
php
protected function readMessage(EndpointInterface $endpoint) { $options = $endpoint->getOptions(); $method = $options[NoSQLConfigurableProtocol::OPTION_METHOD]; $config = $this->methodsConfiguration[$method]; $steps = $config[ConfigurableConsumerInterface::CONFIG_QUERY_STEPS]; $context = $this->getConfHelper()->createContext($options); try { $this->configurableStepsProvider->executeSteps($steps, $options, $context); $result = $this->getConfHelper()->resolve( $config[ConfigurableConsumerInterface::CONFIG_QUERY_RESULT], $context ); } catch (NoResultsException $exception) { $result = null; if ($options[ConfigurableDbalProtocol::OPTION_STOP_ON_NO_RESULTS]) { $this->stop(); } } if (null == $result) { return null; } elseif (is_array($result)) { $result = new SerializableArray($result); } $context = new Context([ Context::FLOWS_VERSION => $this->getFlowsVersion(), Context::TRANSACTION_ID => uniqid('', true), Context::ORIGINAL_FROM => $endpoint->getURI(), ]); return $this->smartesbHelper->getMessageFactory()->createMessage($result, [], $context); }
[ "protected", "function", "readMessage", "(", "EndpointInterface", "$", "endpoint", ")", "{", "$", "options", "=", "$", "endpoint", "->", "getOptions", "(", ")", ";", "$", "method", "=", "$", "options", "[", "NoSQLConfigurableProtocol", "::", "OPTION_METHOD", "...
Reads a message from the NoSQL database executing the configured steps. @param EndpointInterface $endpoint @return \Smartbox\Integration\FrameworkBundle\Core\Messages\Message
[ "Reads", "a", "message", "from", "the", "NoSQL", "database", "executing", "the", "configured", "steps", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/DB/DBConfigurableConsumer.php#L53-L89
train
smartboxgroup/integration-framework-bundle
Components/DB/DBConfigurableConsumer.php
DBConfigurableConsumer.onConsume
protected function onConsume(EndpointInterface $endpoint, MessageInterface $message) { $options = $endpoint->getOptions(); $method = $options[NoSQLConfigurableProtocol::OPTION_METHOD]; $config = $this->methodsConfiguration[$method]; $steps = $config[ConfigurableConsumerInterface::CONFIG_ON_CONSUME]; $context = $this->getConfHelper()->createContext($options, $message); $this->configurableStepsProvider->executeSteps($steps, $options, $context); }
php
protected function onConsume(EndpointInterface $endpoint, MessageInterface $message) { $options = $endpoint->getOptions(); $method = $options[NoSQLConfigurableProtocol::OPTION_METHOD]; $config = $this->methodsConfiguration[$method]; $steps = $config[ConfigurableConsumerInterface::CONFIG_ON_CONSUME]; $context = $this->getConfHelper()->createContext($options, $message); $this->configurableStepsProvider->executeSteps($steps, $options, $context); }
[ "protected", "function", "onConsume", "(", "EndpointInterface", "$", "endpoint", ",", "MessageInterface", "$", "message", ")", "{", "$", "options", "=", "$", "endpoint", "->", "getOptions", "(", ")", ";", "$", "method", "=", "$", "options", "[", "NoSQLConfig...
Executes the necessary actions after the message has been consumed. @param EndpointInterface $endpoint @param MessageInterface $message
[ "Executes", "the", "necessary", "actions", "after", "the", "message", "has", "been", "consumed", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Components/DB/DBConfigurableConsumer.php#L97-L107
train
smartboxgroup/integration-framework-bundle
Tools/Evaluator/CustomExpressionLanguageProvider.php
CustomExpressionLanguageProvider.createNumberFormat
protected function createNumberFormat() { return new ExpressionFunction( 'numberFormat', function ($number, $decimals = 0, $dec_point = '.', $thousands_sep = ',') { return sprintf('( %1$s !== null ? number_format(%1$s, %2$s, %3$s, %4$s)) : null', $number, $decimals, $dec_point, $thousands_sep); }, function ($arguments, $number, $decimals = 0, $dec_point = '.', $thousands_sep = ',') { if (null === $number) { return null; } return number_format($number, $decimals, $dec_point, $thousands_sep); } ); }
php
protected function createNumberFormat() { return new ExpressionFunction( 'numberFormat', function ($number, $decimals = 0, $dec_point = '.', $thousands_sep = ',') { return sprintf('( %1$s !== null ? number_format(%1$s, %2$s, %3$s, %4$s)) : null', $number, $decimals, $dec_point, $thousands_sep); }, function ($arguments, $number, $decimals = 0, $dec_point = '.', $thousands_sep = ',') { if (null === $number) { return null; } return number_format($number, $decimals, $dec_point, $thousands_sep); } ); }
[ "protected", "function", "createNumberFormat", "(", ")", "{", "return", "new", "ExpressionFunction", "(", "'numberFormat'", ",", "function", "(", "$", "number", ",", "$", "decimals", "=", "0", ",", "$", "dec_point", "=", "'.'", ",", "$", "thousands_sep", "="...
Exposes php number_format. string numberFormat ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," ) returns null if null passed @return ExpressionFunction
[ "Exposes", "php", "number_format", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Tools/Evaluator/CustomExpressionLanguageProvider.php#L179-L194
train
smartboxgroup/integration-framework-bundle
Tools/Evaluator/CustomExpressionLanguageProvider.php
CustomExpressionLanguageProvider.createSliceFunction
protected function createSliceFunction() { return new ExpressionFunction( 'slice', function ($array, $start, $length = null, $preserveKeys = false) { return sprintf('array_slice(%s, %s, %s, %s)', $array, $start, $length, $preserveKeys); }, function ($arguments, $array, $start, $length = null, $preserveKeys = false) { return array_slice($array, $start, $length, $preserveKeys); } ); }
php
protected function createSliceFunction() { return new ExpressionFunction( 'slice', function ($array, $start, $length = null, $preserveKeys = false) { return sprintf('array_slice(%s, %s, %s, %s)', $array, $start, $length, $preserveKeys); }, function ($arguments, $array, $start, $length = null, $preserveKeys = false) { return array_slice($array, $start, $length, $preserveKeys); } ); }
[ "protected", "function", "createSliceFunction", "(", ")", "{", "return", "new", "ExpressionFunction", "(", "'slice'", ",", "function", "(", "$", "array", ",", "$", "start", ",", "$", "length", "=", "null", ",", "$", "preserveKeys", "=", "false", ")", "{", ...
Returns the sequence of elements from an array based on start and length parameters. @return ExpressionFunction
[ "Returns", "the", "sequence", "of", "elements", "from", "an", "array", "based", "on", "start", "and", "length", "parameters", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Tools/Evaluator/CustomExpressionLanguageProvider.php#L235-L246
train
smartboxgroup/integration-framework-bundle
Tools/Evaluator/CustomExpressionLanguageProvider.php
CustomExpressionLanguageProvider.createExplodeFunction
protected function createExplodeFunction() { return new ExpressionFunction( 'explode', function ($delimiter, $string) { return sprintf('explode(%s,%s)', $delimiter, $string); }, function ($arguments, $delimiter, $string) { return explode($delimiter, $string); } ); }
php
protected function createExplodeFunction() { return new ExpressionFunction( 'explode', function ($delimiter, $string) { return sprintf('explode(%s,%s)', $delimiter, $string); }, function ($arguments, $delimiter, $string) { return explode($delimiter, $string); } ); }
[ "protected", "function", "createExplodeFunction", "(", ")", "{", "return", "new", "ExpressionFunction", "(", "'explode'", ",", "function", "(", "$", "delimiter", ",", "$", "string", ")", "{", "return", "sprintf", "(", "'explode(%s,%s)'", ",", "$", "delimiter", ...
Explode a string into an array. @return ExpressionFunction
[ "Explode", "a", "string", "into", "an", "array", "." ]
5f0bf8ff86337a51f6d208bd38df39017643b905
https://github.com/smartboxgroup/integration-framework-bundle/blob/5f0bf8ff86337a51f6d208bd38df39017643b905/Tools/Evaluator/CustomExpressionLanguageProvider.php#L253-L264
train