_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1400 | Document.processDocument | train | public function processDocument(DocumentEvent $event)
{
$subdir = $event->getCacheSubdirectory();
$sourceFile = $event->getSourceFilepath();
if (null == $subdir || null == $sourceFile) {
throw new \InvalidArgumentException("Cache sub-directory and source file path cannot be null");
}
$originalDocumentPathInCache = $this->getCacheFilePath($subdir, $sourceFile, true);
if (! file_exists($originalDocumentPathInCache)) {
if (! file_exists($sourceFile)) {
throw new DocumentException(sprintf("Source document file %s does not exists.", $sourceFile));
}
$mode = ConfigQuery::read(self::CONFIG_DELIVERY_MODE, 'symlink');
if ($mode == 'symlink') {
if (false === symlink($sourceFile, $originalDocumentPathInCache)) {
throw new DocumentException(sprintf("Failed to create symbolic link for %s in %s document cache directory", basename($sourceFile), $subdir));
}
} else {
// mode = 'copy'
if (false === @copy($sourceFile, $originalDocumentPathInCache)) {
throw new DocumentException(sprintf("Failed to copy %s in %s document cache directory", basename($sourceFile), $subdir));
}
}
}
// Compute the document URL
$documentUrl = $this->getCacheFileURL($subdir, basename($originalDocumentPathInCache));
// Update the event with file path and file URL
$event->setDocumentPath($documentUrl);
$event->setDocumentUrl(URL::getInstance()->absoluteUrl($documentUrl, null, URL::PATH_TO_FILE, $this->cdnBaseUrl));
} | php | {
"resource": ""
} |
q1401 | Category.create | train | public function create(CategoryCreateEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$category = new CategoryModel();
$category
->setDispatcher($dispatcher)
->setLocale($event->getLocale())
->setParent($event->getParent())
->setVisible($event->getVisible())
->setTitle($event->getTitle())
->save()
;
$event->setCategory($category);
} | php | {
"resource": ""
} |
q1402 | Category.update | train | public function update(CategoryUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if (null !== $category = CategoryQuery::create()->findPk($event->getCategoryId())) {
$category
->setDispatcher($dispatcher)
->setDefaultTemplateId($event->getDefaultTemplateId() == 0 ? null : $event->getDefaultTemplateId())
->setLocale($event->getLocale())
->setTitle($event->getTitle())
->setDescription($event->getDescription())
->setChapo($event->getChapo())
->setPostscriptum($event->getPostscriptum())
->setParent($event->getParent())
->setVisible($event->getVisible())
->save();
$event->setCategory($category);
}
} | php | {
"resource": ""
} |
q1403 | Category.delete | train | public function delete(CategoryDeleteEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if (null !== $category = CategoryQuery::create()->findPk($event->getCategoryId())) {
$con = Propel::getWriteConnection(CategoryTableMap::DATABASE_NAME);
$con->beginTransaction();
try {
$fileList = ['images' => [], 'documentList' => []];
// Get category's files to delete after category deletion
$fileList['images']['list'] = CategoryImageQuery::create()
->findByCategoryId($event->getCategoryId());
$fileList['images']['type'] = TheliaEvents::IMAGE_DELETE;
$fileList['documentList']['list'] = CategoryDocumentQuery::create()
->findByCategoryId($event->getCategoryId());
$fileList['documentList']['type'] = TheliaEvents::DOCUMENT_DELETE;
// Delete category
$category
->setDispatcher($dispatcher)
->delete($con);
$event->setCategory($category);
// Dispatch delete category's files event
foreach ($fileList as $fileTypeList) {
foreach ($fileTypeList['list'] as $fileToDelete) {
$fileDeleteEvent = new FileDeleteEvent($fileToDelete);
$dispatcher->dispatch($fileTypeList['type'], $fileDeleteEvent);
}
}
$con->commit();
} catch (\Exception $e) {
$con->rollback();
throw $e;
}
}
} | php | {
"resource": ""
} |
q1404 | Category.toggleVisibility | train | public function toggleVisibility(CategoryToggleVisibilityEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$category = $event->getCategory();
$category
->setDispatcher($dispatcher)
->setVisible($category->getVisible() ? false : true)
->save()
;
$event->setCategory($category);
} | php | {
"resource": ""
} |
q1405 | Category.viewCheck | train | public function viewCheck(ViewCheckEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if ($event->getView() == 'category') {
$category = CategoryQuery::create()
->filterById($event->getViewId())
->filterByVisible(1)
->count();
if ($category == 0) {
$dispatcher->dispatch(TheliaEvents::VIEW_CATEGORY_ID_NOT_VISIBLE, $event);
}
}
} | php | {
"resource": ""
} |
q1406 | SiteController.renderToolSiteHeaderAction | train | public function renderToolSiteHeaderAction() {
$melisTool = $this->getServiceLocator()->get('MelisCoreTool');
$melisKey = $this->params()->fromRoute('melisKey', '');
$melisTool->setMelisToolKey(self::TOOL_INDEX, self::TOOL_KEY);
$view = new ViewModel();
$view->title = $melisTool->getTitle();
return $view;
} | php | {
"resource": ""
} |
q1407 | SiteController.renderToolSiteModalAddAction | train | public function renderToolSiteModalAddAction()
{
// declare the Tool service that we will be using to completely create our tool.
$melisTool = $this->getServiceLocator()->get('MelisCoreTool');
// tell the Tool what configuration in the app.tool.php that will be used.
$melisTool->setMelisToolKey(self::TOOL_INDEX, self::TOOL_KEY);
$view = new ViewModel();
$view->setVariable('meliscms_site_tool_creation_form', $melisTool->getForm('meliscms_site_tool_creation_form'));
return $view;
} | php | {
"resource": ""
} |
q1408 | SiteController.getSiteDomainPlatform | train | public function getSiteDomainPlatform()
{
$data = array();
if($this->getRequest()->isGet()){
$siteDomain = $this->getServiceLocator()->get('SiteDomain');
$data = $siteDomain->getSiteDomain();
}
return $data;
} | php | {
"resource": ""
} |
q1409 | SiteController.getSiteEnvironmentAction | train | public function getSiteEnvironmentAction()
{
$json = array();
$siteId = (int) $this->params()->fromQuery('siteId');
$melisEngineTableSiteDomain = $this->getServiceLocator()->get('MelisEngineTableSiteDomain');
$sitePlatform = $melisEngineTableSiteDomain->getEntryByField('sdom_site_id', $siteId);
$sitePlatform = $sitePlatform->current();
$siteDomainEnv = ($sitePlatform) ? $sitePlatform->sdom_env : null;
return new JsonModel(array('data' => $siteDomainEnv));
} | php | {
"resource": ""
} |
q1410 | SiteController.getSiteEnvironmentsAction | train | public function getSiteEnvironmentsAction()
{
$json = array();
$siteId = (int) $this->params()->fromQuery('siteId');
$domainTable = $this->getServiceLocator()->get('MelisCoreTablePlatform');
$domainData = $domainTable->fetchAll();
$domainData = $domainData->toArray();
if($domainData) {
foreach($domainData as $domainValues) {
$json[] = $domainValues['plf_name'];
}
}
return new JsonModel(array('data' => $json));
} | php | {
"resource": ""
} |
q1411 | SiteController.deleteSiteByIdAction | train | public function deleteSiteByIdAction()
{
$translator = $this->getServiceLocator()->get('translator');
$request = $this->getRequest();
$domainId = null;
$success = 0;
$textTitle = 'tr_meliscms_tool_site';
$textMessage = '';
$eventDatas = array();
$this->getEventManager()->trigger('meliscms_site_delete_by_id_start', $this, $eventDatas);
if($request->isPost()) {
$domainTable = $this->getServiceLocator()->get('MelisEngineTableSiteDomain');
$site404Table = $this->getServiceLocator()->get('MelisEngineTableSite404');
$siteID = (int) $request->getPost('siteid');
$siteEnv = $request->getPost('env');
$site404PageId = $request->getPost('site404Page');
$domainData = $domainTable->getDataBySiteIdAndEnv($siteID,$siteEnv);
$domainData = $domainData->current();
if($domainData)
{
$domainId = $domainData->sdom_id;
$domainTable->deleteByField('sdom_id', $domainId);
$success = 1;
$textMessage = 'tr_meliscms_tool_site_delete_env_success';
}
else
{
$textMessage = 'tr_meliscms_tool_site_delete_env_failed';
}
}
$response = array(
'success' => $success,
'textTitle' => $textTitle,
'textMessage' => $textMessage,
);
$this->getEventManager()->trigger('meliscms_site_delete_by_id_end', $this, array_merge($response, array('typeCode' => 'CMS_SITE_ENV_DELETE', 'itemId' => $domainId)));
return new JsonModel($response);
} | php | {
"resource": ""
} |
q1412 | UseDeclarationNode.setAlias | train | public function setAlias($alias) {
if (is_string($alias)) {
$alias = new TokenNode(T_STRING, $alias);
}
if ($alias instanceof TokenNode) {
if ($this->hasAlias()) {
$this->alias->replaceWith($alias);
}
else {
$this->alias = $alias;
$this->addChild(WhitespaceNode::create(' '));
$this->addChild(Token::_as());
$this->addChild(WhitespaceNode::create(' '));
$this->addChild($alias, 'alias');
}
}
elseif ($alias === NULL && $this->hasAlias()) {
$this->alias->previousUntil(Filter::isInstanceOf('\Pharborist\Namespaces\NameNode'))->remove();
$this->alias->remove();
$this->alias = NULL;
}
else {
throw new \InvalidArgumentException();
}
return $this;
} | php | {
"resource": ""
} |
q1413 | UseDeclarationNode.getBoundedName | train | public function getBoundedName() {
if ($this->alias) {
return $this->alias->getText();
}
else {
return $this->name->lastChild()->getText();
}
} | php | {
"resource": ""
} |
q1414 | Order.orderCartClear | train | public function orderCartClear(/** @noinspection PhpUnusedParameterInspection */ OrderEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
// Empty cart and clear current order
$session = $this->getSession();
$session->clearSessionCart($dispatcher);
$session->setOrder(new OrderModel());
} | php | {
"resource": ""
} |
q1415 | Order.getStockUpdateOnOrderStatusChange | train | public function getStockUpdateOnOrderStatusChange(GetStockUpdateOperationOnOrderStatusChangeEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
// The order
$order = $event->getOrder();
// The new order status
$newStatus = $event->getNewOrderStatus();
if ($newStatus->getId() !== $order->getStatusId()) {
// We have to change the stock in the following cases :
// 1) The order is currently paid, and will become unpaid (get products back in stock unconditionnaly)
// 2) The order is currently unpaid, and will become paid (remove products from stock, except if was done at order creation $manageStockOnCreation == false)
// 3) The order is currently NOT PAID, and will become canceled or the like (get products back in stock if it was done at order creation $manageStockOnCreation == true)
// We consider the ManageStockOnCreation flag only if the order status as not yet changed.
// Count distinct order statuses (e.g. NOT_PAID to something else) in the order version table.
if (OrderVersionQuery::create()->groupByStatusId()->filterById($order->getId())->count() > 1) {
// A status change occured. Ignore $manageStockOnCreation
$manageStockOnCreation = false;
} else {
// A status has not yet occured. Consider the ManageStockOnCreation flag
$manageStockOnCreation = $order->isStockManagedOnOrderCreation($dispatcher);
}
if (($order->isPaid(false) && $newStatus->isNotPaid(false)) // Case 1
||
($order->isNotPaid(true) && $newStatus->isNotPaid(false) && $manageStockOnCreation === true) // Case 3
) {
$event->setOperation($event::INCREASE_STOCK);
}
if ($order->isNotPaid(false) // Case 2
&&
$newStatus->isPaid(false)
&&
$manageStockOnCreation === false) {
$event->setOperation($event::DECREASE_STOCK);
}
Tlog::getInstance()->addInfo(
"Checking stock operation for status change of order : " . $order->getRef()
. ", version: " . $order->getVersion()
. ", manageStockOnCreation: " . ($manageStockOnCreation ? 0 : 1)
. ", paid:" . ($order->isPaid(false) ? 1 : 0)
. ", is not paid:" . ($order->isNotPaid(false) ? 1 : 0)
. ", new status paid:" . ($newStatus->isPaid(false) ? 1 : 0)
. ", new status is not paid:" . ($newStatus->isNotPaid(false) ? 1 : 0)
. " = operation: " . $event->getOperation()
);
}
} | php | {
"resource": ""
} |
q1416 | Order.updateQuantity | train | protected function updateQuantity(ModelOrder $order, $newStatus, EventDispatcherInterface $dispatcher)
{
if ($newStatus !== $order->getStatusId()) {
if (null !== $newStatusModel = OrderStatusQuery::create()->findPk($newStatus)) {
$operationEvent = new GetStockUpdateOperationOnOrderStatusChangeEvent($order, $newStatusModel);
$dispatcher->dispatch(
TheliaEvents::ORDER_GET_STOCK_UPDATE_OPERATION_ON_ORDER_STATUS_CHANGE,
$operationEvent
);
if ($operationEvent->getOperation() !== $operationEvent::DO_NOTHING) {
$orderProductList = $order->getOrderProducts();
/** @var OrderProduct $orderProduct */
foreach ($orderProductList as $orderProduct) {
$productSaleElementsId = $orderProduct->getProductSaleElementsId();
/** @var ProductSaleElements $productSaleElements */
if (null !== $productSaleElements = ProductSaleElementsQuery::create()->findPk($productSaleElementsId)) {
$offset = 0;
if ($operationEvent->getOperation() == $operationEvent::INCREASE_STOCK) {
$offset = $orderProduct->getQuantity();
} elseif ($operationEvent->getOperation() == $operationEvent::DECREASE_STOCK) {
/* Check if we have enough stock */
if ($orderProduct->getQuantity() > $productSaleElements->getQuantity() && true === ConfigQuery::checkAvailableStock()) {
throw new TheliaProcessException($productSaleElements->getRef() . " : Not enough stock 2");
}
$offset = -$orderProduct->getQuantity();
}
Tlog::getInstance()->addError("Product stock: " . $productSaleElements->getQuantity() . " -> " . ($productSaleElements->getQuantity() + $offset));
$productSaleElements
->setQuantity($productSaleElements->getQuantity() + $offset)
->save();
}
}
}
}
}
} | php | {
"resource": ""
} |
q1417 | PostNewKey.admin_notices | train | public function admin_notices() {
$afterKeyAdded = get_option( $this->option );
if ( empty( $afterKeyAdded ) ) {
return;
}
switch( $afterKeyAdded ) {
case 'success':
echo '<div class="notice notice-success is-dismissible bglib-key-added"><p>' .
esc_html( 'Your new BoldGrid Connect Key has been successfully added!', 'boldgrid-library' ) .
'</p></div>';
break;
case 'fail':
echo '<div class="notice notice-error is-dismissible bglib-key-added"><p>' .
esc_html( 'An unknown error occurred adding your new BoldGrid Connect Key.', 'boldgrid-library' ) .
'</p></div>';
break;
}
delete_option( $this->option );
} | php | {
"resource": ""
} |
q1418 | PostNewKey.getCentralUrl | train | public static function getCentralUrl() {
/**
* Allow the return url to be filtered.
*
* The return url is the url that BoldGrid Central will link the user to after they received
* their new BoldGrid Connect Key.
*
* By default, we will link them to Dashboard > Settings > BoldGrid Connect. However,
* with this filter plugins can change this url.
*
* @since 2.8.0
*
* @param string URL to the BoldGrid Connect settings page.
*/
$returnUrl = apply_filters( 'Boldgrid\Library\Key\returnUrl', admin_url( 'options-general.php?page=boldgrid-connect.php' ) );
$returnUrl = add_query_arg( 'nonce', wp_create_nonce( 'bglib-key-prompt' ), $returnUrl );
// Create the final url and return it.
return add_query_arg(
array(
'wp-url' => urlencode( $returnUrl ),
),
Configs::get( 'getNewKey' )
);
} | php | {
"resource": ""
} |
q1419 | PostNewKey.processPost | train | public function processPost() {
if ( $this->isPosting() ) {
$releaseChannel = new ReleaseChannel;
$key = new Key( $releaseChannel );
$hashed_key = md5( $_POST['activateKey'] );
$success = $key->addKey( $hashed_key );
/*
* This option is used to setup an event similiar to WordPress' after_switch_theme hook.
* It allows us to take action on the page load following a new Connect Key being added.
*/
update_option( $this->option, $success ? 'success' : 'fail' );
/*
* Refersh the current page so that when it reloads the new page begins with the user
* having a Connect Key installed. Otherwise, the current page will load and propmpt the
* user for a key even though we've just added one.
*/
header( 'Refresh:0' );
exit;
}
} | php | {
"resource": ""
} |
q1420 | PostNewKey.isPosting | train | private function isPosting() {
if ( empty( $_POST['activateKey'] ) ) {
return false;
}
if ( empty( $_GET['nonce'] ) || ! wp_verify_nonce( $_GET['nonce'], 'bglib-key-prompt') ) {
return false;
}
if ( ! current_user_can( 'update_plugins' ) ) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q1421 | ResponseRest.setRestContent | train | public function setRestContent($data)
{
$serializer = $this->getSerializer();
if (isset($data)) {
$this->setContent($serializer->serialize($data, $this->format));
}
return $this;
} | php | {
"resource": ""
} |
q1422 | NameNode.create | train | public static function create($name) {
$parts = explode('\\', $name);
$name_node = new NameNode();
foreach ($parts as $i => $part) {
$part = trim($part);
if ($i > 0) {
$name_node->append(Token::namespaceSeparator());
}
if ($part !== '') {
$name_node->append(Token::identifier($part));
}
}
return $name_node;
} | php | {
"resource": ""
} |
q1423 | NameNode.getPathInfo | train | public function getPathInfo() {
/** @var TokenNode $first */
$first = $this->firstChild();
$absolute = $first->getType() === T_NS_SEPARATOR;
$relative = $first->getType() === T_NAMESPACE;
$parts = $this->getParts();
return [
'absolute' => $absolute,
'relative' => $relative,
'qualified' => !$absolute && count($parts) > 1,
'unqualified' => !$absolute && count($parts) === 1,
'parts' => $parts,
];
} | php | {
"resource": ""
} |
q1424 | NameNode.getPath | train | public function getPath() {
$path = '';
/** @var TokenNode $child */
$child = $this->head;
while ($child) {
$type = $child->getType();
if ($type === T_NAMESPACE || $type === T_NS_SEPARATOR || $type === T_STRING) {
$path .= $child->getText();
}
$child = $child->next;
}
return $path;
} | php | {
"resource": ""
} |
q1425 | NameNode.resolveUnqualified | train | protected function resolveUnqualified($name) {
if ($this->parent instanceof NamespaceNode) {
return '\\' . $name;
}
if ($this->parent instanceof UseDeclarationNode) {
return '\\' . $name;
}
$namespace = $this->getNamespace();
$use_declarations = array();
if ($namespace) {
$use_declarations = $namespace->getBody()->getUseDeclarations();
}
else {
/** @var \Pharborist\RootNode $root_node */
$root_node = $this->closest(Filter::isInstanceOf('\Pharborist\RootNode'));
if ($root_node) {
$use_declarations = $root_node->getUseDeclarations();
}
}
if ($this->parent instanceof FunctionCallNode) {
/** @var UseDeclarationNode $use_declaration */
foreach ($use_declarations as $use_declaration) {
if ($use_declaration->isFunction() && $use_declaration->getBoundedName() === $name) {
return '\\' . $use_declaration->getName()->getPath();
}
}
return $this->getParentPath() . $name;
}
elseif ($this->parent instanceof ConstantNode) {
/** @var UseDeclarationNode $use_declaration */
foreach ($use_declarations as $use_declaration) {
if ($use_declaration->isConst() && $use_declaration->getBoundedName() === $name) {
return '\\' . $use_declaration->getName()->getPath();
}
}
return $this->getParentPath() . $name;
}
else {
// Name is a class reference.
/** @var UseDeclarationNode $use_declaration */
foreach ($use_declarations as $use_declaration) {
if ($use_declaration->isClass() && $use_declaration->getBoundedName() === $name) {
return '\\' . $use_declaration->getName()->getPath();
}
}
// No use declaration so class name refers to class in current namespace.
return $this->getParentPath() . $name;
}
} | php | {
"resource": ""
} |
q1426 | ReferenceAnalyzer.analyze | train | public function analyze(string $path)
{
$contents = (string) file_get_contents($path);
$traverser = new NodeTraverser();
$traverser->addVisitor(new NameResolver());
$traverser->addVisitor($imports = new ImportVisitor());
$traverser->addVisitor($names = new NameVisitor());
$traverser->addVisitor($docs = DocVisitor::create($contents));
$traverser->traverse($this->parser->parse($contents));
return array_values(array_unique(array_merge(
$imports->getImports(),
$names->getNames(),
DocProcessor::process($docs->getDoc())
)));
} | php | {
"resource": ""
} |
q1427 | CommentNode.create | train | public static function create($comment) {
$comment = trim($comment);
$nl_count = substr_count($comment, "\n");
if ($nl_count > 1) {
return LineCommentBlockNode::create($comment);
}
else {
return new CommentNode(T_COMMENT, '// ' . $comment . "\n");
}
} | php | {
"resource": ""
} |
q1428 | ClientManager.getWebhookForClient | train | public function getWebhookForClient($name)
{
return Arr::get($this->clientsConfig[$name], 'webhook') ?:
Arr::get($this->clientsDefaults, 'webhook');
} | php | {
"resource": ""
} |
q1429 | ClientManager.getMessageDefaultsForClient | train | public function getMessageDefaultsForClient($name)
{
return array_merge(
Arr::get($this->clientsDefaults, 'message_defaults', []),
Arr::get($this->clientsConfig[$name], 'message_defaults', [])
);
} | php | {
"resource": ""
} |
q1430 | Mailer.sendRestorePassword | train | public function sendRestorePassword(string $email, string $hash): void
{
$mail = $this->createMail('restorePassword');
$mail->link = $this->link('Cms:Sign:restorePassword', [
'hash' => $hash
]);
$mail->setSubject('cms.mailing.restorePassword.subject')
->addTo($email);
$mail->send();
} | php | {
"resource": ""
} |
q1431 | Mailer.sendNewUser | train | public function sendNewUser(string $email, string $username, string $password): void
{
$mail = $this->createMail('newUser');
$mail->link = $this->link('Cms:Sign:in');
$mail->username = $username;
$mail->password = $password;
$mail->setSubject('cms.mailing.newUser.subject')
->addTo($email);
$mail->send();
} | php | {
"resource": ""
} |
q1432 | State.toggleVisibility | train | public function toggleVisibility(StateToggleVisibilityEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
$state = $event->getState();
$state
->setDispatcher($dispatcher)
->setVisible(!$state->getVisible())
->save()
;
$event->setState($state);
} | php | {
"resource": ""
} |
q1433 | StatementNode.getLineCount | train | public function getLineCount() {
$count = 1;
$this
->find(Filter::isInstanceOf('\Pharborist\WhitespaceNode'))
->each(function(WhitespaceNode $node) use (&$count) {
$count += $node->getNewlineCount();
});
return $count;
} | php | {
"resource": ""
} |
q1434 | StatementNode.addCommentAbove | train | public function addCommentAbove($comment) {
if ($comment instanceof LineCommentBlockNode) {
$this->before($comment);
}
elseif (is_string($comment)) {
$this->addCommentAbove(LineCommentBlockNode::create($comment));
}
else {
throw new \InvalidArgumentException();
}
return $this;
} | php | {
"resource": ""
} |
q1435 | ParameterNode.create | train | public static function create($parameter_name) {
$parameter_name = '$' . ltrim($parameter_name, '$');
$parameter_node = new ParameterNode();
$parameter_node->addChild(new VariableNode(T_VARIABLE, $parameter_name), 'name');
return $parameter_node;
} | php | {
"resource": ""
} |
q1436 | ParameterNode.getDocBlockTag | train | public function getDocBlockTag() {
$doc_comment = $this->getFunction()->getDocComment();
return $doc_comment ? $doc_comment->getParameter($this->name->getText()) : NULL;
} | php | {
"resource": ""
} |
q1437 | ParameterNode.hasDocTypes | train | public function hasDocTypes() {
$doc_comment = $this->getFunction()->getDocComment();
if (!$doc_comment) {
return FALSE;
}
$param_tag = $doc_comment->getParameter($this->getName());
if (!$param_tag) {
return FALSE;
}
$types = $param_tag->getTypes();
return !empty($types);
} | php | {
"resource": ""
} |
q1438 | ParameterNode.getDocTypes | train | public function getDocTypes() {
// No type specified means type is mixed.
$types = ['mixed'];
// Use types from the doc comment if available.
$doc_comment = $this->getFunction()->getDocComment();
if (!$doc_comment) {
return $types;
}
$param_tag = $doc_comment->getParameter($this->getName());
if (!$param_tag) {
return $types;
}
$types = Types::normalize($param_tag->getTypes());
if (empty($types)) {
$types[] = 'mixed';
}
return $types;
} | php | {
"resource": ""
} |
q1439 | ParameterNode.getTypes | train | public function getTypes() {
// If type hint is set then that is the type of the parameter.
if ($this->typeHint) {
if ($this->typeHint instanceof TokenNode) {
if ($this->typeHint->getType() === T_ARRAY) {
$docTypes = $this->getDocTypes();
foreach ($docTypes as $docType) {
if ($docType !== 'array' && substr($docType, -2) !== '[]') {
return [$this->typeHint->getText()];
}
}
return $docTypes;
}
else {
return [$this->typeHint->getText()];
}
}
else {
return [$this->typeHint->getAbsolutePath()];
}
}
return $this->getDocTypes();
} | php | {
"resource": ""
} |
q1440 | ContentController.addAdditionalFolderAction | train | public function addAdditionalFolderAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
return $response;
}
$folder_id = \intval($this->getRequest()->request->get('additional_folder_id'));
if ($folder_id > 0) {
$event = new ContentAddFolderEvent(
$this->getExistingObject(),
$folder_id
);
try {
$this->dispatch(TheliaEvents::CONTENT_ADD_FOLDER, $event);
} catch (\Exception $e) {
return $this->errorPage($e);
}
}
return $this->redirectToEditionTemplate();
} | php | {
"resource": ""
} |
q1441 | ContentController.removeAdditionalFolderAction | train | public function removeAdditionalFolderAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
return $response;
}
$folder_id = \intval($this->getRequest()->request->get('additional_folder_id'));
if ($folder_id > 0) {
$event = new ContentRemoveFolderEvent(
$this->getExistingObject(),
$folder_id
);
try {
$this->dispatch(TheliaEvents::CONTENT_REMOVE_FOLDER, $event);
} catch (\Exception $e) {
return $this->errorPage($e);
}
}
return $this->redirectToEditionTemplate();
} | php | {
"resource": ""
} |
q1442 | TaxEngine.getDeliveryCountry | train | public function getDeliveryCountry()
{
if (null === $this->taxCountry) {
/* is there a logged in customer ? */
/** @var Customer $customer */
if (null !== $customer = $this->getSession()->getCustomerUser()) {
if (null !== $this->getSession()->getOrder()
&& null !== $this->getSession()->getOrder()->getChoosenDeliveryAddress()
&& null !== $currentDeliveryAddress = AddressQuery::create()->findPk($this->getSession()->getOrder()->getChoosenDeliveryAddress())) {
$this->taxCountry = $currentDeliveryAddress->getCountry();
$this->taxState = $currentDeliveryAddress->getState();
} else {
$customerDefaultAddress = $customer->getDefaultAddress();
if (isset($customerDefaultAddress)) {
$this->taxCountry = $customerDefaultAddress->getCountry();
$this->taxState = $customerDefaultAddress->getState();
}
}
}
if (null == $this->taxCountry) {
$this->taxCountry = CountryQuery::create()->findOneByByDefault(1);
$this->taxState = null;
}
}
return $this->taxCountry;
} | php | {
"resource": ""
} |
q1443 | CategoryController.setToggleVisibilityAction | train | public function setToggleVisibilityAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
return $response;
}
$event = new CategoryToggleVisibilityEvent($this->getExistingObject());
try {
$this->dispatch(TheliaEvents::CATEGORY_TOGGLE_VISIBILITY, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
// Ajax response -> no action
return $this->nullResponse();
} | php | {
"resource": ""
} |
q1444 | CategoryController.addRelatedPictureAction | train | public function addRelatedPictureAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
return $response;
}
return $this->redirectToEditionTemplate();
} | php | {
"resource": ""
} |
q1445 | DocProcessor.process | train | public static function process(array $docs)
{
return self::flatmap(function ($doc) {
return self::flatmap(function ($tag) {
return self::flatmap(function ($type) {
return self::processType($type);
}, self::processTag($tag));
}, $doc->getTags());
}, $docs);
} | php | {
"resource": ""
} |
q1446 | DocProcessor.processTag | train | private static function processTag(BaseTag $tag)
{
$types = [];
if (method_exists($tag, 'getType') && is_callable([$tag, 'getType'])) {
if (($type = $tag->getType()) !== null) {
$types[] = $type;
}
}
if (method_exists($tag, 'getArguments') && is_callable([$tag, 'getArguments'])) {
foreach ($tag->getArguments() as $param) {
if (($type = $param['type'] ?? null) !== null) {
$types[] = $type;
}
}
}
return $types;
} | php | {
"resource": ""
} |
q1447 | DocProcessor.processType | train | private static function processType(Type $type)
{
// TODO type-resolver v1 compat
// if ($type instanceof AbstractList) {
if ($type instanceof Array_) {
return self::flatmap(function ($t) {
return self::processType($t);
}, [$type->getKeyType(), $type->getValueType()]);
}
if ($type instanceof Compound) {
return self::flatmap(function ($t) {
return self::processType($t);
}, iterator_to_array($type));
}
if ($type instanceof Nullable) {
return self::processType($type->getActualType());
}
if ($type instanceof Object_) {
if (($fq = $type->getFqsen()) !== null) {
return [ltrim((string) $fq, '\\')];
}
}
return [];
} | php | {
"resource": ""
} |
q1448 | BaseLoop.initialize | train | protected function initialize()
{
$class = \get_class($this);
if (null === self::$loopDefinitions) {
self::$loopDefinitions = \array_flip($this->container->getParameter('thelia.parser.loops'));
}
if (isset(self::$loopDefinitions[$class])) {
$this->loopName = self::$loopDefinitions[$class];
}
if (!isset(self::$loopDefinitionsArgs[$class])) {
$this->args = $this->getArgDefinitions()->addArguments($this->getDefaultArgs(), false);
$eventName = $this->getDispatchEventName(TheliaEvents::LOOP_EXTENDS_ARG_DEFINITIONS);
if (null !== $eventName) {
$this->dispatcher->dispatch(
$eventName,
new LoopExtendsArgDefinitionsEvent($this)
);
};
self::$loopDefinitionsArgs[$class] = $this->args;
}
$this->args = self::$loopDefinitionsArgs[$class];
} | php | {
"resource": ""
} |
q1449 | BaseLoop.getDefaultArgs | train | protected function getDefaultArgs()
{
$defaultArgs = [
Argument::createBooleanTypeArgument('backend_context', false),
Argument::createBooleanTypeArgument('force_return', false),
Argument::createAnyTypeArgument('type'),
Argument::createBooleanTypeArgument('no-cache', false),
Argument::createBooleanTypeArgument('return_url', true)
];
if (true === $this->countable) {
$defaultArgs[] = Argument::createIntTypeArgument('offset', 0);
$defaultArgs[] = Argument::createIntTypeArgument('page');
$defaultArgs[] = Argument::createIntTypeArgument('limit', PHP_INT_MAX);
}
if ($this instanceof SearchLoopInterface) {
$defaultArgs[] = Argument::createAnyTypeArgument('search_term');
$defaultArgs[] = new Argument(
'search_in',
new TypeCollection(
new EnumListType($this->getSearchIn())
)
);
$defaultArgs[] = new Argument(
'search_mode',
new TypeCollection(
new EnumType(
[
SearchLoopInterface::MODE_ANY_WORD,
SearchLoopInterface::MODE_SENTENCE,
SearchLoopInterface::MODE_STRICT_SENTENCE,
]
)
),
SearchLoopInterface::MODE_STRICT_SENTENCE
);
}
return $defaultArgs;
} | php | {
"resource": ""
} |
q1450 | BaseLoop.initializeArgs | train | public function initializeArgs(array $nameValuePairs)
{
$faultActor = [];
$faultDetails = [];
if (null !== $eventName = $this->getDispatchEventName(TheliaEvents::LOOP_EXTENDS_INITIALIZE_ARGS)) {
$event = new LoopExtendsInitializeArgsEvent($this, $nameValuePairs);
$this->dispatcher->dispatch($eventName, $event);
$nameValuePairs = $event->getLoopParameters();
}
$loopType = isset($nameValuePairs['type']) ? $nameValuePairs['type'] : "undefined";
$loopName = isset($nameValuePairs['name']) ? $nameValuePairs['name'] : "undefined";
$this->args->rewind();
while (($argument = $this->args->current()) !== false) {
$this->args->next();
$value = isset($nameValuePairs[$argument->name]) ? $nameValuePairs[$argument->name] : null;
/* check if mandatory */
if ($value === null && $argument->mandatory) {
$faultActor[] = $argument->name;
$faultDetails[] = $this->translator->trans(
'"%param" parameter is missing in loop type: %type, name: %name',
[
'%param' => $argument->name,
'%type' => $loopType,
'%name' => $loopName
]
);
} elseif ($value === '') {
if (!$argument->empty) {
/* check if empty */
$faultActor[] = $argument->name;
$faultDetails[] = $this->translator->trans(
'"%param" parameter cannot be empty in loop type: %type, name: %name',
[
'%param' => $argument->name,
'%type' => $loopType,
'%name' => $loopName
]
);
}
} elseif ($value !== null && !$argument->type->isValid($value)) {
/* check type */
$faultActor[] = $argument->name;
$faultDetails[] = $this->translator->trans(
'Invalid value "%value" for "%param" parameter in loop type: %type, name: %name',
[
'%value' => $value,
'%param' => $argument->name,
'%type' => $loopType,
'%name' => $loopName
]
);
} else {
/* set default value */
/* did it as last checking for we consider default value is acceptable no matter type or empty restriction */
if ($value === null) {
$value = $argument->default;
}
$argument->setValue($value);
}
}
if (! empty($faultActor)) {
$complement = sprintf('[%s]', implode(', ', $faultDetails));
throw new \InvalidArgumentException($complement);
}
} | php | {
"resource": ""
} |
q1451 | BaseLoop.getArg | train | protected function getArg($argumentName)
{
$arg = $this->args->get($argumentName);
if ($arg === null) {
throw new \InvalidArgumentException(
$this->translator->trans('Undefined loop argument "%name"', ['%name' => $argumentName])
);
}
return $arg;
} | php | {
"resource": ""
} |
q1452 | BaseLoop.getDispatchEventName | train | protected function getDispatchEventName($eventName)
{
$customEventName = TheliaEvents::getLoopExtendsEvent($eventName, $this->loopName);
if (!isset(self::$dispatchCache[$customEventName])) {
self::$dispatchCache[$customEventName] = $this->dispatcher->hasListeners($customEventName);
}
return self::$dispatchCache[$customEventName]
? $customEventName
: null;
} | php | {
"resource": ""
} |
q1453 | BaseLoop.extendsBuildModelCriteria | train | protected function extendsBuildModelCriteria(ModelCriteria $search = null)
{
if (null === $search) {
return null;
}
$eventName = $this->getDispatchEventName(TheliaEvents::LOOP_EXTENDS_BUILD_MODEL_CRITERIA);
if (null !== $eventName) {
$this->dispatcher->dispatch(
$eventName,
new LoopExtendsBuildModelCriteriaEvent($this, $search)
);
}
return $search;
} | php | {
"resource": ""
} |
q1454 | BaseLoop.extendsBuildArray | train | protected function extendsBuildArray(array $search = null)
{
if (null === $search) {
return null;
}
$eventName = $this->getDispatchEventName(TheliaEvents::LOOP_EXTENDS_BUILD_ARRAY);
if (null !== $eventName) {
$event = new LoopExtendsBuildArrayEvent($this, $search);
$this->dispatcher->dispatch($eventName, $event);
$search = $event->getArray();
}
return $search;
} | php | {
"resource": ""
} |
q1455 | BaseLoop.extendsParseResults | train | protected function extendsParseResults(LoopResult $loopResult)
{
$eventName = $this->getDispatchEventName(TheliaEvents::LOOP_EXTENDS_PARSE_RESULTS);
if (null !== $eventName) {
$this->dispatcher->dispatch(
$eventName,
new LoopExtendsParseResultsEvent($this, $loopResult)
);
}
return $loopResult;
} | php | {
"resource": ""
} |
q1456 | Key.setNotice | train | public function setNotice( $forceDisplay = false ) {
if ( $this->notice ) {
return $this->notice;
}
// If we already have transient data saying the API is not available.
if ( 0 === get_site_transient( 'boldgrid_available' ) ) {
return new Notice( 'ConnectionIssue' );
}
// If we don't have a key stored, or this is not a valid response when calling.
if ( ! Configs::get( 'key' ) || ! self::$valid || $forceDisplay ) {
return new Notice( 'keyPrompt', $this );
}
} | php | {
"resource": ""
} |
q1457 | Key.addKey | train | public function addKey( $key ) {
/*
* @todo The majority of this method has been copied from
* Boldgrid\Library\Library\Notice\KeyPrompt\addKey() because the logic to add a key should
* be in this class and not the KeyPrompt class. that KeyPrompt method needs to be refactored.
*/
// When adding Keys, delete the transient to make sure we get new license info.
delete_site_transient( 'bg_license_data' );
delete_site_transient( 'boldgrid_api_data' );
$data = $this->callCheckVersion( array( 'key' => $key ) );
if ( is_object( $data ) ) {
$this->save( $data, $key );
return true;
} else {
return false;
}
} | php | {
"resource": ""
} |
q1458 | Key.callCheckVersion | train | public function callCheckVersion( $args ) {
if ( ! empty( $args['key'] ) ) {
$call = new Api\Call( Configs::get( 'api' ) . '/api/plugin/checkVersion', $args );
// If there's an error set that as the response.
if ( ! $response = $call->getError() ) {
// If the response is successful, then retrieve the response.
$response = $call->getResponse();
}
} else {
$response = 'No Connect Key available.';
}
// Return the API response.
return $response;
} | php | {
"resource": ""
} |
q1459 | Key.verify | train | public function verify( $key = null ) {
$key = $key ? $key : Configs::get( 'key' );
// Make an API call for API data.
$data = $this->callCheckVersion( array(
'key' => $key,
'channel' => $this->releaseChannel->getPluginChannel(),
'theme_channel' => $this->releaseChannel->getThemeChannel(),
) );
// Let the transient data set it's own validity.
if ( $this->verifyData( $data ) ) {
$data->license_status = true;
}
// Return back the transient data object.
return $data;
} | php | {
"resource": ""
} |
q1460 | SendBearyChat.client | train | public function client($client)
{
$this->client = $client instanceof Client ? $client : bearychat($client);
if ($this->message) {
$this->message->setClient($this->client);
}
return $this;
} | php | {
"resource": ""
} |
q1461 | Image.createImagineInstance | train | protected function createImagineInstance()
{
$driver = ConfigQuery::read("imagine_graphic_driver", "gd");
switch ($driver) {
case 'imagick':
$image = new ImagickImagine();
break;
case 'gmagick':
$image = new GmagickImagine();
break;
case 'gd':
default:
$image = new Imagine();
}
return $image;
} | php | {
"resource": ""
} |
q1462 | BallouFactory.make | train | public function make(array $config)
{
Arr::requires($config, ['token']);
$client = new Client();
return new BallouGateway($client, $config);
} | php | {
"resource": ""
} |
q1463 | ParentNode.childrenByInstance | train | protected function childrenByInstance($class_name) {
$matches = [];
$child = $this->head;
while ($child) {
if ($child instanceof $class_name) {
$matches[] = $child;
}
$child = $child->next;
}
return $matches;
} | php | {
"resource": ""
} |
q1464 | ParentNode.prependChild | train | protected function prependChild(Node $node) {
if ($this->head === NULL) {
$this->childCount++;
$node->parent = $this;
$node->previous = NULL;
$node->next = NULL;
$this->head = $this->tail = $node;
}
else {
$this->insertBeforeChild($this->head, $node);
$this->head = $node;
}
return $this;
} | php | {
"resource": ""
} |
q1465 | ParentNode.appendChild | train | protected function appendChild(Node $node) {
if ($this->tail === NULL) {
$this->prependChild($node);
}
else {
$this->insertAfterChild($this->tail, $node);
$this->tail = $node;
}
return $this;
} | php | {
"resource": ""
} |
q1466 | ParentNode.addChild | train | public function addChild(Node $node, $property_name = NULL) {
$this->appendChild($node);
if ($property_name !== NULL) {
$this->{$property_name} = $node;
}
return $this;
} | php | {
"resource": ""
} |
q1467 | ParentNode.mergeNode | train | public function mergeNode(ParentNode $node) {
$child = $node->head;
while ($child) {
$next = $child->next;
$this->appendChild($child);
$child = $next;
}
foreach ($node->getChildProperties() as $name => $value) {
$this->{$name} = $value;
}
} | php | {
"resource": ""
} |
q1468 | ParentNode.insertBeforeChild | train | protected function insertBeforeChild(Node $child, Node $node) {
$this->childCount++;
$node->parent = $this;
if ($child->previous === NULL) {
$this->head = $node;
}
else {
$child->previous->next = $node;
}
$node->previous = $child->previous;
$node->next = $child;
$child->previous = $node;
return $this;
} | php | {
"resource": ""
} |
q1469 | ParentNode.insertAfterChild | train | protected function insertAfterChild(Node $child, Node $node) {
$this->childCount++;
$node->parent = $this;
if ($child->next === NULL) {
$this->tail = $node;
}
else {
$child->next->previous = $node;
}
$node->previous = $child;
$node->next = $child->next;
$child->next = $node;
return $this;
} | php | {
"resource": ""
} |
q1470 | ParentNode.removeChild | train | protected function removeChild(Node $child) {
$this->childCount--;
foreach ($this->getChildProperties() as $name => $value) {
if ($child === $value) {
$this->{$name} = NULL;
break;
}
}
if ($child->previous === NULL) {
$this->head = $child->next;
}
else {
$child->previous->next = $child->next;
}
if ($child->next === NULL) {
$this->tail = $child->previous;
}
else {
$child->next->previous = $child->previous;
}
$child->parent = NULL;
$child->previous = NULL;
$child->next = NULL;
return $this;
} | php | {
"resource": ""
} |
q1471 | ParentNode.replaceChild | train | protected function replaceChild(Node $child, Node $replacement) {
foreach ($this->getChildProperties() as $name => $value) {
if ($child === $value) {
$this->{$name} = $replacement;
break;
}
}
$replacement->parent = $this;
$replacement->previous = $child->previous;
$replacement->next = $child->next;
if ($child->previous === NULL) {
$this->head = $replacement;
}
else {
$child->previous->next = $replacement;
}
if ($child->next === NULL) {
$this->tail = $replacement;
}
else {
$child->next->previous = $replacement;
}
$child->parent = NULL;
$child->previous = NULL;
$child->next = NULL;
return $this;
} | php | {
"resource": ""
} |
q1472 | ParentNode.getTree | train | public function getTree() {
$children = array();
$properties = $this->getChildProperties();
$child = $this->head;
$i = 0;
while ($child) {
$key = array_search($child, $properties, TRUE);
if (!$key) {
$key = $i;
}
if ($child instanceof ParentNode) {
$children[$key] = $child->getTree();
}
else {
/** @var TokenNode $child */
$children[$key] = array($child->getTypeName() => $child->getText());
}
$child = $child->next;
$i++;
}
$class_name = get_class($this);
return array($class_name => $children);
} | php | {
"resource": ""
} |
q1473 | Environment.checkTypeAllowed | train | protected function checkTypeAllowed()
{
if (!in_array($this->type, static::$ALLOWED_TYPES)) {
throw new \Exception(
sprintf(
"`%s` is not a valid environment type. Expected one of: %s",
$this->type,
implode(', ', static::$ALLOWED_TYPES)
)
);
}
} | php | {
"resource": ""
} |
q1474 | ModuleHookCreationForm.verifyTemplates | train | public function verifyTemplates($value, ExecutionContextInterface $context)
{
$data = $context->getRoot()->getData();
if (!empty($data['templates']) && $data['method'] !== BaseHook::INJECT_TEMPLATE_METHOD_NAME) {
$context->addViolation(
$this->trans(
"If you use automatic insert templates, you should use the method %method%",
[
'%method%' => BaseHook::INJECT_TEMPLATE_METHOD_NAME
]
)
);
}
} | php | {
"resource": ""
} |
q1475 | Operators.getI18n | train | public static function getI18n(Translator $translator, $operator)
{
$ret = $operator;
switch ($operator) {
case self::INFERIOR:
$ret = $translator->trans(
'Less than',
[]
);
break;
case self::INFERIOR_OR_EQUAL:
$ret = $translator->trans(
'Less than or equals',
[]
);
break;
case self::EQUAL:
$ret = $translator->trans(
'Equal to',
[]
);
break;
case self::SUPERIOR_OR_EQUAL:
$ret = $translator->trans(
'Greater than or equals',
[]
);
break;
case self::SUPERIOR:
$ret = $translator->trans(
'Greater than',
[]
);
break;
case self::DIFFERENT:
$ret = $translator->trans(
'Not equal to',
[]
);
break;
case self::IN:
$ret = $translator->trans(
'In',
[]
);
break;
case self::OUT:
$ret = $translator->trans(
'Not in',
[]
);
break;
default:
}
return $ret;
} | php | {
"resource": ""
} |
q1476 | TheliaFormValidator.getErrorMessages | train | public function getErrorMessages(Form $form)
{
$errors = '';
foreach ($form->getErrors() as $key => $error) {
$errors .= $error->getMessage().', ';
}
/** @var Form $child */
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$fieldName = $child->getConfig()->getOption('label', null);
if (empty($fieldName)) {
$fieldName = $child->getName();
}
$errors .= sprintf("[%s] %s, ", $fieldName, $this->getErrorMessages($child));
}
}
return rtrim($errors, ', ');
} | php | {
"resource": ""
} |
q1477 | AbstractSeoCrudController.getUpdateSeoEvent | train | protected function getUpdateSeoEvent($formData)
{
$updateSeoEvent = new UpdateSeoEvent($formData['id']);
$updateSeoEvent
->setLocale($formData['locale'])
->setMetaTitle($formData['meta_title'])
->setMetaDescription($formData['meta_description'])
->setMetaKeywords($formData['meta_keywords'])
->setUrl($formData['url'])
;
// Create and dispatch the change event
return $updateSeoEvent;
} | php | {
"resource": ""
} |
q1478 | AbstractSeoCrudController.hydrateSeoForm | train | protected function hydrateSeoForm($object)
{
// The "SEO" tab form
$locale = $object->getLocale();
$data = array(
'id' => $object->getId(),
'locale' => $locale,
'url' => $object->getRewrittenUrl($locale),
'meta_title' => $object->getMetaTitle(),
'meta_description' => $object->getMetaDescription(),
'meta_keywords' => $object->getMetaKeywords()
);
$seoForm = $this->createForm(AdminForm::SEO, "form", $data);
$this->getParserContext()->addForm($seoForm);
// URL based on the language
$this->getParserContext()->set('url_language', $this->getUrlLanguage($locale));
} | php | {
"resource": ""
} |
q1479 | AbstractSeoCrudController.processUpdateSeoAction | train | public function processUpdateSeoAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, $this->getModuleCode(), AccessManager::UPDATE)) {
return $response;
}
// Error (Default: false)
$error_msg = false;
// Create the Form from the request
$updateSeoForm = $this->getUpdateSeoForm($this->getRequest());
// Pass the object id to the request
$this->getRequest()->attributes->set($this->objectName . '_id', $this->getRequest()->get('current_id'));
try {
// Check the form against constraints violations
$form = $this->validateForm($updateSeoForm, "POST");
// Get the form field values
$data = $form->getData();
// Create a new event object with the modified fields
$updateSeoEvent = $this->getUpdateSeoEvent($data);
// Dispatch Update SEO Event
$this->dispatch($this->updateSeoEventIdentifier, $updateSeoEvent);
// Execute additional Action
$response = $this->performAdditionalUpdateSeoAction($updateSeoEvent);
if ($response == null) {
// If we have to stay on the same page, do not redirect to the successUrl,
// just redirect to the edit page again.
if ($this->getRequest()->get('save_mode') == 'stay') {
return $this->redirectToEditionTemplate($this->getRequest());
}
// Redirect to the success URL
return $this->generateSuccessRedirect($updateSeoForm);
} else {
return $response;
}
} catch (FormValidationException $ex) {
// Form cannot be validated
$error_msg = $this->createStandardFormValidationErrorMessage($ex);
/*} catch (\Exception $ex) {
// Any other error
$error_msg = $ex->getMessage();*/
}
// Load object if exist
if (null !== $object = $this->getExistingObject()) {
// Hydrate the form abd pass it to the parser
$changeForm = $this->hydrateObjectForm($object);
// Pass it to the parser
$this->getParserContext()->addForm($changeForm);
}
if (false !== $error_msg) {
$this->setupFormErrorContext(
$this->getTranslator()->trans("%obj SEO modification", array('%obj' => $this->objectName)),
$error_msg,
$updateSeoForm,
$ex
);
// At this point, the form has errors, and should be redisplayed.
return $this->renderEditionTemplate();
}
} | php | {
"resource": ""
} |
q1480 | Module.checkDeactivation | train | private function checkDeactivation($module)
{
$moduleValidator = new ModuleValidator($module->getAbsoluteBaseDir());
$modules = $moduleValidator->getModulesDependOf();
if (\count($modules) > 0) {
$moduleList = implode(', ', array_column($modules, 'code'));
$message = (\count($modules) == 1)
? Translator::getInstance()->trans(
'%s has dependency to module %s. You have to deactivate this module before.'
)
: Translator::getInstance()->trans(
'%s have dependencies to module %s. You have to deactivate these modules before.'
);
throw new ModuleException(
sprintf($message, $moduleList, $moduleValidator->getModuleDefinition()->getCode())
);
}
return true;
} | php | {
"resource": ""
} |
q1481 | Module.recursiveActivation | train | public function recursiveActivation(ModuleToggleActivationEvent $event, $eventName, EventDispatcherInterface $dispatcher)
{
if (null !== $module = ModuleQuery::create()->findPk($event->getModuleId())) {
$moduleValidator = new ModuleValidator($module->getAbsoluteBaseDir());
$dependencies = $moduleValidator->getCurrentModuleDependencies();
foreach ($dependencies as $defMod) {
$submodule = ModuleQuery::create()
->findOneByCode($defMod["code"]);
if ($submodule && $submodule->getActivate() != BaseModule::IS_ACTIVATED) {
$subevent = new ModuleToggleActivationEvent($submodule->getId());
$subevent->setRecursive(true);
$dispatcher->dispatch(TheliaEvents::MODULE_TOGGLE_ACTIVATION, $subevent);
}
}
}
} | php | {
"resource": ""
} |
q1482 | Module.pay | train | public function pay(OrderPaymentEvent $event)
{
$order = $event->getOrder();
/* call pay method */
if (null === $paymentModule = ModuleQuery::create()->findPk($order->getPaymentModuleId())) {
throw new \RuntimeException(
Translator::getInstance()->trans(
"Failed to find a payment Module with ID=%mid for order ID=%oid",
[
"%mid" => $order->getPaymentModuleId(),
"%oid" => $order->getId()
]
)
);
}
$paymentModuleInstance = $paymentModule->getPaymentModuleInstance($this->container);
$response = $paymentModuleInstance->pay($order);
if (null !== $response && $response instanceof Response) {
$event->setResponse($response);
}
} | php | {
"resource": ""
} |
q1483 | MatchForTotalAmount.isMatching | train | public function isMatching()
{
$condition1 = $this->conditionValidator->variableOpComparison(
$this->facade->getCartTotalTaxPrice(),
$this->operators[self::CART_TOTAL],
$this->values[self::CART_TOTAL]
);
if ($condition1) {
$condition2 = $this->conditionValidator->variableOpComparison(
$this->facade->getCheckoutCurrency(),
$this->operators[self::CART_CURRENCY],
$this->values[self::CART_CURRENCY]
);
if ($condition2) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q1484 | FileUtil.findFiles | train | public static function findFiles($directory, $extensions = ['php']) {
if (!is_dir($directory)) {
return [];
}
$directory_iterator = new \RecursiveDirectoryIterator($directory);
$iterator = new \RecursiveIteratorIterator($directory_iterator);
$pattern = '/^.+\.(' . implode('|', $extensions) . ')$/i';
$regex = new \RegexIterator($iterator, $pattern, \RecursiveRegexIterator::GET_MATCH);
$files = [];
foreach ($regex as $name => $object) {
$files[] = $name;
}
return $files;
} | php | {
"resource": ""
} |
q1485 | CheckDatabaseConnection.exec | train | public function exec()
{
$dsn = "mysql:host=%s;port=%s";
try {
$this->connection = new \PDO(
sprintf($dsn, $this->host, $this->port),
$this->user,
$this->password
);
} catch (\PDOException $e) {
$this->validationMessages = 'Wrong connection information';
$this->isValid = false;
}
return $this->isValid;
} | php | {
"resource": ""
} |
q1486 | DocCommentTrait.getIndent | train | public function getIndent() {
/** @var ParentNode $this */
$whitespace_token = $this->previousToken();
if (empty($whitespace_token) || $whitespace_token->getType() !== T_WHITESPACE) {
return '';
}
$nl = FormatterFactory::getDefaultFormatter()->getConfig('nl');
$lines = explode($nl, $whitespace_token->getText());
$last_line = end($lines);
return $last_line;
} | php | {
"resource": ""
} |
q1487 | Coupon.createOrUpdate | train | public function createOrUpdate(
$code,
$title,
array $effects,
$type,
$isRemovingPostage,
$shortDescription,
$description,
$isEnabled,
$expirationDate,
$isAvailableOnSpecialOffers,
$isCumulative,
$maxUsage,
$defaultSerializedRule,
$locale,
$freeShippingForCountries,
$freeShippingForMethods,
$perCustomerUsageCount,
$startDate = null
) {
$con = Propel::getWriteConnection(CouponTableMap::DATABASE_NAME);
$con->beginTransaction();
try {
$this
->setCode($code)
->setType($type)
->setEffects($effects)
->setIsRemovingPostage($isRemovingPostage)
->setIsEnabled($isEnabled)
->setStartDate($startDate)
->setExpirationDate($expirationDate)
->setIsAvailableOnSpecialOffers($isAvailableOnSpecialOffers)
->setIsCumulative($isCumulative)
->setMaxUsage($maxUsage)
->setPerCustomerUsageCount($perCustomerUsageCount)
->setLocale($locale)
->setTitle($title)
->setShortDescription($shortDescription)
->setDescription($description)
;
// If no rule given, set default rule
if (null === $this->getSerializedConditions()) {
$this->setSerializedConditions($defaultSerializedRule);
}
$this->save();
// Update countries and modules relation for free shipping
CouponCountryQuery::create()->filterByCouponId($this->id)->delete();
CouponModuleQuery::create()->filterByCouponId($this->id)->delete();
foreach ($freeShippingForCountries as $countryId) {
if ($countryId <= 0) {
continue;
}
$couponCountry = new CouponCountry();
$couponCountry
->setCouponId($this->getId())
->setCountryId($countryId)
->save();
;
}
foreach ($freeShippingForMethods as $moduleId) {
if ($moduleId <= 0) {
continue;
}
$couponModule = new CouponModule();
$couponModule
->setCouponId($this->getId())
->setModuleId($moduleId)
->save()
;
}
$con->commit();
} catch (\Exception $ex) {
$con->rollback();
throw $ex;
}
} | php | {
"resource": ""
} |
q1488 | Coupon.createOrUpdateConditions | train | public function createOrUpdateConditions($serializableConditions, $locale)
{
$this->setSerializedConditions($serializableConditions);
// Set object language (i18n)
if (!\is_null($locale)) {
$this->setLocale($locale);
}
$this->save();
} | php | {
"resource": ""
} |
q1489 | Coupon.setAmount | train | public function setAmount($amount)
{
$effects = $this->unserializeEffects($this->getSerializedEffects());
$effects['amount'] = \floatval($amount);
$this->setEffects($effects);
return $this;
} | php | {
"resource": ""
} |
q1490 | Coupon.getUsagesLeft | train | public function getUsagesLeft($customerId = null)
{
$usageLeft = $this->getMaxUsage();
if ($this->getPerCustomerUsageCount()) {
// Get usage left for current customer. If the record is not found,
// it means that the customer has not yes used this coupon.
if (null !== $couponCustomerCount = CouponCustomerCountQuery::create()
->filterByCouponId($this->getId())
->filterByCustomerId($customerId)
->findOne()) {
// The coupon has already been used -> remove this customer's usage count
$usageLeft -= $couponCustomerCount->getCount();
}
}
return $usageLeft;
} | php | {
"resource": ""
} |
q1491 | FileController.processImage | train | public function processImage(
$fileBeingUploaded,
$parentId,
$parentType,
$objectType,
$validMimeTypes = array(),
$extBlackList = array()
) {
@trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 2.6. Please use the process method File present in the same class.', E_USER_DEPRECATED);
return $this->processFile($fileBeingUploaded, $parentId, $parentType, $objectType, $validMimeTypes, $extBlackList);
} | php | {
"resource": ""
} |
q1492 | FileController.saveImageAjaxAction | train | public function saveImageAjaxAction($parentId, $parentType)
{
$config = FileConfiguration::getImageConfig();
return $this->saveFileAjaxAction(
$parentId,
$parentType,
$config['objectType'],
$config['validMimeTypes'],
$config['extBlackList']
);
} | php | {
"resource": ""
} |
q1493 | FileController.saveDocumentAjaxAction | train | public function saveDocumentAjaxAction($parentId, $parentType)
{
$config = FileConfiguration::getDocumentConfig();
return $this->saveFileAjaxAction(
$parentId,
$parentType,
$config['objectType'],
$config['validMimeTypes'],
$config['extBlackList']
);
} | php | {
"resource": ""
} |
q1494 | FileController.viewImageAction | train | public function viewImageAction($imageId, $parentType)
{
if (null !== $response = $this->checkAuth($this->getAdminResources()->getResource($parentType, static::MODULE_RIGHT), array(), AccessManager::UPDATE)) {
return $response;
}
$fileManager = $this->getFileManager();
$imageModel = $fileManager->getModelInstance('image', $parentType);
$image = $imageModel->getQueryInstance()->findPk($imageId);
$redirectUrl = $image->getRedirectionUrl();
return $this->render('image-edit', array(
'imageId' => $imageId,
'imageType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $imageModel->getUpdateFormId(),
'breadcrumb' => $image->getBreadcrumb(
$this->getRouter($this->getCurrentRouter()),
$this->container,
'images',
$this->getCurrentEditionLocale()
)
));
} | php | {
"resource": ""
} |
q1495 | FileController.viewDocumentAction | train | public function viewDocumentAction($documentId, $parentType)
{
if (null !== $response = $this->checkAuth($this->getAdminResources()->getResource($parentType, static::MODULE_RIGHT), array(), AccessManager::UPDATE)) {
return $response;
}
$fileManager = $this->getFileManager();
$documentModel = $fileManager->getModelInstance('document', $parentType);
$document = $documentModel->getQueryInstance()->findPk($documentId);
$redirectUrl = $document->getRedirectionUrl();
return $this->render('document-edit', array(
'documentId' => $documentId,
'documentType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $documentModel->getUpdateFormId(),
'breadcrumb' => $document->getBreadcrumb(
$this->getRouter($this->getCurrentRouter()),
$this->container,
'documents',
$this->getCurrentEditionLocale()
)
));
} | php | {
"resource": ""
} |
q1496 | FileController.updateImageAction | train | public function updateImageAction($imageId, $parentType)
{
if (null !== $response = $this->checkAuth($this->getAdminResources()->getResource($parentType, static::MODULE_RIGHT), array(), AccessManager::UPDATE)) {
return $response;
}
$imageInstance = $this->updateFileAction($imageId, $parentType, 'image', TheliaEvents::IMAGE_UPDATE);
if ($imageInstance instanceof \Symfony\Component\HttpFoundation\Response) {
return $imageInstance;
} else {
return $this->render('image-edit', array(
'imageId' => $imageId,
'imageType' => $parentType,
'redirectUrl' => $imageInstance->getRedirectionUrl(),
'formId' => $imageInstance->getUpdateFormId()
));
}
} | php | {
"resource": ""
} |
q1497 | FileController.updateDocumentAction | train | public function updateDocumentAction($documentId, $parentType)
{
if (null !== $response = $this->checkAuth($this->getAdminResources()->getResource($parentType, static::MODULE_RIGHT), array(), AccessManager::UPDATE)) {
return $response;
}
$documentInstance = $this->updateFileAction($documentId, $parentType, 'document', TheliaEvents::DOCUMENT_UPDATE);
if ($documentInstance instanceof \Symfony\Component\HttpFoundation\Response) {
return $documentInstance;
} else {
return $this->render('document-edit', array(
'documentId' => $documentId,
'documentType' => $parentType,
'redirectUrl' => $documentInstance->getRedirectionUrl(),
'formId' => $documentInstance->getUpdateFormId()
));
}
} | php | {
"resource": ""
} |
q1498 | FileController.deleteFileAction | train | public function deleteFileAction($fileId, $parentType, $objectType, $eventName)
{
$message = null;
$this->checkAuth($this->getAdminResources()->getResource($parentType, static::MODULE_RIGHT), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest();
$fileManager = $this->getFileManager();
$modelInstance = $fileManager->getModelInstance($objectType, $parentType);
$model = $modelInstance->getQueryInstance()->findPk($fileId);
if ($model == null) {
return $this->pageNotFound();
}
// Feed event
$fileDeleteEvent = new FileDeleteEvent($model);
// Dispatch Event to the Action
try {
$this->dispatch($eventName, $fileDeleteEvent);
$this->adminLogAppend(
$this->getAdminResources()->getResource($parentType, static::MODULE_RIGHT),
AccessManager::UPDATE,
$this->getTranslator()->trans(
'Deleting %obj% for %id% with parent id %parentId%',
array(
'%obj%' => $objectType,
'%id%' => $fileDeleteEvent->getFileToDelete()->getId(),
'%parentId%' => $fileDeleteEvent->getFileToDelete()->getParentId(),
)
),
$fileDeleteEvent->getFileToDelete()->getId()
);
} catch (\Exception $e) {
$message = $this->getTranslator()->trans(
'Fail to delete %obj% for %id% with parent id %parentId% (Exception : %e%)',
array(
'%obj%' => $objectType,
'%id%' => $fileDeleteEvent->getFileToDelete()->getId(),
'%parentId%' => $fileDeleteEvent->getFileToDelete()->getParentId(),
'%e%' => $e->getMessage()
)
);
$this->adminLogAppend(
$this->getAdminResources()->getResource($parentType, static::MODULE_RIGHT),
AccessManager::UPDATE,
$message,
$fileDeleteEvent->getFileToDelete()->getId()
);
}
if (null === $message) {
$message = $this->getTranslator()->trans(
'%obj%s deleted successfully',
['%obj%' => ucfirst($objectType)],
'image'
);
}
return new Response($message);
} | php | {
"resource": ""
} |
q1499 | SlackGateway.formatMessage | train | public function formatMessage($string)
{
$string = str_replace('&', '&', $string);
$string = str_replace('<', '<', $string);
$string = str_replace('>', '>', $string);
return $string;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.