_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q1600
CommaListNode.appendItem
train
public function appendItem(Node $item) { if ($this->getItems()->isEmpty()) { $this->append($item); } else { $this->append([ Token::comma(), Token::space(), $item, ]); } return $this; }
php
{ "resource": "" }
q1601
CommaListNode.insertItem
train
public function insertItem(Node $item, $index) { $items = $this->getItems(); if ($items->isEmpty()) { if ($index !== 0) { throw new \OutOfBoundsException('index out of bounds'); } $this->append($item); } else { $max_index = count($items) - 1; if ($index < 0 || $index > $max_index) { throw new \OutOfBoundsException('index out of bounds'); } $items[$index]->before([ $item, Token::comma(), Token::space(), ]); } return $this; }
php
{ "resource": "" }
q1602
CommaListNode.pop
train
public function pop() { $items = $this->getItems(); if ($items->isEmpty()) { return NULL; } if (count($items) === 1) { $pop_item = $items[0]; $pop_item->remove(); return $pop_item; } $pop_item = $items[count($items) - 1]; $pop_item->previousUntil(function ($node) { if ($node instanceof HiddenNode) { return FALSE; } if ($node instanceof TokenNode && $node->getType() === ',') { return FALSE; } return TRUE; })->remove(); $pop_item->remove(); return $pop_item; }
php
{ "resource": "" }
q1603
CommaListNode.shift
train
public function shift() { $items = $this->getItems(); if ($items->isEmpty()) { return NULL; } if (count($items) === 1) { $pop_item = $items[0]; $pop_item->remove(); return $pop_item; } $pop_item = $items[0]; $pop_item->nextUntil(function ($node) { if ($node instanceof HiddenNode) { return FALSE; } if ($node instanceof TokenNode && $node->getType() === ',') { return FALSE; } return TRUE; })->remove(); $pop_item->remove(); return $pop_item; }
php
{ "resource": "" }
q1604
CommaListNode.toArrayNode
train
public function toArrayNode() { return ($this->parent instanceof ArrayNode) ? clone $this->parent : Parser::parseExpression('[' . $this->getText() . ']'); }
php
{ "resource": "" }
q1605
AbstractPaymentModule.generateGatewayFormResponse
train
public function generateGatewayFormResponse($order, $gateway_url, $form_data) { /** @var ParserInterface $parser */ $parser = $this->getContainer()->get("thelia.parser"); $parser->setTemplateDefinition( $parser->getTemplateHelper()->getActiveFrontTemplate() ); $renderedTemplate = $parser->render( "order-payment-gateway.html", array( "order_id" => $order->getId(), "cart_count" => $this->getRequest()->getSession()->getSessionCart($this->getDispatcher())->getCartItems()->count(), "gateway_url" => $gateway_url, "payment_form_data" => $form_data ) ); return Response::create($renderedTemplate); }
php
{ "resource": "" }
q1606
AbstractPaymentModule.getPaymentSuccessPageUrl
train
public function getPaymentSuccessPageUrl($order_id) { $frontOfficeRouter = $this->getContainer()->get('router.front'); return URL::getInstance()->absoluteUrl( $frontOfficeRouter->generate( "order.placed", array("order_id" => $order_id), Router::ABSOLUTE_URL ) ); }
php
{ "resource": "" }
q1607
PermissionsPresenter.handleClearCacheACL
train
public function handleClearCacheACL(): void { if ($this->isAjax()) { $this->authorizatorFactory->cleanCache(); $this->flashNotifier->success('cms.permissions.aclCacheCleared'); } else { $this->terminate(); } }
php
{ "resource": "" }
q1608
PermissionsPresenter.setRoleName
train
public function setRoleName(int $id, string $value): void { if ($this->isAjax()) { $grid = $this['rolesList']; try { $role = $this->orm->aclRoles->getById($id); $role->setName($value); $this->orm->persistAndFlush($role); $this->flashNotifier->success('default.dataSaved'); } catch (UniqueConstraintViolationException $ex) { $this->flashNotifier->error('cms.permissions.duplicityName'); $grid->redrawItem($id); } catch (InvalidArgumentException $ex) { $this->flashNotifier->error('cms.permissions.invalidName'); $grid->redrawItem($id); } } else { $this->terminate(); } }
php
{ "resource": "" }
q1609
PermissionsPresenter.setRoleParent
train
public function setRoleParent(int $id, string $value): void { if ($this->isAjax()) { $role = $this->orm->aclRoles->getById($id); $role->parent = $value; $this->orm->persistAndFlush($role); $this->flashNotifier->success('default.dataSaved'); $this['rolesList']->redrawItem($id); } else { $this->terminate(); } }
php
{ "resource": "" }
q1610
PermissionsPresenter.setPermissionRole
train
public function setPermissionRole(int $id, int $value): void { if ($this->isAjax()) { $acl = $this->orm->acl->getById($id); $acl->role = $value; $this->orm->persistAndFlush($acl); $this->flashNotifier->success('default.dataSaved'); $this['permissionsList']->redrawItem($id); } else { $this->terminate(); } }
php
{ "resource": "" }
q1611
PermissionsPresenter.setPermissionResource
train
public function setPermissionResource(int $id, int $value): void { if ($this->isAjax()) { $acl = $this->orm->acl->getById($id); $acl->resource = $value; $this->orm->persistAndFlush($acl); $this->flashNotifier->success('default.dataSaved'); $this['permissionsList']->redrawItem($id); } else { $this->terminate(); } }
php
{ "resource": "" }
q1612
PermissionsPresenter.setPermissionPrivilege
train
public function setPermissionPrivilege(int $id, string $value): void { if ($this->isAjax()) { $permission = $this->orm->acl->getById($id); $permission->privilege = $value; $this->orm->persistAndFlush($permission); $this->flashNotifier->success('default.dataSaved'); $this['permissionsList']->redrawItem($id); } else { $this->terminate(); } }
php
{ "resource": "" }
q1613
PermissionsPresenter.setPermissionState
train
public function setPermissionState(int $id, bool $value): void { if ($this->isAjax()) { $permission = $this->orm->acl->getById($id); $permission->allowed = $value; $this->orm->persistAndFlush($permission); $this->flashNotifier->success('default.dataSaved'); $this['permissionsList']->redrawItem($id); } else { $this->terminate(); } }
php
{ "resource": "" }
q1614
FunctionDeclarationNode.create
train
public static function create($function_name, $parameters = NULL) { /** @var FunctionDeclarationNode $function */ $function = Parser::parseSnippet("function $function_name() {}"); if (is_array($parameters)) { foreach ($parameters as $parameter) { if (is_string($parameter)) { $parameter = ParameterNode::create($parameter); } $function->appendParameter($parameter); } } return $function; }
php
{ "resource": "" }
q1615
FunctionDeclarationNode.setName
train
public function setName($name) { /** @var TokenNode $function_name */ $function_name = $this->getName()->firstChild(); $function_name->setText($name); return $this; }
php
{ "resource": "" }
q1616
CurrencyController.updateRatesAction
train
public function updateRatesAction() { // Check current user authorization if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) { return $response; } try { $event = new CurrencyUpdateRateEvent(); $this->dispatch(TheliaEvents::CURRENCY_UPDATE_RATES, $event); if ($event->hasUndefinedRates()) { return $this->render('currencies', [ 'undefined_rates' => $event->getUndefinedRates() ]); } } catch (\Exception $ex) { // Any error return $this->errorPage($ex); } return $this->redirectToListTemplate(); }
php
{ "resource": "" }
q1617
CurrencyController.setVisibleAction
train
public function setVisibleAction() { // Check current user authorization if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) { return $response; } $changeEvent = new CurrencyUpdateEvent((int) $this->getRequest()->get('currency_id', 0)); // Create and dispatch the change event $changeEvent->setVisible((int) $this->getRequest()->get('visible', 0)); try { $this->dispatch(TheliaEvents::CURRENCY_SET_VISIBLE, $changeEvent); } catch (\Exception $ex) { // Any error return $this->errorPage($ex); } return $this->redirectToListTemplate(); }
php
{ "resource": "" }
q1618
TwilioFactory.make
train
public function make(array $config) { Arr::requires($config, ['from', 'client', 'token']); $client = new Client(); return new TwilioGateway($client, $config); }
php
{ "resource": "" }
q1619
ClassMethodNode.fromFunction
train
public static function fromFunction(FunctionDeclarationNode $function_node) { $method_name = $function_node->getName()->getText(); $parameters = $function_node->getParameterList()->getText(); $body = $function_node->getBody()->getText(); /** @var ClassNode $class_node */ $class_node = Parser::parseSnippet("class Method {public function {$method_name}($parameters) $body}"); FormatterFactory::format($class_node); $method_node = $class_node->getStatements()[0]->remove(); return $method_node; }
php
{ "resource": "" }
q1620
InterfaceNode.getMethod
train
public function getMethod($name) { $methods = $this ->getMethods() ->filter(function (InterfaceMethodNode $method) use ($name) { return $method->getName()->getText() === $name; }); return $methods->isEmpty() ? NULL : $methods[0]; }
php
{ "resource": "" }
q1621
InterfaceNode.appendMethod
train
public function appendMethod($method) { if (is_string($method)) { $method = InterfaceMethodNode::create($method); } $this->statements->lastChild()->before($method); FormatterFactory::format($this); return $this; }
php
{ "resource": "" }
q1622
Address.makeItDefault
train
public function makeItDefault() { AddressQuery::create()->filterByCustomerId($this->getCustomerId()) ->update(array('IsDefault' => '0')); $this->setIsDefault(1); $this->save(); }
php
{ "resource": "" }
q1623
Address.preInsert
train
public function preInsert(ConnectionInterface $con = null) { parent::preInsert($con); $this->dispatchEvent(TheliaEvents::BEFORE_CREATEADDRESS, new AddressEvent($this)); return true; }
php
{ "resource": "" }
q1624
Address.postInsert
train
public function postInsert(ConnectionInterface $con = null) { parent::postInsert($con); $this->dispatchEvent(TheliaEvents::AFTER_CREATEADDRESS, new AddressEvent($this)); }
php
{ "resource": "" }
q1625
Address.preUpdate
train
public function preUpdate(ConnectionInterface $con = null) { parent::preUpdate($con); $this->dispatchEvent(TheliaEvents::BEFORE_UPDATEADDRESS, new AddressEvent($this)); return true; }
php
{ "resource": "" }
q1626
Address.postUpdate
train
public function postUpdate(ConnectionInterface $con = null) { parent::postUpdate($con); $this->dispatchEvent(TheliaEvents::AFTER_UPDATEADDRESS, new AddressEvent($this)); }
php
{ "resource": "" }
q1627
Address.preDelete
train
public function preDelete(ConnectionInterface $con = null) { parent::preDelete($con); if ($this->getIsDefault()) { return false; } $this->dispatchEvent(TheliaEvents::BEFORE_DELETEADDRESS, new AddressEvent($this)); return true; }
php
{ "resource": "" }
q1628
Address.postDelete
train
public function postDelete(ConnectionInterface $con = null) { parent::postDelete($con); $this->dispatchEvent(TheliaEvents::AFTER_DELETEADDRESS, new AddressEvent($this)); }
php
{ "resource": "" }
q1629
Start.loadPluginTextdomain
train
private function loadPluginTextdomain() { load_textdomain( $this->textdomain, $this->configs->get( 'libraryDir' ) . 'languages/' . $this->textdomain . '-' . get_locale() . '.mo' ); }
php
{ "resource": "" }
q1630
Start.loadPluginInstaller
train
public function loadPluginInstaller() { if ( ! did_action( 'Boldgrid\Library\Library\Start::loadPluginInstaller' ) ) { do_action( 'Boldgrid\Library\Library\Start::loadPluginInstaller' ); if ( class_exists( '\Boldgrid\Library\Plugin\Installer' ) ) { $this->pluginInstaller = new \Boldgrid\Library\Plugin\Installer( Configs::get( 'pluginInstaller' ), $this->getReleaseChannel() ); } } }
php
{ "resource": "" }
q1631
Start.filterConfigs
train
public function filterConfigs( $configs ) { if ( ! empty( $configs['libraryDir'] ) ) { $configs['libraryUrl'] = str_replace( ABSPATH, get_site_url() . '/', $configs['libraryDir'] ); } return $configs; }
php
{ "resource": "" }
q1632
ImportCommand.listImport
train
protected function listImport(OutputInterface $output) { $table = new Table($output); foreach ((new ImportQuery)->find() as $import) { $table->addRow([ $import->getRef(), $import->getTitle(), $import->getDescription() ]); } $table ->setHeaders([ 'Reference', 'Title', 'Description' ]) ->render() ; }
php
{ "resource": "" }
q1633
ActiveResource._build_xml
train
public function _build_xml ($k, $v) { if (is_object ($v) && strtolower (get_class ($v)) == 'simplexmlelement') { return preg_replace ('/<\?xml(.*?)\?>\n*/', '', $v->asXML ()); } $res = ''; $attrs = ''; if (! is_numeric ($k)) { $res = '<' . $k . '{{attributes}}>'; } if (is_object ($v)) { $v = (array) $v; } if (is_array ($v)) { foreach ($v as $key => $value) { // handle attributes of repeating tags if (is_numeric ($key) && is_array ($value)) { foreach ($value as $sub_key => $sub_value) { if (strpos ($sub_key, '@') === 0) { $attrs .= ' ' . substr ($sub_key, 1) . '="' . $this->_xml_entities ($sub_value) . '"'; unset ($value[$sub_key]); continue; } } } if (strpos ($key, '@') === 0) { $attrs .= ' ' . substr ($key, 1) . '="' . $this->_xml_entities ($value) . '"'; continue; } $res .= $this->_build_xml ($key, $value); $keys = array_keys ($v); if (is_numeric ($key) && $key !== array_pop ($keys)) { // reset attributes on repeating tags if (is_array ($value)) { $res = str_replace ('<' . $k . '{{attributes}}>', '<' . $k . $attrs . '>', $res); $attrs = ''; } $res .= '</' . $k . ">\n<" . $k . '{{attributes}}>'; } } } else { $res .= $this->_xml_entities ($v); } if (! is_numeric ($k)) { $res .= '</' . $k . ">\n"; } $res = str_replace ('<' . $k . '{{attributes}}>', '<' . $k . $attrs . '>', $res); return $res; }
php
{ "resource": "" }
q1634
ActiveResource._unicode_ord
train
public function _unicode_ord (&$c, &$i = 0) { // get the character length $l = strlen($c); // copy the offset $index = $i; // check it's a valid offset if ($index >= $l) { return false; } // check the value $o = ord($c[$index]); // if it's ascii if ($o <= 0x7F) { return $o; // not sure what it is... } elseif ($o < 0xC2) { return false; // if it's a two-byte character } elseif ($o <= 0xDF && $index < $l - 1) { $i += 1; return ($o & 0x1F) << 6 | (ord($c[$index + 1]) & 0x3F); // three-byte } elseif ($o <= 0xEF && $index < $l - 2) { $i += 2; return ($o & 0x0F) << 12 | (ord($c[$index + 1]) & 0x3F) << 6 | (ord($c[$index + 2]) & 0x3F); // four-byte } elseif ($o <= 0xF4 && $index < $l - 3) { $i += 3; return ($o & 0x0F) << 18 | (ord($c[$index + 1]) & 0x3F) << 12 | (ord($c[$index + 2]) & 0x3F) << 6 | (ord($c[$index + 3]) & 0x3F); // not sure what it is... } else { return false; } }
php
{ "resource": "" }
q1635
ActiveResource._xml_entities
train
public function _xml_entities ($s, $hex = true) { // if the string is empty if (empty($s)) { // just return it return $s; } $s = (string) $s; // create the return string $r = ''; // get the length $l = strlen($s); // iterate the string for ($i = 0; $i < $l; $i++) { // get the value of the character $o = $this->_unicode_ord($s, $i); // valid characters $v = ( // \t \n <vertical tab> <form feed> \r ($o >= 9 && $o <= 13) || // <space> ! ($o == 32) || ($o == 33) || // # $ % ($o >= 35 && $o <= 37) || // ( ) * + , - . / ($o >= 40 && $o <= 47) || // numbers ($o >= 48 && $o <= 57) || // : ; ($o == 58) || ($o == 59) || // = ? ($o == 61) || ($o == 63) || // @ ($o == 64) || // uppercase ($o >= 65 && $o <= 90) || // [ \ ] ^ _ ` ($o >= 91 && $o <= 96) || // lowercase ($o >= 97 && $o <= 122) || // { | } ~ ($o >= 123 && $o <= 126) ); // if it's valid, just keep it if ($v) { $r .= $s[$i]; // & } elseif ($o == 38) { $r .= '&amp;'; // < } elseif ($o == 60) { $r .= '&lt;'; // > } elseif ($o == 62) { $r .= '&gt;'; // ' } elseif ($o == 39) { $r .= '&apos;'; // " } elseif ($o == 34) { $r .= '&quot;'; // unknown, add it as a reference } elseif ($o > 0) { if ($hex) { $r .= '&#x'.strtoupper(dechex($o)).';'; } else { $r .= '&#'.$o.';'; } } } return $r; }
php
{ "resource": "" }
q1636
ActiveResource._fetch
train
public function _fetch ($url, $method, $params) { if (! extension_loaded ('curl')) { $this->error = 'cURL extension not loaded.'; return false; } $ch = curl_init (); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_MAXREDIRS, 3); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_VERBOSE, 0); curl_setopt ($ch, CURLOPT_HEADER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); /* HTTP Basic Authentication */ if ($this->user && $this->password) { curl_setopt ($ch, CURLOPT_USERPWD, $this->user . ":" . $this->password); } if ($this->request_format == 'xml') { $this->request_headers = array_merge ($this->request_headers, array ("Expect:", "Content-Type: text/xml", "Length: " . strlen ($params))); } switch ($method) { case 'POST': curl_setopt ($ch, CURLOPT_POST, 1); curl_setopt ($ch, CURLOPT_POSTFIELDS, $params); break; case 'DELETE': curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; case 'PUT': curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt ($ch, CURLOPT_POSTFIELDS, $params); break; case 'GET': default: break; } if (count ($this->request_headers)) { curl_setopt ($ch, CURLOPT_HTTPHEADER, $this->request_headers); } $res = curl_exec ($ch); $http_code = curl_getinfo ($ch, CURLINFO_HTTP_CODE); // Check HTTP status code for denied access if ($http_code == 401) { $this->errno = $http_code; $this->error = "HTTP Basic: Access denied."; curl_close ($ch); return false; } // Check HTTP status code for rate limit if ($http_code == 429) { if (preg_match ('/Retry-After: ([0-9]+)/', $res, $retry_after)) { sleep(intval($retry_after[1])); return $this->_fetch ($url, $method, $params); } $this->errno = $http_code; $this->error = "Too Many Requests"; curl_close ($ch); return false; } if (! $res) { $this->errno = curl_errno ($ch); $this->error = curl_error ($ch); curl_close ($ch); return false; } curl_close ($ch); return $res; }
php
{ "resource": "" }
q1637
ActiveResource.set
train
public function set ($k, $v = false) { if (! $v && is_array ($k)) { foreach ($k as $key => $value) { $this->_data[$key] = $value; } } else { $this->_data[$k] = $v; } return $this; }
php
{ "resource": "" }
q1638
BasePaymentModuleController.getLog
train
protected function getLog() { if ($this->log == null) { $this->log = Tlog::getNewInstance(); $logFilePath = $this->getLogFilePath(); $this->log->setPrefix("#LEVEL: #DATE #HOUR: "); $this->log->setDestinations("\\Thelia\\Log\\Destination\\TlogDestinationFile"); $this->log->setConfig("\\Thelia\\Log\\Destination\\TlogDestinationFile", 0, $logFilePath); $this->log->setLevel(Tlog::INFO); } return $this->log; }
php
{ "resource": "" }
q1639
BasePaymentModuleController.confirmPayment
train
public function confirmPayment($orderId) { try { $orderId = \intval($orderId); if (null !== $order = $this->getOrder($orderId)) { $this->getLog()->addInfo( $this->getTranslator()->trans( "Processing confirmation of order ref. %ref, ID %id", array('%ref' => $order->getRef(), '%id' => $order->getId()) ) ); $event = new OrderEvent($order); $event->setStatus(OrderStatusQuery::getPaidStatus()->getId()); $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); $this->getLog()->addInfo( $this->getTranslator()->trans( "Order ref. %ref, ID %id has been successfully paid.", array('%ref' => $order->getRef(), '%id' => $order->getId()) ) ); } } catch (\Exception $ex) { $this->getLog()->addError( $this->getTranslator()->trans( "Error occured while processing order ref. %ref, ID %id: %err", array( '%err' => $ex->getMessage(), '%ref' => !isset($order) ? "?" : $order->getRef(), '%id' => !isset($order) ? "?" : $order->getId() ) ) ); throw $ex; } }
php
{ "resource": "" }
q1640
BasePaymentModuleController.getOrder
train
protected function getOrder($orderId) { if (null == $order = OrderQuery::create()->findPk($orderId)) { $this->getLog()->addError( $this->getTranslator()->trans("Unknown order ID: %id", array('%id' => $orderId)) ); } return $order; }
php
{ "resource": "" }
q1641
BasePaymentModuleController.redirectToSuccessPage
train
public function redirectToSuccessPage($orderId) { $this->getLog()->addInfo("Redirecting customer to payment success page"); throw new RedirectException( $this->retrieveUrlFromRouteId( 'order.placed', [], [ 'order_id' => $orderId ], Router::ABSOLUTE_PATH ) ); }
php
{ "resource": "" }
q1642
GitterFactory.make
train
public function make(array $config) { Arr::requires($config, ['token']); $client = new Client(); return new GitterGateway($client, $config); }
php
{ "resource": "" }
q1643
Sale.getPriceOffsets
train
public function getPriceOffsets() { $currencyOffsets = SaleOffsetCurrencyQuery::create()->filterBySaleId($this->getId())->find(); $offsetList = []; /** @var SaleOffsetCurrency $currencyOffset */ foreach ($currencyOffsets as $currencyOffset) { $offsetList[$currencyOffset->getCurrencyId()] = $currencyOffset->getPriceOffsetValue(); } return $offsetList; }
php
{ "resource": "" }
q1644
Sale.getSaleProductList
train
public function getSaleProductList() { $saleProducts = SaleProductQuery::create()->filterBySaleId($this->getId())->groupByProductId()->find(); return $saleProducts; }
php
{ "resource": "" }
q1645
Sale.getSaleProductsAttributeList
train
public function getSaleProductsAttributeList() { $saleProducts = SaleProductQuery::create()->filterBySaleId($this->getId())->orderByProductId()->find(); $selectedAttributes = []; $currentProduct = false; /** @var SaleProduct $saleProduct */ foreach ($saleProducts as $saleProduct) { if ($currentProduct != $saleProduct->getProductId()) { $currentProduct = $saleProduct->getProductId(); $selectedAttributes[$currentProduct] = []; } $selectedAttributes[$currentProduct][] = $saleProduct->getAttributeAvId(); } return $selectedAttributes; }
php
{ "resource": "" }
q1646
DefaultController.noAction
train
public function noAction(Request $request) { $view = null; if (! $view = $request->query->get('view')) { if ($request->request->has('view')) { $view = $request->request->get('view'); } } if (null !== $view) { $request->attributes->set('_view', $view); } if (null === $view && null === $request->attributes->get("_view")) { $request->attributes->set("_view", "index"); } if (ConfigQuery::isRewritingEnable()) { if ($request->attributes->get('_rewritten', false) === false) { /* Does the query GET parameters match a rewritten URL ? */ $rewrittenUrl = URL::getInstance()->retrieveCurrent($request); if ($rewrittenUrl->rewrittenUrl !== null) { /* 301 redirection to rewritten URL */ throw new RedirectException($rewrittenUrl->rewrittenUrl, 301); } } } }
php
{ "resource": "" }
q1647
ConditionEvaluator.isMatching
train
public function isMatching(ConditionCollection $conditions) { $isMatching = true; /** @var ConditionInterface $condition */ foreach ($conditions as $condition) { if (!$condition->isMatching()) { return false; } } return $isMatching; }
php
{ "resource": "" }
q1648
ConditionEvaluator.variableOpComparison
train
public function variableOpComparison($v1, $o, $v2) { switch ($o) { case Operators::DIFFERENT: // != return ($v1 != $v2); case Operators::SUPERIOR: // > return ($v1 > $v2); case Operators::SUPERIOR_OR_EQUAL: // >= return ($v1 >= $v2); case Operators::INFERIOR: // < return ($v1 < $v2); case Operators::INFERIOR_OR_EQUAL: // <= return ($v1 <= $v2); case Operators::EQUAL: // == return ($v1 == $v2); case Operators::IN: // in return (\in_array($v1, $v2)); case Operators::OUT: // not in return (!\in_array($v1, $v2)); default: throw new \Exception('Unrecognized operator ' . $o); } }
php
{ "resource": "" }
q1649
BaseHookRenderEvent.getArgument
train
public function getArgument($key, $default = null) { return array_key_exists($key, $this->arguments) ? $this->arguments[$key] : $default; }
php
{ "resource": "" }
q1650
BaseHookRenderEvent.getTemplateVar
train
public function getTemplateVar($templateVariableName) { if (! isset($this->templateVars[$templateVariableName])) { throw new \InvalidArgumentException(sprintf("Template variable '%s' is not defined.", $templateVariableName)); } return $this->templateVars[$templateVariableName]; }
php
{ "resource": "" }
q1651
FilterRuleTags.sanitizeValue
train
public function sanitizeValue() { $strColNameId = $this->objAttribute->get('tag_id') ?: 'id'; $strColNameAlias = $this->objAttribute->get('tag_alias'); $arrValues = \is_array($this->value) ? $this->value : \explode(',', $this->value); if (!$this->isMetaModel()) { if ($strColNameAlias) { $builder = $this->connection->createQueryBuilder() ->select($strColNameId) ->from($this->objAttribute->get('tag_table')); foreach ($arrValues as $index => $value) { $builder ->orWhere($strColNameAlias . ' LIKE :value_' . $index) ->setParameter('value_' . $index, $value); } $arrValues = $builder->execute()->fetchAll(\PDO::FETCH_COLUMN); } else { $arrValues = \array_map('intval', $arrValues); } } else { if ($strColNameAlias == 'id') { $values = $arrValues; } else { $values = []; foreach ($arrValues as $value) { $values[] = \array_values( $this->getTagMetaModel()->getAttribute($strColNameAlias)->searchFor($value) ); } } $arrValues = $this->flatten($values); } return $arrValues; }
php
{ "resource": "" }
q1652
NotifyMeFactory.make
train
public function make(array $config) { if (!isset($config['driver'])) { throw new InvalidArgumentException('A driver must be specified.'); } return $this->factory($config['driver'])->make($config); }
php
{ "resource": "" }
q1653
NotifyMeFactory.factory
train
public function factory($name) { if (isset($this->factories[$name])) { return $this->factories[$name]; } if (class_exists($class = $this->inflect($name))) { return $this->factories[$name] = new $class(); } throw new InvalidArgumentException("Unsupported factory [$name]."); }
php
{ "resource": "" }
q1654
Category.getRoot
train
public function getRoot($categoryId) { $category = CategoryQuery::create()->findPk($categoryId); if (0 !== $category->getParent()) { $parentCategory = CategoryQuery::create()->findPk($category->getParent()); if (null !== $parentCategory) { $categoryId = $this->getRoot($parentCategory->getId()); } } return $categoryId; }
php
{ "resource": "" }
q1655
LoaderFactory.addRemoteFile
train
public function addRemoteFile(string $file, string $locale = null): self { $collection = $this->getCollection($this->getType($file), $locale); $collection->addRemoteFile($file); return $this; }
php
{ "resource": "" }
q1656
LoaderFactory.createCssLoader
train
public function createCssLoader(): CssLoader { $compiler = Compiler::createCssCompiler($this->files[self::CSS][null], $this->wwwDir . '/' . $this->outputDir); foreach ($this->filters[self::CSS] as $filter) { $compiler->addFileFilter($filter); } return new CssLoader($compiler, $this->httpRequest->getUrl()->basePath . $this->outputDir); }
php
{ "resource": "" }
q1657
LoaderFactory.createJavaScriptLoader
train
public function createJavaScriptLoader(string $locale = null): JavaScriptLoader { $compilers[] = $this->createJSCompiler($this->files[self::JS][null]); if ($locale !== null && isset($this->files[self::JS][$locale])) { $compilers[] = $this->createJSCompiler($this->files[self::JS][$locale]); } return new JavaScriptLoader($this->httpRequest->getUrl()->basePath . $this->outputDir, ...$compilers); }
php
{ "resource": "" }
q1658
LoaderFactory.getCollection
train
private function getCollection(string $type, string $locale = null): FileCollection { if (!isset($this->files[$type][$locale])) { $this->files[$type][$locale] = new FileCollection($this->root); } return $this->files[$type][$locale]; }
php
{ "resource": "" }
q1659
LoaderFactory.getType
train
private function getType(string $file): string { $css = '/\.(css|less)$/'; $js = '/\.js$/'; if (preg_match($css, $file)) { return self::CSS; } elseif (preg_match($js, $file)) { return self::JS; } throw new InvalidArgumentException("Unknown assets file '$file'"); }
php
{ "resource": "" }
q1660
Product.getDefaultCategoryId
train
protected function getDefaultCategoryId($product) { $defaultCategoryId = null; if ((bool) $product->getVirtualColumn('is_default_category')) { $defaultCategoryId = $product->getVirtualColumn('default_category_id'); } else { $defaultCategoryId = $product->getDefaultCategoryId(); } return $defaultCategoryId; }
php
{ "resource": "" }
q1661
ProfilePresenter.createComponentPasswordForm
train
protected function createComponentPasswordForm(): Form { $form = $this->formFactory->create(); $form->setAjaxRequest(); $form->addPassword('oldPassword', 'cms.user.oldPassword') ->setRequired(); $form->addPassword('password', 'cms.user.newPassword') ->setRequired() ->addRule(Form::MIN_LENGTH, null, $this->minPasswordLength); $form->addPassword('passwordVerify', 'cms.user.passwordVerify') ->setRequired() ->addRule(Form::EQUAL, null, $form['password']); $form->addProtection(); $form->addSubmit('save', 'form.save'); $form->onSuccess[] = [$this, 'passwordFormSucceeded']; return $form; }
php
{ "resource": "" }
q1662
ProductSaleElement.create
train
public function create(ProductSaleElementCreateEvent $event) { $con = Propel::getWriteConnection(ProductSaleElementsTableMap::DATABASE_NAME); $con->beginTransaction(); try { // Check if we have a PSE without combination, this is the "default" PSE. Attach the combination to this PSE $salesElement = ProductSaleElementsQuery::create() ->filterByProductId($event->getProduct()->getId()) ->joinAttributeCombination(null, Criteria::LEFT_JOIN) ->add(AttributeCombinationTableMap::COL_PRODUCT_SALE_ELEMENTS_ID, null, Criteria::ISNULL) ->findOne($con); if ($salesElement == null) { // Create a new default product sale element $salesElement = $event->getProduct()->createProductSaleElement($con, 0, 0, 0, $event->getCurrencyId(), false); } else { // This (new) one is the default $salesElement->setIsDefault(true)->save($con); } // Attach combination, if defined. $combinationAttributes = $event->getAttributeAvList(); if (\count($combinationAttributes) > 0) { foreach ($combinationAttributes as $attributeAvId) { $attributeAv = AttributeAvQuery::create()->findPk($attributeAvId); if ($attributeAv !== null) { $attributeCombination = new AttributeCombination(); $attributeCombination ->setAttributeAvId($attributeAvId) ->setAttribute($attributeAv->getAttribute()) ->setProductSaleElements($salesElement) ->save($con); } } } $event->setProductSaleElement($salesElement); // Store all the stuff ! $con->commit(); } catch (\Exception $ex) { $con->rollback(); throw $ex; } }
php
{ "resource": "" }
q1663
ProductSaleElement.update
train
public function update(ProductSaleElementUpdateEvent $event) { $salesElement = ProductSaleElementsQuery::create()->findPk($event->getProductSaleElementId()); $con = Propel::getWriteConnection(ProductSaleElementsTableMap::DATABASE_NAME); $con->beginTransaction(); try { // Update the product's tax rule $event->getProduct()->setTaxRuleId($event->getTaxRuleId())->save($con); // If product sale element is not defined, create it. if ($salesElement == null) { $salesElement = new ProductSaleElements(); $salesElement->setProduct($event->getProduct()); } $defaultStatus = $event->getIsDefault(); // If this PSE will become the default one, be sure to have *only one* default for this product if ($defaultStatus) { ProductSaleElementsQuery::create() ->filterByProduct($event->getProduct()) ->filterByIsDefault(true) ->filterById($event->getProductSaleElementId(), Criteria::NOT_EQUAL) ->update(['IsDefault' => false], $con) ; } else { // We will not allow the default PSE to become non default if no other default PSE exists for this product. if ($salesElement->getIsDefault() && ProductSaleElementsQuery::create() ->filterByProduct($event->getProduct()) ->filterByIsDefault(true) ->filterById($salesElement->getId(), Criteria::NOT_EQUAL) ->count() === 0) { // Prevent setting the only default PSE to non-default $defaultStatus = true; } } // Update sale element $salesElement ->setRef($event->getReference()) ->setQuantity($event->getQuantity()) ->setPromo($event->getOnsale()) ->setNewness($event->getIsnew()) ->setWeight($event->getWeight()) ->setIsDefault($defaultStatus) ->setEanCode($event->getEanCode()) ->save() ; // Update/create price for current currency $productPrice = ProductPriceQuery::create() ->filterByCurrencyId($event->getCurrencyId()) ->filterByProductSaleElementsId($salesElement->getId()) ->findOne($con); // If price is not defined, create it. if ($productPrice == null) { $productPrice = new ProductPrice(); $productPrice ->setProductSaleElements($salesElement) ->setCurrencyId($event->getCurrencyId()) ; } // Check if we have to store the price $productPrice->setFromDefaultCurrency($event->getFromDefaultCurrency()); if ($event->getFromDefaultCurrency() == 0) { // Store the price $productPrice ->setPromoPrice($event->getSalePrice()) ->setPrice($event->getPrice()) ; } else { // Do not store the price. $productPrice ->setPromoPrice(0) ->setPrice(0) ; } $productPrice->save($con); // Store all the stuff ! $con->commit(); } catch (\Exception $ex) { $con->rollback(); throw $ex; } }
php
{ "resource": "" }
q1664
ProductSaleElement.delete
train
public function delete(ProductSaleElementDeleteEvent $event) { if (null !== $pse = ProductSaleElementsQuery::create()->findPk($event->getProductSaleElementId())) { $product = $pse->getProduct(); $con = Propel::getWriteConnection(ProductSaleElementsTableMap::DATABASE_NAME); $con->beginTransaction(); try { // If we are deleting the last PSE of the product, don(t delete it, but insteaf // transform it into a PSE detached for any attribute combination, so that product // prices, weight, stock and attributes will not be lost. if ($product->countSaleElements($con) === 1) { $pse ->setIsDefault(true) ->save($con); // Delete the related attribute combination. AttributeCombinationQuery::create() ->filterByProductSaleElementsId($pse->getId()) ->delete($con); } else { // Delete the PSE $pse->delete($con); // If we deleted the default PSE, make the last created one the default if ($pse->getIsDefault()) { $newDefaultPse = ProductSaleElementsQuery::create() ->filterByProductId($product->getId()) ->filterById($pse->getId(), Criteria::NOT_EQUAL) ->orderByCreatedAt(Criteria::DESC) ->findOne($con) ; if (null !== $newDefaultPse) { $newDefaultPse->setIsDefault(true)->save($con); } } } // Store all the stuff ! $con->commit(); } catch (\Exception $ex) { $con->rollback(); throw $ex; } } }
php
{ "resource": "" }
q1665
ProductSaleElement.generateCombinations
train
public function generateCombinations(ProductCombinationGenerationEvent $event) { $con = Propel::getWriteConnection(ProductSaleElementsTableMap::DATABASE_NAME); $con->beginTransaction(); try { // Delete all product's productSaleElement ProductSaleElementsQuery::create()->filterByProductId($event->product->getId())->delete(); $isDefault = true; // Create all combinations foreach ($event->getCombinations() as $combinationAttributesAvIds) { // Create the PSE $saleElement = $event->getProduct()->createProductSaleElement( $con, $event->getWeight(), $event->getPrice(), $event->getSalePrice(), $event->getCurrencyId(), $isDefault, $event->getOnsale(), $event->getIsnew(), $event->getQuantity(), $event->getEanCode(), $event->getReference() ); $isDefault = false; $this->createCombination($con, $saleElement, $combinationAttributesAvIds); } // Store all the stuff ! $con->commit(); } catch (\Exception $ex) { $con->rollback(); throw $ex; } }
php
{ "resource": "" }
q1666
ProductSaleElement.createCombination
train
protected function createCombination(ConnectionInterface $con, ProductSaleElements $salesElement, $combinationAttributes) { foreach ($combinationAttributes as $attributeAvId) { $attributeAv = AttributeAvQuery::create()->findPk($attributeAvId); if ($attributeAv !== null) { $attributeCombination = new AttributeCombination(); $attributeCombination ->setAttributeAvId($attributeAvId) ->setAttribute($attributeAv->getAttribute()) ->setProductSaleElements($salesElement) ->save($con); } } }
php
{ "resource": "" }
q1667
ProductSaleElement.clonePSE
train
public function clonePSE(ProductCloneEvent $event) { $clonedProduct = $event->getClonedProduct(); // Get original product's PSEs $originalProductPSEs = ProductSaleElementsQuery::create() ->orderByIsDefault(Criteria::DESC) ->findByProductId($event->getOriginalProduct()->getId()); /** * Handle PSEs * * @var int $key * @var ProductSaleElements $originalProductPSE */ foreach ($originalProductPSEs as $key => $originalProductPSE) { $currencyId = ProductPriceQuery::create() ->filterByProductSaleElementsId($originalProductPSE->getId()) ->select('CURRENCY_ID') ->findOne(); // The default PSE, created at the same time as the clone product, is overwritten $clonedProductPSEId = $this->createClonePSE($event, $originalProductPSE, $currencyId); $this->updateClonePSE($event, $clonedProductPSEId, $originalProductPSE, $key); // PSE associated images $originalProductPSEImages = ProductSaleElementsProductImageQuery::create() ->findByProductSaleElementsId($originalProductPSE->getId()); if (null !== $originalProductPSEImages) { $this->clonePSEAssociatedFiles($clonedProduct->getId(), $clonedProductPSEId, $originalProductPSEImages, $type = 'image'); } // PSE associated documents $originalProductPSEDocuments = ProductSaleElementsProductDocumentQuery::create() ->findByProductSaleElementsId($originalProductPSE->getId()); if (null !== $originalProductPSEDocuments) { $this->clonePSEAssociatedFiles($clonedProduct->getId(), $clonedProductPSEId, $originalProductPSEDocuments, $type = 'document'); } } }
php
{ "resource": "" }
q1668
Customer.getCustomerLang
train
public function getCustomerLang() { $lang = $this->getLangModel(); if ($lang === null) { $lang = (new LangQuery) ->filterByByDefault(1) ->findOne() ; } return $lang; }
php
{ "resource": "" }
q1669
Customer.setPassword
train
public function setPassword($password) { if ($this->isNew() && ($password === null || trim($password) == "")) { throw new InvalidArgumentException("customer password is mandatory on creation"); } if ($password !== null && trim($password) != "") { $this->setAlgo("PASSWORD_BCRYPT"); parent::setPassword(password_hash($password, PASSWORD_BCRYPT)); } return $this; }
php
{ "resource": "" }
q1670
Plugin.getDownloadUrl
train
public function getDownloadUrl() { $url = Configs::get( 'api' ) . '/v1/plugins/' . $this->slug . '/download'; $url = add_query_arg( 'key', Configs::get( 'key' ), $url ); return $url; }
php
{ "resource": "" }
q1671
DatabasePresenter.createComponentUploadForm
train
protected function createComponentUploadForm(): Form { $form = $this->formFactory->create(); $form->addUpload('sql', 'cms.database.file') ->setRequired(); $form->addSubmit('upload', 'cms.database.upload'); $form->onSuccess[] = [$this, 'uploadFormSucceeded']; return $form; }
php
{ "resource": "" }
q1672
PlatformServiceConfig.getSolrType
train
public static function getSolrType() { $relationships = PlatformAppConfig::get('relationships'); if (!isset($relationships['solr'])) { return FALSE; } list($solr_key, ) = explode(':', $relationships['solr']); $solr_config = self::get($solr_key); if (!isset($solr_config['type'])) { return FALSE; } return $solr_config['type']; }
php
{ "resource": "" }
q1673
PlatformServiceConfig.getSolrMajorVersion
train
public static function getSolrMajorVersion() { $type = static::getSolrType(); $version = FALSE; if ($type) { list(, $version) = explode(":", $type); if (preg_match('/^(\d)\./', $version, $matches)) { $version = $matches[1]; } else { $version = '4'; } // Platform support 3,4 and 6 atm. We only support 4 and 6. if ($version === '3') { $version = '4'; } } return $version; }
php
{ "resource": "" }
q1674
ArchiverManager.getArchivers
train
public function getArchivers($isAvailable = null) { if ($isAvailable === null) { return $this->archivers; } $filteredArchivers = []; /** @var \Thelia\Core\Archiver\ArchiverInterface $archiver */ foreach ($this->archivers as $archiver) { if ($archiver->isAvailable() === (bool) $isAvailable) { $filteredArchivers[] = $archiver; } } return $filteredArchivers; }
php
{ "resource": "" }
q1675
ArchiverManager.get
train
public function get($archiverId, $isAvailable = null) { $this->has($archiverId, true); if ($isAvailable === null) { return $this->archivers[$archiverId]; } if ($this->archivers[$archiverId]->isAvailable() === (bool) $isAvailable) { return $this->archivers[$archiverId]; } return null; }
php
{ "resource": "" }
q1676
Message.getMessageBody
train
protected function getMessageBody($parser, $message, $layout, $template, $compressOutput = true) { $body = false; // Try to get the body from template file, if a file is defined if (! empty($template)) { try { $body = $parser->render($template, [], $compressOutput); } catch (ResourceNotFoundException $ex) { Tlog::getInstance()->addError("Failed to get mail message template body $template"); } } // We did not get it ? Use the message entered in the back-office if ($body === false) { $body = $parser->renderString($message, [], $compressOutput); } // Do we have a layout ? if (! empty($layout)) { // Populate the message body variable $parser->assign('message_body', $body); // Render the layout file $body = $parser->render($layout, [], $compressOutput); } return $body; }
php
{ "resource": "" }
q1677
Message.getHtmlMessageBody
train
public function getHtmlMessageBody(ParserInterface $parser) { return $this->getMessageBody( $parser, $this->getHtmlMessage(), $this->getHtmlLayoutFileName(), $this->getHtmlTemplateFileName() ); }
php
{ "resource": "" }
q1678
Message.getTextMessageBody
train
public function getTextMessageBody(ParserInterface $parser) { $message = $this->getMessageBody( $parser, $this->getTextMessage(), $this->getTextLayoutFileName(), $this->getTextTemplateFileName(), true // Do not compress the output, and keep empty lines. ); // Replaced all <br> by newlines. return preg_replace("/<br>/i", "\n", $message); }
php
{ "resource": "" }
q1679
Message.buildMessage
train
public function buildMessage(ParserInterface $parser, \Swift_Message $messageInstance, $useFallbackTemplate = true) { // Set mail template, and save the current template $parser->pushTemplateDefinition( $parser->getTemplateHelper()->getActiveMailTemplate(), $useFallbackTemplate ); $subject = $parser->renderString($this->getSubject()); $htmlMessage = $this->getHtmlMessageBody($parser); $textMessage = $this->getTextMessageBody($parser); $messageInstance->setSubject($subject); // If we do not have an HTML message if (empty($htmlMessage)) { // Message body is the text message $messageInstance->setBody($textMessage, 'text/plain'); } else { // The main body is the HTML messahe $messageInstance->setBody($htmlMessage, 'text/html'); // Use the text as a message part, if we have one. if (! empty($textMessage)) { $messageInstance->addPart($textMessage, 'text/plain'); } } // Restore previous template $parser->popTemplateDefinition(); return $messageInstance; }
php
{ "resource": "" }
q1680
PlatformController.renderPlatformModalContentAction
train
public function renderPlatformModalContentAction() { $pids_id = $this->params()->fromQuery('id'); // Get Cms Platform ID form from App Tool $melisMelisCoreConfig = $this->serviceLocator->get('MelisCoreConfig'); $genericPlatformForm = $melisMelisCoreConfig->getFormMergedAndOrdered('meliscms/tools/meliscms_platform_tool/forms/meliscms_tool_platform_generic_form', 'meliscms_tool_platform_generic_form'); // Factoring Calendar event and pass to view $factory = new \Zend\Form\Factory(); $formElements = $this->serviceLocator->get('FormElementManager'); $factory->setFormElementManager($formElements); $propertyForm = $factory->createForm($genericPlatformForm); $view = new ViewModel(); $melisEngineTablePlatformIds = $this->getServiceLocator()->get('MelisEngineTablePlatformIds'); $availablePlatform = $melisEngineTablePlatformIds->getAvailablePlatforms()->toArray(); // Check if Cms Platform Id is Set if (!empty($pids_id)) { // Get Platform ID Details $platformIdsData = $melisEngineTablePlatformIds->getEntryById($pids_id); $platformIdsData = $platformIdsData->current(); $platformTable = $this->getServiceLocator()->get('MelisCoreTablePlatform'); $platformData = $platformTable->getEntryById($pids_id); $platformData = $platformData->current(); // Assign Platform name to Element Name of the Form from the App Tool $platformIdsData->pids_name_input = $platformData->plf_name; // Removing Select input $propertyForm->remove('pids_name_select'); // Binding datas to the Form $propertyForm->bind($platformIdsData); // Set variable to View $view->pids_id = $pids_id; $view->tabTitle = 'tr_meliscms_tool_platform_ids_btn_edit'; } else { // Removing Id input and Platform input $propertyForm->remove('pids_id'); $propertyForm->remove('pids_name_input'); // Set variable to View $view->tabTitle = 'tr_meliscms_tool_platform_ids_btn_add'; } $view->setVariable('meliscms_tool_platform_generic_form', $propertyForm); $view->setVariable('available_platform', $availablePlatform); $view->melisKey = $this->params()->fromRoute('melisKey', ''); return $view; }
php
{ "resource": "" }
q1681
PlatformController.getPlatformList
train
public function getPlatformList() { $success = 0; $data = array(); if($this->getRequest()->isPost()){ $success = 0; $platform = $this->getServiceLocator()->get("Melisplatform"); $data = $platform->getPlatformList(); } return $data; }
php
{ "resource": "" }
q1682
ExportHandler.getExport
train
public function getExport($exportId, $dispatchException = false) { $export = (new ExportQuery)->findPk($exportId); if ($export === null && $dispatchException) { throw new \ErrorException( Translator::getInstance()->trans( 'There is no id "%id" in the exports', [ '%id' => $exportId ] ) ); } return $export; }
php
{ "resource": "" }
q1683
ExportHandler.getExportByRef
train
public function getExportByRef($exportRef, $dispatchException = false) { $export = (new ExportQuery)->findOneByRef($exportRef); if ($export === null && $dispatchException) { throw new \ErrorException( Translator::getInstance()->trans( 'There is no ref "%ref" in the exports', [ '%ref' => $exportRef ] ) ); } return $export; }
php
{ "resource": "" }
q1684
ExportHandler.getCategory
train
public function getCategory($exportCategoryId, $dispatchException = false) { $category = (new ExportCategoryQuery)->findPk($exportCategoryId); if ($category === null && $dispatchException) { throw new \ErrorException( Translator::getInstance()->trans( 'There is no id "%id" in the export categories', [ '%id' => $exportCategoryId ] ) ); } return $category; }
php
{ "resource": "" }
q1685
ExportHandler.processExportImages
train
protected function processExportImages(AbstractExport $export, ArchiverInterface $archiver) { foreach ($export->getImagesPaths() as $imagePath) { $archiver->add($imagePath); } }
php
{ "resource": "" }
q1686
ExportHandler.processExportDocuments
train
protected function processExportDocuments(AbstractExport $export, ArchiverInterface $archiver) { foreach ($export->getDocumentsPaths() as $documentPath) { $archiver->add($documentPath); } }
php
{ "resource": "" }
q1687
BaseI18nLoop.configureI18nProcessing
train
protected function configureI18nProcessing( ModelCriteria $search, $columns = array('TITLE', 'CHAPO', 'DESCRIPTION', 'POSTSCRIPTUM'), $foreignTable = null, $foreignKey = 'ID', $forceReturn = false ) { /* manage translations */ $this->locale = ModelCriteriaTools::getI18n( $this->getBackendContext(), $this->getLang(), $search, $this->getCurrentRequest()->getSession()->getLang()->getLocale(), $columns, $foreignTable, $foreignKey, $this->getForceReturn() ); }
php
{ "resource": "" }
q1688
ArrayNode.isMultidimensional
train
public function isMultidimensional() { foreach ($this->elements->getItems() as $element) { if ($element instanceof ArrayPairNode) { if ($element->getValue() instanceof ArrayNode) { return TRUE; } } elseif ($element instanceof ArrayNode) { return TRUE; } } return FALSE; }
php
{ "resource": "" }
q1689
ArrayNode.toValue
train
public function toValue() { $ret = array(); foreach ($this->elements->getItems() as $element) { if ($element instanceof ArrayNode) { $ref[] = $element->toValue(); } elseif ($element instanceof ArrayPairNode) { $key = $element->getKey(); $value = $element->getValue(); $value_convertable = $value instanceof ScalarNode || $value instanceof ArrayNode; if (!($key instanceof ScalarNode && $value_convertable)) { throw new \BadMethodCallException('Can only convert scalar arrays.'); } $ret[$key->toValue()] = $value->toValue(); } elseif ($element instanceof ScalarNode || $element instanceof ArrayNode) { /** @var ScalarNode|ArrayNode $element */ $ret[] = $element->toValue(); } else { throw new \BadMethodCallException('Can only convert scalar arrays.'); } } return $ret; }
php
{ "resource": "" }
q1690
ArrayNode.hasKey
train
public function hasKey($key, $recursive = TRUE) { if (!($key instanceof ExpressionNode) && !is_scalar($key)) { throw new \InvalidArgumentException(); } $keys = $this->getKeys($recursive); if (is_scalar($key)) { return $keys ->filter(Filter::isInstanceOf('\Pharborist\Types\ScalarNode')) ->is(function(ScalarNode $node) use ($key) { return $node->toValue() === $key; }); } else { return $keys ->is(function(ExpressionNode $expr) use ($key) { return $expr->getText() === $key->getText(); }); } }
php
{ "resource": "" }
q1691
ArrayNode.getKeys
train
public function getKeys($recursive = TRUE) { $keys = new NodeCollection(); $index = 0; foreach ($this->elements->getItems() as $element) { if ($element instanceof ArrayPairNode) { $keys->add($element->getKey()); $value = $element->getValue(); } else { $keys->add(Token::integer($index++)); $value = $element; } if ($recursive && $value instanceof ArrayNode) { $keys->add($value->getKeys($recursive)); } } return $keys; }
php
{ "resource": "" }
q1692
ArrayNode.getValues
train
public function getValues($recursive = TRUE) { $values = new NodeCollection(); foreach ($this->elements->getItems() as $element) { if ($element instanceof ArrayPairNode) { $value = $element->getValue(); if ($recursive && $value instanceof ArrayNode) { $values->add($value->getValues($recursive)); } else { $values->add($value); } } else { $values->add($element); } } return $values; }
php
{ "resource": "" }
q1693
ExportController.configureAction
train
public function configureAction($id) { /** @var \Thelia\Handler\Exporthandler $exportHandler */ $exportHandler = $this->container->get('thelia.export.handler'); $export = $exportHandler->getExport($id); if ($export === null) { return $this->pageNotFound(); } // Render standard view or ajax one $templateName = 'export-page'; if ($this->getRequest()->isXmlHttpRequest()) { $templateName = 'ajax/export-modal'; } return $this->render( $templateName, [ 'exportId' => $id, 'hasImages' => $export->hasImages(), 'hasDocuments' => $export->hasDocuments(), 'useRange' => $export->useRangeDate() ] ); }
php
{ "resource": "" }
q1694
ExportController.exportAction
train
public function exportAction($id) { /** @var \Thelia\Handler\Exporthandler $exportHandler */ $exportHandler = $this->container->get('thelia.export.handler'); $export = $exportHandler->getExport($id); if ($export === null) { return $this->pageNotFound(); } $form = $this->createForm(AdminForm::EXPORT); try { $validatedForm = $this->validateForm($form); set_time_limit(0); $lang = (new LangQuery)->findPk($validatedForm->get('language')->getData()); /** @var \Thelia\Core\Serializer\SerializerManager $serializerManager */ $serializerManager = $this->container->get(RegisterSerializerPass::MANAGER_SERVICE_ID); $serializer = $serializerManager->get($validatedForm->get('serializer')->getData()); $archiver = null; if ($validatedForm->get('do_compress')->getData()) { /** @var \Thelia\Core\Archiver\ArchiverManager $archiverManager */ $archiverManager = $this->container->get(RegisterArchiverPass::MANAGER_SERVICE_ID); $archiver = $archiverManager->get($validatedForm->get('archiver')->getData()); } $rangeDate = null; if ($validatedForm->get('range_date_start')->getData() && $validatedForm->get('range_date_end')->getData() ) { $rangeDate = [ 'start' => $validatedForm->get('range_date_start')->getData(), 'end' =>$validatedForm->get('range_date_end')->getData() ]; } $exportEvent = $exportHandler->export( $export, $serializer, $archiver, $lang, $validatedForm->get('images')->getData(), $validatedForm->get('documents')->getData(), $rangeDate ); $contentType = $exportEvent->getSerializer()->getMimeType(); $fileExt = $exportEvent->getSerializer()->getExtension(); if ($exportEvent->getArchiver() !== null) { $contentType = $exportEvent->getArchiver()->getMimeType(); $fileExt = $exportEvent->getArchiver()->getExtension(); } $header = [ 'Content-Type' => $contentType, 'Content-Disposition' => sprintf( '%s; filename="%s.%s"', ResponseHeaderBag::DISPOSITION_ATTACHMENT, $exportEvent->getExport()->getFileName(), $fileExt ) ]; return new BinaryFileResponse($exportEvent->getFilePath(), 200, $header, false); } catch (FormValidationException $e) { $form->setErrorMessage($this->createStandardFormValidationErrorMessage($e)); } catch (\Exception $e) { $this->getParserContext()->setGeneralError($e->getMessage()); } $this->getParserContext() ->addForm($form) ; return $this->configureAction($id); }
php
{ "resource": "" }
q1695
TokenIterator.current
train
public function current() { if ($this->position >= $this->length) { return NULL; } return $this->tokens[$this->position]; }
php
{ "resource": "" }
q1696
TokenIterator.peek
train
public function peek($offset) { if ($this->position + $offset >= $this->length) { return NULL; } return $this->tokens[$this->position + $offset]; }
php
{ "resource": "" }
q1697
TokenIterator.next
train
public function next() { $this->position++; if ($this->position >= $this->length) { $this->position = $this->length; return NULL; } return $this->tokens[$this->position]; }
php
{ "resource": "" }
q1698
YoFactory.make
train
public function make(array $config) { Arr::requires($config, ['token']); $client = new Client(); return new YoGateway($client, $config); }
php
{ "resource": "" }
q1699
OrderStatus.isNotPaid
train
public function isNotPaid($exact = true) { //return $this->hasStatusHelper(OrderStatus::CODE_NOT_PAID); if ($exact) { return $this->hasStatusHelper(OrderStatus::CODE_NOT_PAID); } else { return ! $this->isPaid(false); } }
php
{ "resource": "" }