_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1700 | OrderStatus.isPaid | train | public function isPaid($exact = true)
{
return $this->hasStatusHelper(
$exact ?
OrderStatus::CODE_PAID :
[ OrderStatus::CODE_PAID, OrderStatus::CODE_PROCESSING, OrderStatus::CODE_SENT ]
);
} | php | {
"resource": ""
} |
q1701 | Availability.checkAvailability | train | private function checkAvailability() {
// Get the boldgrid_available transient.
$available = get_site_transient( 'boldgrid_available' );
// No transient was found.
$wp_http = new WP_Http();
$url = $this->getUrl();
// Check that calling server is not blocked locally.
if ( $wp_http->block_request( $url ) === false ) {
$available = 1;
}
// Update the boldgrid_available transient.
set_site_transient( 'boldgrid_available', ( int ) $available, 2 * MINUTE_IN_SECONDS );
return $available;
} | php | {
"resource": ""
} |
q1702 | TreeSitesController.getTreePagesByPageIdAction | train | public function getTreePagesByPageIdAction()
{
// Get the node id requested, or use default root -1
$idPage = $this->params()->fromQuery('nodeId', -1);
$this->getEventManager()->trigger('melis_cms_tree_get_pages_start', $this, array('idPage' => $idPage));
if ($idPage == -1)
$rootPages = $this->getRootForUser();
else
$rootPages = array($idPage);
$final = $this->getPagesDatas($rootPages);
$triggerResponse = $this->getEventManager()->trigger('melis_cms_tree_get_pages_end', $this, array('parentId' => $idPage, 'request' => $final));
$response = null;
if(isset($triggerResponse[0]) && !empty($triggerResponse[0]))
$response = $this->formatTreeResponse($triggerResponse[0]);
else
$response = $this->formatTreeResponse($final);
return $response;
} | php | {
"resource": ""
} |
q1703 | TreeSitesController.getTreePagesForRightsManagementAction | train | public function getTreePagesForRightsManagementAction()
{
$idPage = $this->params()->fromQuery('nodeId', -1);
if ($idPage == MelisCmsRightsService::MELISCMS_PREFIX_PAGES . '_root')
$idPage = -1;
else
$idPage = str_replace(MelisCmsRightsService::MELISCMS_PREFIX_PAGES . '_', '', $idPage);
$rootPages = array($idPage);
$final = $this->getPagesDatas($rootPages);
return $this->formatTreeResponse($final, true);
} | php | {
"resource": ""
} |
q1704 | TreeSitesController.cleanBreadcrumb | train | private function cleanBreadcrumb($breadcrumb)
{
$newArray = array();
if (!empty($breadcrumb))
foreach ($breadcrumb as $page)
{
if (!empty($page->tree_page_id))
array_push($newArray, $page->tree_page_id);
}
return $newArray;
} | php | {
"resource": ""
} |
q1705 | TreeSitesController.getRootForUser | train | private function getRootForUser()
{
$melisEngineTree = $this->serviceLocator->get('MelisEngineTree');
$melisCoreAuth = $this->getServiceLocator()->get('MelisCoreAuth');
$melisCmsRights = $this->getServiceLocator()->get('MelisCmsRights');
// Get the rights of the user
$xmlRights = $melisCoreAuth->getAuthRights();
$rightsObj = simplexml_load_string($xmlRights);
$rootPages = array();
$breadcrumbRightPages = array();
// Loop into page ids of the rights to determine what are the root pages
// Deleting possible doublons with parent pages selected and also children pages
$sectionId = MelisCmsRightsService::MELISCMS_PREFIX_PAGES;
if (empty($rightsObj->$sectionId))
return array();
foreach ($rightsObj->$sectionId->id as $rightsPageId)
{
$rightsPageId = (int)$rightsPageId;
// No need to continue, -1 is root, there's a full access
if ($rightsPageId == -1)
return array(-1);
// Get the breadcrumb of the page and reformat it to a more simple array
$breadcrumb = $melisEngineTree->getPageBreadcrumb($rightsPageId, 0, true);
$breadcrumb = $this->cleanBreadcrumb($breadcrumb);
/**
* Looping on the temporary array holding pages
* Making intersection to compare between the one checked and those already saved
* If the one checked is equal with the intersection, it means the one checked contains
* already the older one, the page is on top, then we will only keep this one and delete
* the old one
* Otherwise we save
*/
$add = true;
for ($i = 0; $i < count($breadcrumbRightPages); $i++)
{
$result = array_intersect($breadcrumb, $breadcrumbRightPages[$i]);
if ($result === $breadcrumb)
{
$add = false;
$breadcrumbRightPages[$i] = $breadcrumb;
break;
}
if ($result === $breadcrumbRightPages[$i])
{
$add = false;
break;
}
}
if ($add)
$breadcrumbRightPages[count($breadcrumbRightPages)] = $breadcrumb;
}
/**
* Reformat final result to a simple array with the ids of pages
*/
foreach ($breadcrumbRightPages as $breadcrumbPage)
{
if (count($breadcrumbPage) > 0)
array_push($rootPages, $breadcrumbPage[count($breadcrumbPage) - 1]);
}
return $rootPages;
} | php | {
"resource": ""
} |
q1706 | TreeSitesController.getPageIdBreadcrumbAction | train | public function getPageIdBreadcrumbAction()
{
$idPage = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', ''));
$idPage = ($idPage == 'root')? -1 : $idPage;
$includeSelf = $this->params()->fromRoute('includeSelf', $this->params()->fromQuery('includeSelf', ''));
$melisEngineTree = $this->serviceLocator->get('MelisEngineTree');
$breadcrumb = $melisEngineTree->getPageBreadcrumb($idPage, 0, true);
$pageFatherId = $idPage;
$jsonresult = array();
if($includeSelf){
array_unshift($jsonresult, $pageFatherId);
}
while($pageFatherId != NULL){
$page = $melisEngineTree->getPageFather($pageFatherId, 'saved')->current();
$pageFatherId = !empty($page)? $page->tree_father_page_id : NULL;
if(!empty($pageFatherId)){
array_unshift($jsonresult, $pageFatherId);
}
}
return new JsonModel($jsonresult);
} | php | {
"resource": ""
} |
q1707 | TreeSitesController.canEditPagesAction | train | public function canEditPagesAction()
{
$melisCoreAuth = $this->getServiceLocator()->get('MelisCoreAuth');
$xmlRights = $melisCoreAuth->getAuthRights();
$rightsObj = simplexml_load_string($xmlRights);
$sectionId = MelisCmsRightsService::MELISCMS_PREFIX_PAGES;
if (empty($rightsObj->$sectionId->id))
$edit = 0;
else
$edit = 1;
$result = array(
'success' => 1,
'edit' => $edit
);
return new JsonModel($result);
} | php | {
"resource": ""
} |
q1708 | CouponManager.getDiscount | train | public function getDiscount()
{
$discount = 0.00;
$coupons = $this->facade->getCurrentCoupons();
if (\count($coupons) > 0) {
$couponsKept = $this->sortCoupons($coupons);
$discount = $this->getEffect($couponsKept);
// Just In Case test
$checkoutTotalPrice = $this->facade->getCartTotalTaxPrice();
if ($discount >= $checkoutTotalPrice) {
$discount = $checkoutTotalPrice;
}
}
return $discount;
} | php | {
"resource": ""
} |
q1709 | CouponManager.isCouponRemovingPostage | train | public function isCouponRemovingPostage(Order $order)
{
$coupons = $this->facade->getCurrentCoupons();
if (\count($coupons) == 0) {
return false;
}
$couponsKept = $this->sortCoupons($coupons);
/** @var CouponInterface $coupon */
foreach ($couponsKept as $coupon) {
if ($coupon->isRemovingPostage()) {
// Check if delivery country is on the list of countries for which delivery is free
// If the list is empty, the shipping is free for all countries.
$couponCountries = $coupon->getFreeShippingForCountries();
if (! $couponCountries->isEmpty()) {
if (null === $deliveryAddress = AddressQuery::create()->findPk($order->getChoosenDeliveryAddress())) {
continue;
}
$countryValid = false;
$deliveryCountryId = $deliveryAddress->getCountryId();
/** @var CouponCountry $couponCountry */
foreach ($couponCountries as $couponCountry) {
if ($deliveryCountryId == $couponCountry->getCountryId()) {
$countryValid = true;
break;
}
}
if (! $countryValid) {
continue;
}
}
// Check if shipping method is on the list of methods for which delivery is free
// If the list is empty, the shipping is free for all methods.
$couponModules = $coupon->getFreeShippingForModules();
if (! $couponModules->isEmpty()) {
$moduleValid = false;
$shippingModuleId = $order->getDeliveryModuleId();
/** @var CouponModule $couponModule */
foreach ($couponModules as $couponModule) {
if ($shippingModuleId == $couponModule->getModuleId()) {
$moduleValid = true;
break;
}
}
if (! $moduleValid) {
continue;
}
}
// All conditions are met, the shipping is free !
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q1710 | CouponManager.sortCoupons | train | protected function sortCoupons(array $coupons)
{
$couponsKept = array();
/** @var CouponInterface $coupon */
foreach ($coupons as $coupon) {
if ($coupon && !$coupon->isExpired()) {
if ($coupon->isCumulative()) {
if (isset($couponsKept[0])) {
/** @var CouponInterface $previousCoupon */
$previousCoupon = $couponsKept[0];
if ($previousCoupon->isCumulative()) {
// Add Coupon
$couponsKept[] = $coupon;
} else {
// Reset Coupons, add last
$couponsKept = array($coupon);
}
} else {
// Reset Coupons, add last
$couponsKept = array($coupon);
}
} else {
// Reset Coupons, add last
$couponsKept = array($coupon);
}
}
}
$coupons = $couponsKept;
$couponsKept = array();
/** @var CouponInterface $coupon */
foreach ($coupons as $coupon) {
try {
if ($coupon->isMatching()) {
$couponsKept[] = $coupon;
}
} catch (UnmatchableConditionException $e) {
// ignore unmatchable coupon
continue;
}
}
return $couponsKept;
} | php | {
"resource": ""
} |
q1711 | CouponManager.getEffect | train | protected function getEffect(array $coupons)
{
$discount = 0.00;
/** @var CouponInterface $coupon */
foreach ($coupons as $coupon) {
$discount += $coupon->exec($this->facade);
}
return $discount;
} | php | {
"resource": ""
} |
q1712 | CouponManager.clear | train | public function clear()
{
$coupons = $this->facade->getCurrentCoupons();
/** @var CouponInterface $coupon */
foreach ($coupons as $coupon) {
$coupon->clear();
}
} | php | {
"resource": ""
} |
q1713 | CouponManager.decrementQuantity | train | public function decrementQuantity(Coupon $coupon, $customerId = null)
{
if ($coupon->isUsageUnlimited()) {
return true;
} else {
try {
$usageLeft = $coupon->getUsagesLeft($customerId);
if ($usageLeft > 0) {
// If the coupon usage is per user, add an entry to coupon customer usage count table
if ($coupon->getPerCustomerUsageCount()) {
if (null == $customerId) {
throw new \LogicException("Customer should not be null at this time.");
}
$ccc = CouponCustomerCountQuery::create()
->filterByCouponId($coupon->getId())
->filterByCustomerId($customerId)
->findOne()
;
if ($ccc === null) {
$ccc = new CouponCustomerCount();
$ccc
->setCustomerId($customerId)
->setCouponId($coupon->getId())
->setCount(0);
}
$newCount = 1 + $ccc->getCount();
$ccc
->setCount($newCount)
->save()
;
return $usageLeft - $newCount;
} else {
$coupon->setMaxUsage(--$usageLeft);
$coupon->save();
return $usageLeft;
}
}
} catch (\Exception $ex) {
// Just log the problem.
Tlog::getInstance()->addError(sprintf("Failed to decrement coupon %s: %s", $coupon->getCode(), $ex->getMessage()));
}
}
return false;
} | php | {
"resource": ""
} |
q1714 | AddressFormat.format | train | public function format(
AddressInterface $address,
$locale = null,
$html = true,
$htmlTag = "p",
$htmlAttributes = []
) {
$locale = $this->normalizeLocale($locale);
$addressFormatRepository = new AddressFormatRepository();
$countryRepository = new CountryRepository();
$subdivisionRepository = new SubdivisionRepository();
$formatter = new DefaultFormatter(
$addressFormatRepository,
$countryRepository,
$subdivisionRepository,
$locale
);
$formatter->setOption('html', $html);
$formatter->setOption('html_tag', $htmlTag);
$formatter->setOption('html_attributes', $htmlAttributes);
$addressFormatted = $formatter->format($address);
return $addressFormatted;
} | php | {
"resource": ""
} |
q1715 | AddressFormat.postalLabelFormat | train | public function postalLabelFormat(AddressInterface $address, $locale = null, $originCountry = null, $options = [])
{
$locale = $this->normalizeLocale($locale);
$addressFormatRepository = new AddressFormatRepository();
$countryRepository = new CountryRepository();
$subdivisionRepository = new SubdivisionRepository();
if (null === $originCountry) {
$countryId = Country::getShopLocation();
if (null === $country = CountryQuery::create()->findPk($countryId)) {
$country = Country::getDefaultCountry();
}
$originCountry = $country->getIsoalpha2();
}
$formatter = new PostalLabelFormatter(
$addressFormatRepository,
$countryRepository,
$subdivisionRepository,
$originCountry,
$locale,
$options
);
$addressFormatted = $formatter->format($address);
return $addressFormatted;
} | php | {
"resource": ""
} |
q1716 | BaseController.getTranslator | train | public function getTranslator()
{
if (null === $this->translator) {
$this->translator = $this->container->get('thelia.translator');
}
return $this->translator;
} | php | {
"resource": ""
} |
q1717 | BaseController.retrieveFormBasedUrl | train | protected function retrieveFormBasedUrl($parameterName, BaseForm $form = null)
{
$url = null;
if ($form != null) {
$url = $form->getFormDefinedUrl($parameterName);
} else {
$url = $this->container->get('request_stack')->getCurrentRequest()->get($parameterName);
}
return $url;
} | php | {
"resource": ""
} |
q1718 | BaseController.getRoute | train | protected function getRoute($routeId, $parameters = array(), $referenceType = Router::ABSOLUTE_URL)
{
return $this->getRouteFromRouter(
$this->getCurrentRouter(),
$routeId,
$parameters,
$referenceType
);
} | php | {
"resource": ""
} |
q1719 | BaseController.getRouteFromRouter | train | protected function getRouteFromRouter(
$routerName,
$routeId,
$parameters = array(),
$referenceType = Router::ABSOLUTE_URL
) {
/** @var Router $router */
$router = $this->getRouter($routerName);
if ($router == null) {
throw new \InvalidArgumentException(sprintf("Router '%s' does not exists.", $routerName));
}
return $router->generate($routeId, $parameters, $referenceType);
} | php | {
"resource": ""
} |
q1720 | BaseController.checkXmlHttpRequest | train | protected function checkXmlHttpRequest()
{
if (false === $this->container->get('request_stack')->getCurrentRequest()->isXmlHttpRequest() && false === $this->isDebug()) {
$this->accessDenied();
}
} | php | {
"resource": ""
} |
q1721 | TemplateController.performAdditionalDeleteAction | train | protected function performAdditionalDeleteAction($deleteEvent)
{
if ($deleteEvent->getProductCount() > 0) {
$this->getParserContext()->setGeneralError(
$this->getTranslator()->trans(
"This template is in use in some of your products, and cannot be deleted. Delete it from all your products and try again."
)
);
return $this->renderList();
}
// Normal delete processing
return null;
} | php | {
"resource": ""
} |
q1722 | AdminLog.append | train | public static function append(
$resource,
$action,
$message,
Request $request,
UserInterface $adminUser = null,
$withRequestContent = true,
$resourceId = null
) {
$log = new AdminLog();
$log
->setAdminLogin($adminUser !== null ? $adminUser->getUsername() : '<no login>')
->setAdminFirstname($adminUser !== null && $adminUser instanceof Admin ? $adminUser->getFirstname() : '<no first name>')
->setAdminLastname($adminUser !== null && $adminUser instanceof Admin ? $adminUser->getLastname() : '<no last name>')
->setResource($resource)
->setResourceId($resourceId)
->setAction($action)
->setMessage($message)
->setRequest($request->toString($withRequestContent));
try {
$log->save();
} catch (\Exception $ex) {
Tlog::getInstance()->err("Failed to insert new entry in AdminLog: {ex}", array('ex' => $ex));
}
} | php | {
"resource": ""
} |
q1723 | Formatter.spaceBefore | train | protected function spaceBefore(Node $node) {
$prev = $node->previousToken();
if ($prev instanceof WhitespaceNode) {
$prev->setText(' ');
}
else {
$node->before(Token::space());
}
} | php | {
"resource": ""
} |
q1724 | Formatter.spaceAfter | train | protected function spaceAfter(Node $node) {
$next = $node->nextToken();
if ($next instanceof WhitespaceNode) {
$next->setText(' ');
}
else {
$node->after(Token::space());
}
} | php | {
"resource": ""
} |
q1725 | Formatter.removeSpaceBefore | train | protected function removeSpaceBefore(Node $node) {
$prev = $node->previousToken();
if ($prev instanceof WhitespaceNode) {
$prev->remove();
}
} | php | {
"resource": ""
} |
q1726 | Formatter.removeSpaceAfter | train | protected function removeSpaceAfter(Node $node) {
$next = $node->nextToken();
if ($next instanceof WhitespaceNode) {
$next->remove();
}
} | php | {
"resource": ""
} |
q1727 | Formatter.newlineBefore | train | protected function newlineBefore(Node $node, $close = FALSE) {
$prev = $node->previousToken();
if ($prev instanceof WhitespaceNode) {
$prev_ws = $prev->previousToken();
if ($prev_ws instanceof CommentNode && $prev_ws->isLineComment() && $prev->getNewlineCount() === 0) {
$prev->setText($this->getIndent($close));
}
else {
$prev->setText($this->getNewlineIndent($prev, $close));
}
}
else {
if ($prev instanceof CommentNode && $prev->isLineComment()) {
if ($this->indentLevel > 0) {
$node->before(Token::whitespace($this->getIndent($close)));
}
}
else {
$node->before(Token::whitespace($this->getNewlineIndent(NULL, $close)));
}
}
} | php | {
"resource": ""
} |
q1728 | Formatter.newlineAfter | train | protected function newlineAfter(Node $node) {
$next = $node->nextToken();
if ($next instanceof WhitespaceNode) {
$next->setText($this->getNewlineIndent($next));
}
else {
$node->after(Token::whitespace($this->getNewlineIndent()));
}
} | php | {
"resource": ""
} |
q1729 | Formatter.handleBuiltinConstantNode | train | protected function handleBuiltinConstantNode(ConstantNode $node) {
$to_upper = $this->config['boolean_null_upper'];
if ($to_upper) {
$node->toUpperCase();
}
else {
$node->toLowerCase();
}
} | php | {
"resource": ""
} |
q1730 | Formatter.encloseBlock | train | protected function encloseBlock($node) {
if ($node && !($node instanceof StatementBlockNode)) {
$blockNode = new StatementBlockNode();
$blockNode->append([Token::openBrace(), clone $node, Token::closeBrace()]);
$node->replaceWith($blockNode);
}
} | php | {
"resource": ""
} |
q1731 | Formatter.handleParens | train | protected function handleParens($node) {
$open_paren = $node->getOpenParen();
$this->removeSpaceAfter($open_paren);
$this->spaceBefore($open_paren);
$close_paren = $node->getCloseParen();
$this->removeSpaceBefore($close_paren);
} | php | {
"resource": ""
} |
q1732 | Formatter.handleControlStructure | train | protected function handleControlStructure($node) {
$this->handleParens($node);
$colons = $node->children(Filter::isTokenType(':'));
foreach ($colons as $colon) {
$this->removeSpaceBefore($colon);
}
if ($colons->isNotEmpty()) {
$this->newlineBefore($node->lastChild()->previous());
}
} | php | {
"resource": ""
} |
q1733 | Formatter.isDeclaration | train | protected function isDeclaration(ParentNode $node) {
return $node instanceof FunctionDeclarationNode ||
$node instanceof SingleInheritanceNode ||
$node instanceof InterfaceNode ||
$node instanceof ClassMethodNode ||
$node instanceof InterfaceMethodNode;
} | php | {
"resource": ""
} |
q1734 | Formatter.calculateColumnPosition | train | protected function calculateColumnPosition(Node $node) {
// Add tokens until have whitespace containing newline.
$column_position = 1;
$start_token = $node instanceof ParentNode ? $node->firstToken() : $node;
$token = $start_token;
while ($token = $token->previousToken()) {
if ($token instanceof WhitespaceNode && $token->getNewlineCount() > 0) {
$lines = explode($this->config['nl'], $token->getText());
$last_line = end($lines);
$column_position += strlen($last_line);
break;
}
$column_position += strlen($token->getText());
}
return $column_position;
} | php | {
"resource": ""
} |
q1735 | CouponCreateOrUpdateEvent.setEffects | train | public function setEffects(array $effects)
{
// Amount is now optionnal.
$this->amount = isset($effects['amount']) ? $effects['amount'] : 0;
$this->effects = $effects;
} | php | {
"resource": ""
} |
q1736 | TopicEvent.toMessage | train | public function toMessage()
{
return array_merge($this->attributes, [
'topic' => $this->topic,
'event' => $this->name,
'version' => $this->version,
]);
} | php | {
"resource": ""
} |
q1737 | TopicEvent.matches | train | public function matches($expr)
{
$params = self::parseEventExpr($expr);
if ($params['topic'] === '*') {
return true;
} elseif ($this->topic !== $params['topic']) {
return false;
}
if ($params['event'] === '*') {
return true;
} elseif ($this->name !== $params['event']) {
return false;
}
if ($params['version'] === '*') {
return true;
} else {
return Semver::satisfies($this->version, $params['version']);
}
} | php | {
"resource": ""
} |
q1738 | OperatorFactory.createOperator | train | public static function createOperator($token_type, $static_only = FALSE) {
if (array_key_exists($token_type, self::$operators)) {
list($assoc, $precedence, $static, $binary_class_name, $unary_class_name) = self::$operators[$token_type];
if ($static_only && !$static) {
return NULL;
}
$operator = new Operator();
$operator->type = $token_type;
$operator->associativity = $assoc;
$operator->precedence = $precedence;
$operator->hasBinaryMode = $binary_class_name !== NULL;
$operator->hasUnaryMode = $unary_class_name !== NULL;
$operator->binaryClassName = $binary_class_name;
$operator->unaryClassName = $unary_class_name;
return $operator;
}
return NULL;
} | php | {
"resource": ""
} |
q1739 | Plugin.getPluginFile | train | public static function getPluginFile( $slug ) {
// Load plugin.php if not already included by core.
if ( ! function_exists( 'get_plugins' ) ) {
require ABSPATH . '/wp-admin/includes/plugin.php';
}
$plugins = get_plugins();
foreach ( $plugins as $file => $info ) {
// Get the basename of the plugin.
$basename = dirname( plugin_basename( $file ) );
if ( $basename === $slug ) {
return $file;
}
}
return null;
} | php | {
"resource": ""
} |
q1740 | CouponFactory.buildCouponFromCode | train | public function buildCouponFromCode($couponCode)
{
/** @var Coupon $couponModel */
$couponModel = $this->facade->findOneCouponByCode($couponCode);
if ($couponModel === null) {
return false;
}
// check if coupon is enabled
if (!$couponModel->getIsEnabled()) {
throw new InactiveCouponException($couponCode);
}
$nowDateTime = new \DateTime();
// Check coupon start date
if ($couponModel->getStartDate() !== null && $couponModel->getStartDate() > $nowDateTime) {
throw new CouponNotReleaseException($couponCode);
}
// Check coupon expiration date
if ($couponModel->getExpirationDate() < $nowDateTime) {
throw new CouponExpiredException($couponCode);
}
// Check coupon usage count
if (! $couponModel->isUsageUnlimited()) {
if (null === $customer = $this->facade->getCustomer()) {
throw new UnmatchableConditionException($couponCode);
}
if ($couponModel->getUsagesLeft($customer->getId()) <= 0) {
throw new CouponNoUsageLeftException($couponCode);
}
}
/** @var CouponInterface $couponInterface */
$couponInterface = $this->buildCouponFromModel($couponModel);
if ($couponInterface && $couponInterface->getConditions()->count() == 0) {
throw new InvalidConditionException(
\get_class($couponInterface)
);
}
return $couponInterface;
} | php | {
"resource": ""
} |
q1741 | CouponFactory.buildCouponFromModel | train | public function buildCouponFromModel(Coupon $model)
{
$isCumulative = ($model->getIsCumulative() == 1 ? true : false);
$isRemovingPostage = ($model->getIsRemovingPostage() == 1 ? true : false);
if (!$this->container->has($model->getType())) {
return false;
}
/** @var CouponInterface $couponManager*/
$couponManager = $this->container->get($model->getType());
$couponManager->set(
$this->facade,
$model->getCode(),
$model->getTitle(),
$model->getShortDescription(),
$model->getDescription(),
$model->getEffects(),
$isCumulative,
$isRemovingPostage,
$model->getIsAvailableOnSpecialOffers(),
$model->getIsEnabled(),
$model->getMaxUsage(),
$model->getExpirationDate(),
$model->getFreeShippingForCountries(),
$model->getFreeShippingForModules(),
$model->getPerCustomerUsageCount()
);
/** @var ConditionFactory $conditionFactory */
$conditionFactory = $this->container->get('thelia.condition.factory');
$conditions = $conditionFactory->unserializeConditionCollection(
$model->getSerializedConditions()
);
$couponManager->setConditions($conditions);
return clone $couponManager;
} | php | {
"resource": ""
} |
q1742 | TwilioGateway.mapResponse | train | protected function mapResponse($success, array $response)
{
return (new Response())->setRaw($response)->map([
'success' => $success,
'message' => $success ? 'Message sent' : $response['message'],
]);
} | php | {
"resource": ""
} |
q1743 | Api.setConfig | train | public function setConfig(array $config)
{
try {
$this->config = $this
->getConfigResolver()
->resolve($config);
} catch (ExceptionInterface $e) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
} | php | {
"resource": ""
} |
q1744 | Api.createPaymentForm | train | public function createPaymentForm(array $data)
{
$this->ensureApiIsConfigured();
try {
$data = $this
->getRequestOptionsResolver()
->resolve($data);
} catch (ExceptionInterface $e) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
$fields = [
'TPE' => $this->config['tpe'],
'date' => $data['date'],
'montant' => $data['amount'] . $data['currency'],
'reference' => $data['reference'],
'texte-libre' => $data['comment'],
'version' => static::VERSION,
'lgue' => $data['locale'],
'societe' => $this->config['company'],
'mail' => $data['email'],
];
$macData = array_values($fields);
$fields['texte-libre'] = $this->htmlEncode($data['comment']);
if (!empty($data['schedule'])) {
$macData[] = $fields['nbrech'] = count($data['schedule']);
$count = 0;
foreach ($data['schedule'] as $datum) {
$count++;
$macData[] = $fields['dateech' . $count] = $datum['date'];
$macData[] = $fields['montantech' . $count] = $datum['amount'] . $data['currency'];
}
// Fills empty schedule
for ($i = 2 * $count + 10; $i < 18; $i++) {
$macData[] = null;
}
$options = [];
foreach ($data['options'] as $key => $value) {
$options = "$key=$value";
}
$macData[] = $fields['options'] = implode('&', $options);
}
$fields['MAC'] = $this->computeMac($macData);
$fields['url_retour'] = $data['return_url'];
$fields['url_retour_ok'] = $data['success_url'];
$fields['url_retour_err'] = $data['failure_url'];
return [
'action' => $this->getEndpointUrl(static::TYPE_PAYMENT),
'method' => 'POST',
'fields' => $fields,
];
} | php | {
"resource": ""
} |
q1745 | Api.checkPaymentResponse | train | public function checkPaymentResponse(array $data)
{
if (!isset($data['MAC'])) {
return false;
}
$data = array_replace([
'date' => null,
'montant' => null,
'reference' => null,
'texte-libre' => null,
'code-retour' => null,
'cvx' => null,
'vld' => null,
'brand' => null,
'status3ds' => null,
'numauto' => null,
'motifrefus' => null,
'originecb' => null,
'bincb' => null,
'hpancb' => null,
'ipclient' => null,
'originetr' => null,
'veres' => null,
'pares' => null,
], $data);
$macData = [
$this->config['tpe'],
$data["date"],
$data['montant'],
$data['reference'],
$data['texte-libre'],
static::VERSION,
$data['code-retour'],
$data['cvx'],
$data['vld'],
$data['brand'],
$data['status3ds'],
$data['numauto'],
$data['motifrefus'],
$data['originecb'],
$data['bincb'],
$data['hpancb'],
$data['ipclient'],
$data['originetr'],
$data['veres'],
$data['pares'],
null,
];
return strtolower($data['MAC']) === $this->computeMac($macData);
} | php | {
"resource": ""
} |
q1746 | Api.getMacKey | train | public function getMacKey()
{
$key = $this->config['key'];
$hexStrKey = substr($key, 0, 38);
$hexFinal = "" . substr($key, 38, 2) . "00";
$cca0 = ord($hexFinal);
if ($cca0 > 70 && $cca0 < 97) {
$hexStrKey .= chr($cca0 - 23) . substr($hexFinal, 1, 1);
} else {
if (substr($hexFinal, 1, 1) == "M") {
$hexStrKey .= substr($hexFinal, 0, 1) . "0";
} else {
$hexStrKey .= substr($hexFinal, 0, 2);
}
}
return pack("H*", $hexStrKey);
} | php | {
"resource": ""
} |
q1747 | Api.htmlEncode | train | private function htmlEncode($data)
{
if (empty($data)) {
return null;
}
$safeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890._-";
$result = "";
for ($i = 0; $i < strlen($data); $i++) {
if (strstr($safeChars, $data[$i])) {
$result .= $data[$i];
} else if ("7F" >= $var = bin2hex(substr($data, $i, 1))) {
$result .= "&#x" . $var . ";";
} else {
$result .= $data[$i];
}
}
return $result;
} | php | {
"resource": ""
} |
q1748 | ArrayLookupNode.create | train | public static function create(ExpressionNode $array, ExpressionNode $key) {
$node = new static();
/** @var Node $array */
$node->addChild($array, 'array');
$node->addChild(Token::openBracket());
/** @var Node $key */
$node->addChild($key, 'key');
$node->addChild(Token::closeBracket());
return $node;
} | php | {
"resource": ""
} |
q1749 | ArrayLookupNode.getKey | train | public function getKey($index = 0) {
$keys = $this->getKeys();
if (!is_integer($index)) {
throw new \InvalidArgumentException();
}
if ($index < 0 || $index >= count($keys)) {
throw new \OutOfBoundsException();
}
return $keys[$index];
} | php | {
"resource": ""
} |
q1750 | AddClientAssets.addLocales | train | public function addLocales(ConfigureLocales $event)
{
foreach (new DirectoryIterator(__DIR__.'/../../locale') as $file) {
if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) {
$event->locales->addTranslations($file->getBasename('.'.$file->getExtension()), $file->getPathname());
}
}
} | php | {
"resource": ""
} |
q1751 | ModuleInstallForm.checkModuleValidity | train | public function checkModuleValidity(UploadedFile $file, ExecutionContextInterface $context)
{
$modulePath = $this->unzipModule($file);
if ($modulePath !== false) {
try {
// get the first directory
$moduleFiles = $this->getDirContents($modulePath);
if (\count($moduleFiles['directories']) !== 1) {
throw new Exception(
Translator::getInstance()->trans(
"Your zip must contain 1 root directory which is the root folder directory of your module"
)
);
}
$moduleDirectory = $moduleFiles['directories'][0];
$this->modulePath = sprintf('%s/%s', $modulePath, $moduleDirectory);
$moduleValidator = new ModuleValidator($this->modulePath);
$moduleValidator->validate();
$this->moduleDefinition = $moduleValidator->getModuleDefinition();
} catch (Exception $ex) {
$context->addViolation(
Translator::getInstance()->trans(
"The module is not valid : %message",
['%message' => $ex->getMessage()]
)
);
}
}
} | php | {
"resource": ""
} |
q1752 | ModuleInstallForm.unzipModule | train | protected function unzipModule(UploadedFile $file)
{
$extractPath = false;
$zip = new ZipArchiver(true);
if (!$zip->open($file->getRealPath())) {
throw new \Exception("unable to open zipfile");
}
$extractPath = $this->tempdir();
if ($extractPath !== false) {
if ($zip->extract($extractPath) === false) {
$extractPath = false;
}
}
$zip->close();
return $extractPath;
} | php | {
"resource": ""
} |
q1753 | ModuleInstallForm.tempdir | train | protected function tempdir()
{
$tempfile = tempnam(sys_get_temp_dir(), '');
if (file_exists($tempfile)) {
unlink($tempfile);
}
mkdir($tempfile);
if (is_dir($tempfile)) {
return $tempfile;
}
return false;
} | php | {
"resource": ""
} |
q1754 | FalseNode.create | train | public static function create($boolean = FALSE) {
$is_upper = FormatterFactory::getDefaultFormatter()->getConfig('boolean_null_upper');
$node = new FalseNode();
$node->addChild(NameNode::create($is_upper ? 'FALSE' : 'false'), 'constantName');
return $node;
} | php | {
"resource": ""
} |
q1755 | CallNode.appendMethodCall | train | public function appendMethodCall($method_name) {
$method_call = ObjectMethodCallNode::create(clone $this, $method_name);
$this->replaceWith($method_call);
return $method_call;
} | php | {
"resource": ""
} |
q1756 | Folder.countAllContents | train | public function countAllContents($contentVisibility = true)
{
$children = FolderQuery::findAllChild($this->getId());
array_push($children, $this);
$query = ContentQuery::create()->filterByFolder(new ObjectCollection($children), Criteria::IN);
if ($contentVisibility !== '*') {
$query->filterByVisible($contentVisibility);
}
return $query->count();
} | php | {
"resource": ""
} |
q1757 | Folder.getRoot | train | public function getRoot($folderId)
{
$folder = FolderQuery::create()->findPk($folderId);
if (0 !== $folder->getParent()) {
$parentFolder = FolderQuery::create()->findPk($folder->getParent());
if (null !== $parentFolder) {
$folderId = $this->getRoot($parentFolder->getId());
}
}
return $folderId;
} | php | {
"resource": ""
} |
q1758 | PropelInitService.runCommand | train | public function runCommand(Command $command, array $parameters = [], OutputInterface $output = null)
{
$parameters['command'] = $command->getName();
$input = new ArrayInput($parameters);
if ($output === null) {
$output = new NullOutput();
}
$command->setApplication(new SymfonyConsoleApplication());
return $command->run($input, $output);
} | php | {
"resource": ""
} |
q1759 | PropelInitService.buildPropelConfig | train | public function buildPropelConfig()
{
$propelConfigCache = new ConfigCache(
$this->getPropelConfigFile(),
$this->debug
);
if ($propelConfigCache->isFresh()) {
return;
}
$configService = new DatabaseConfigurationSource(
Yaml::parse(file_get_contents($this->getTheliaDatabaseConfigFile())),
$this->envParameters
);
$propelConfig = $configService->getPropelConnectionsConfiguration();
$propelConfig['propel']['paths']['phpDir'] = THELIA_ROOT;
$propelConfig['propel']['generator']['objectModel']['builders'] = [
'object'
=> '\Thelia\Core\Propel\Generator\Builder\Om\ObjectBuilder',
'objectstub'
=> '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionObjectBuilder',
'objectmultiextend'
=> '\Thelia\Core\Propel\Generator\Builder\Om\MultiExtendObjectBuilder',
'query'
=> '\Thelia\Core\Propel\Generator\Builder\Om\QueryBuilder',
'querystub'
=> '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionQueryBuilder',
'queryinheritance'
=> '\Thelia\Core\Propel\Generator\Builder\Om\QueryInheritanceBuilder',
'queryinheritancestub'
=> '\Thelia\Core\Propel\Generator\Builder\Om\ExtensionQueryInheritanceBuilder',
'tablemap'
=> '\Thelia\Core\Propel\Generator\Builder\Om\TableMapBuilder',
'event'
=> '\Thelia\Core\Propel\Generator\Builder\Om\EventBuilder',
];
$propelConfigCache->write(
Yaml::dump($propelConfig),
[new FileResource($this->getTheliaDatabaseConfigFile())]
);
} | php | {
"resource": ""
} |
q1760 | PropelInitService.buildPropelInitFile | train | public function buildPropelInitFile()
{
$propelInitCache = new ConfigCache(
$this->getPropelInitFile(),
$this->debug
);
if ($propelInitCache->isFresh()) {
return;
}
$this->runCommand(
new ConfigConvertCommand(),
[
'--config-dir' => $this->getPropelConfigDir(),
'--output-dir' => $this->getPropelConfigDir(),
'--output-file' => static::$PROPEL_CONFIG_CACHE_FILENAME,
]
);
// rewrite the file as a cached file
$propelInitContent = file_get_contents($this->getPropelInitFile());
$propelInitCache->write(
$propelInitContent,
[new FileResource($this->getPropelConfigFile())]
);
} | php | {
"resource": ""
} |
q1761 | PropelInitService.buildPropelModels | train | public function buildPropelModels()
{
$fs = new Filesystem();
// cache testing
if ($fs->exists($this->getPropelModelDir() . 'hash')
&& file_get_contents($this->getPropelCacheDir() . 'hash') === file_get_contents($this->getPropelModelDir() . 'hash')) {
return;
}
$fs->remove($this->getPropelModelDir());
$this->runCommand(
new ModelBuildCommand(),
[
'--config-dir' => $this->getPropelConfigDir(),
'--schema-dir' => $this->getPropelSchemaDir(),
]
);
$fs->copy(
$this->getPropelCacheDir() . 'hash',
$this->getPropelModelDir() . 'hash'
);
} | php | {
"resource": ""
} |
q1762 | PropelInitService.registerPropelModelLoader | train | public function registerPropelModelLoader()
{
$loader = new ClassLoader();
$loader->addPrefix(
'', // no prefix, models already define their full namespace
$this->getPropelModelDir()
);
$loader->register(
true // prepend the autoloader to use cached models first
);
} | php | {
"resource": ""
} |
q1763 | PropelInitService.init | train | public function init($force = false)
{
$flockFactory = new Factory(new FlockStore());
$lock = $flockFactory->createLock('propel-cache-generation');
// Acquire a blocking cache generation lock
$lock->acquire(true);
try {
if ($force) {
(new Filesystem())->remove($this->getPropelCacheDir());
}
if (!file_exists($this->getTheliaDatabaseConfigFile())) {
return false;
}
$this->buildPropelConfig();
$this->buildPropelInitFile();
require $this->getPropelInitFile();
$theliaDatabaseConnection = Propel::getConnection('thelia');
$this->schemaLocator->setTheliaDatabaseConnection($theliaDatabaseConnection);
$this->buildPropelGlobalSchema();
$this->buildPropelModels();
$this->registerPropelModelLoader();
$theliaDatabaseConnection->setAttribute(ConnectionWrapper::PROPEL_ATTR_CACHE_PREPARES, true);
if ($this->debug) {
// In debug mode, we have to initialize Tlog at this point, as this class uses Propel
Tlog::getInstance()->setLevel(Tlog::DEBUG);
Propel::getServiceContainer()->setLogger('defaultLogger', Tlog::getInstance());
$theliaDatabaseConnection->useDebug(true);
}
} catch (\Throwable $th) {
$fs = new Filesystem();
$fs->remove(THELIA_CACHE_DIR . $this->environment);
$fs->remove($this->getPropelModelDir());
throw $th;
} finally {
// Release cache generation lock
$lock->release();
}
return true;
} | php | {
"resource": ""
} |
q1764 | ModuleExtension.addLoaderFile | train | protected function addLoaderFile(string $file, string $locale = null): void
{
if ($this->loader === null) {
$builder = $this->getContainerBuilder();
$loader = $builder->getByType(LoaderFactory::class);
$this->loader = $builder->getDefinition($loader);
}
$this->loader->addSetup('addFile', [$file, $locale]);
} | php | {
"resource": ""
} |
q1765 | Load.setLoad | train | public function setLoad( $libraries ) {
$load = false;
$product = false;
foreach( $libraries as $name => $version ) {
// Check for branch versions normalized (dev/master).
if ( strpos( $version, 'dev' ) !== false ) {
$load = $version;
$product = $name;
break;
}
// Check for highest loaded version.
if ( version_compare( $load, $version ) === -1 ) {
$load = $version;
$product = $name;
}
}
return $this->load = ( object ) array( 'product' => $product, 'version' => $load );
} | php | {
"resource": ""
} |
q1766 | Load.setPath | train | public function setPath() {
$found = $this->getLoad();
$path = false;
if ( ! empty( $found->product ) ) {
// Loading from must use plugin directory?
if ( ! is_file( $path = trailingslashit( WPMU_PLUGIN_DIR ) . $found->product ) ) {
// Loading from plugin directory?
if ( ! is_file( $path = trailingslashit( WP_PLUGIN_DIR ) . $found->product ) ) {
// Loading from a parent theme directory?
$path = get_template_directory() . '/inc/boldgrid-theme-framework/includes/theme';
}
}
// Loading from framework path override directory?
if ( defined( 'BGTFW_PATH' ) ) {
$dir = ABSPATH . trim( BGTFW_PATH, '/' ) . '/includes';
if ( is_dir( $dir . '/vendor/boldgrid/library' ) ) {
$path = $dir . '/theme';
}
}
$path = dirname( $path );
}
return $this->path = $path;
} | php | {
"resource": ""
} |
q1767 | Load.load | train | public function load( $loader ) {
if ( ! empty( $this->configs['libraryDir'] ) ) {
$library = $this->configs['libraryDir'] . 'src/Library';
// Only create a single instance of the BoldGrid Library Start.
if ( did_action( 'Boldgrid\Library\Library\Start' ) === 0 ) {
do_action( 'Boldgrid\Library\Library\Start', $library );
// Check dir and add PSR-4 dir of the BoldGrid Library to autoload.
if ( is_dir( $library ) ) {
$loader->addPsr4( 'Boldgrid\\Library\\Library\\', $library );
$load = new \Boldgrid\Library\Library\Start( $this->configs );
$load->init();
}
}
}
} | php | {
"resource": ""
} |
q1768 | Locale.setDefault | train | public function setDefault(): void
{
$repo = $this->getRepository();
$locales = $repo->findAll();
foreach ($locales as $locale) {
/* @var $locale self */
$locale->default = false;
$repo->persist($locale);
}
$this->default = true;
$repo->persist($this);
$repo->flush();
} | php | {
"resource": ""
} |
q1769 | PageDuplicationController.getOriginOfPageByPageIdAction | train | public function getOriginOfPageByPageIdAction()
{
$data = array();
$tool = $this->getServiceLocator()->get('MelisCmsPage');
$data = $tool->getOriginOfPage()->toArray();
return $data;
} | php | {
"resource": ""
} |
q1770 | AbstractAdminResourcesCompiler.process | train | public function process(\Symfony\Component\DependencyInjection\ContainerBuilder $container)
{
if (!$container->hasDefinition("thelia.admin.resources")) {
return;
}
/** @var \Symfony\Component\DependencyInjection\Definition $adminResources */
$adminResources = $container->getDefinition("thelia.admin.resources");
$adminResources->addMethodCall("addModuleResources", [$this->getResources(), $this->getModuleCode()]);
} | php | {
"resource": ""
} |
q1771 | AbstractImport.checkMandatoryColumns | train | public function checkMandatoryColumns(array $data)
{
$diff = array_diff($this->mandatoryColumns, array_keys($data));
if (\count($diff) > 0) {
throw new \UnexpectedValueException(
Translator::getInstance()->trans(
'The following columns are missing: %columns',
[
'%columns' => implode(', ', $diff)
]
)
);
}
} | php | {
"resource": ""
} |
q1772 | AbstractExport.applyOrderAndAliases | train | public function applyOrderAndAliases(array $data)
{
if ($this->orderAndAliases === null) {
return $data;
}
$processedData = [];
foreach ($this->orderAndAliases as $key => $value) {
if (\is_integer($key)) {
$fieldName = $value;
$fieldAlias = $value;
} else {
$fieldName = $key;
$fieldAlias = $value;
}
$processedData[$fieldAlias] = null;
if (array_key_exists($fieldName, $data)) {
$processedData[$fieldAlias] = $data[$fieldName];
}
}
return $processedData;
} | php | {
"resource": ""
} |
q1773 | AbstractExport.beforeSerialize | train | public function beforeSerialize(array $data)
{
foreach ($data as $idx => &$value) {
if ($value instanceof \DateTime) {
$value = $value->format('Y-m-d H:i:s');
}
}
return $data;
} | php | {
"resource": ""
} |
q1774 | Filter.doFilter | train | private static function doFilter( $action, $class ) {
$reflection = new \ReflectionClass( $class );
foreach ( $reflection->getMethods() as $method ) {
if ( $method->isPublic() && ! $method->isConstructor() ) {
$comment = $method->getDocComment();
// No hooks.
if ( preg_match( '/@nohook[ \t\*\n]+/', $comment ) ) {
continue;
}
// Set hook.
preg_match_all( '/@hook:?\s+([^\s]+)/', $comment, $matches ) ? $matches[1] : $method->name;
if ( empty( $matches[1] ) ) {
$hooks = array( $method->name );
} else {
$hooks = $matches[1];
}
// Allow setting priority.
$priority = preg_match( '/@priority:?\s+(\d+)/', $comment, $matches ) ? $matches[1] : 10;
// Fire.
foreach ( $hooks as $hook ) {
call_user_func( $action, $hook, array( $class, $method->name ), $priority, $method->getNumberOfParameters() );
}
}
}
} | php | {
"resource": ""
} |
q1775 | Filter.removeHook | train | public static function removeHook( $tag, $class, $name, $priority = 10 ) {
global $wp_filter;
// Check that filter exists.
if ( isset( $wp_filter[ $tag ] ) ) {
/**
* If filter config is an object, means we're using WordPress 4.7+ and the config is no longer
* a simple array, and it is an object that implements the ArrayAccess interface.
*
* To be backwards compatible, we set $callbacks equal to the correct array as a reference (so $wp_filter is updated).
*
* @see https://make.wordpress.org/core/2016/09/08/wp_hook-next-generation-actions-and-filters/
*/
if ( is_object( $wp_filter[ $tag ] ) && isset( $wp_filter[ $tag ]->callbacks ) ) {
// Create $fob object from filter tag, to use below.
$fob = $wp_filter[ $tag ];
$callbacks = &$wp_filter[ $tag ]->callbacks;
} else {
$callbacks = &$wp_filter[ $tag ];
}
// Exit if there aren't any callbacks for specified priority.
if ( ! isset( $callbacks[ $priority ] ) || empty( $callbacks[ $priority ] ) ) {
return false;
}
// Loop through each filter for the specified priority, looking for our class & method.
foreach( ( array ) $callbacks[ $priority ] as $filter_id => $filter ) {
// Filter should always be an array - array( $this, 'method' ), if not goto next.
if ( ! isset( $filter['function'] ) || ! is_array( $filter['function'] ) ) {
continue;
}
// If first value in array is not an object, it can't be a class.
if ( ! is_object( $filter['function'][0] ) ) {
continue;
}
// Method doesn't match the one we're looking for, goto next.
if ( $filter['function'][1] !== $name ) {
continue;
}
// Callback method matched, so check class.
if ( get_class( $filter['function'][0] ) === $class ) {
// WordPress 4.7+ use core remove_filter() since we found the class object.
if ( isset( $fob ) ) {
// Handles removing filter, reseting callback priority keys mid-iteration, etc.
$fob->remove_filter( $tag, $filter['function'], $priority );
} else {
// Use legacy removal process (pre 4.7).
unset( $callbacks[ $priority ][ $filter_id ] );
// If it was the only filter in that priority, unset that priority.
if ( empty( $callbacks[ $priority ] ) ) {
unset( $callbacks[ $priority ] );
}
// If the only filter for that tag, set the tag to an empty array.
if ( empty( $callbacks ) ) {
$callbacks = array();
}
// Remove this filter from merged_filters, which specifies if filters have been sorted.
unset( $GLOBALS['merged_filters'][ $tag ] );
}
return true;
}
}
}
return false;
} | php | {
"resource": ""
} |
q1776 | SaleModificationForm.checkDate | train | public function checkDate($value, ExecutionContextInterface $context)
{
$format = self::PHP_DATE_FORMAT;
if (! empty($value) && false === \DateTime::createFromFormat($format, $value)) {
$context->addViolation(Translator::getInstance()->trans("Date '%date' is invalid, please enter a valid date using %fmt format", [
'%fmt' => self::MOMENT_JS_DATE_FORMAT,
'%date' => $value
]));
}
} | php | {
"resource": ""
} |
q1777 | ContainerAwareCommand.initRequest | train | protected function initRequest(Lang $lang = null)
{
$container = $this->getContainer();
$request = Request::create($this->getBaseUrl($lang));
$request->setSession(new Session(new MockArraySessionStorage()));
$container->set("request_stack", new RequestStack());
$container->get('request_stack')->push($request);
$requestContext = new RequestContext();
$requestContext->fromRequest($request);
$url = $container->get('thelia.url.manager');
$url->setRequestContext($requestContext);
$this->getContainer()->get('router.admin')->setContext($requestContext);
} | php | {
"resource": ""
} |
q1778 | Cart.duplicate | train | public function duplicate(
$token,
Customer $customer = null,
Currency $currency = null,
EventDispatcherInterface $dispatcher = null
) {
if (!$dispatcher) {
return false;
}
$cartItems = $this->getCartItems();
$cart = new Cart();
$cart->setAddressDeliveryId($this->getAddressDeliveryId());
$cart->setAddressInvoiceId($this->getAddressInvoiceId());
$cart->setToken($token);
$discount = 0;
if (null === $currency) {
$currencyQuery = CurrencyQuery::create();
$currency = $currencyQuery->findPk($this->getCurrencyId()) ?: $currencyQuery->findOneByByDefault(1);
}
$cart->setCurrency($currency);
if ($customer) {
$cart->setCustomer($customer);
if ($customer->getDiscount() > 0) {
$discount = $customer->getDiscount();
}
}
$cart->save();
foreach ($cartItems as $cartItem) {
$product = $cartItem->getProduct();
$productSaleElements = $cartItem->getProductSaleElements();
if ($product &&
$productSaleElements &&
$product->getVisible() == 1 &&
($productSaleElements->getQuantity() >= $cartItem->getQuantity() || $product->getVirtual() === 1 || ! ConfigQuery::checkAvailableStock())) {
$item = new CartItem();
$item->setCart($cart);
$item->setProductId($cartItem->getProductId());
$item->setQuantity($cartItem->getQuantity());
$item->setProductSaleElements($productSaleElements);
$prices = $productSaleElements->getPricesByCurrency($currency, $discount);
$item
->setPrice($prices->getPrice())
->setPromoPrice($prices->getPromoPrice())
->setPromo($productSaleElements->getPromo());
$item->save();
$dispatcher->dispatch(TheliaEvents::CART_ITEM_DUPLICATE, new CartItemDuplicationItem($item, $cartItem));
}
}
// Dispatche the duplication event before delting the cart from the database,
$dispatcher->dispatch(TheliaEvents::CART_DUPLICATED, new CartDuplicationEvent($cart, $this));
try {
$this->delete();
} catch (\Exception $e) {
// just fail silently in some cases
}
return $cart;
} | php | {
"resource": ""
} |
q1779 | Cart.getLastCartItemAdded | train | public function getLastCartItemAdded()
{
return CartItemQuery::create()
->filterByCartId($this->getId())
->orderByCreatedAt(Criteria::DESC)
->findOne()
;
} | php | {
"resource": ""
} |
q1780 | Cart.getTotalVAT | train | public function getTotalVAT($taxCountry, $taxState = null)
{
return ($this->getTaxedAmount($taxCountry, true, $taxState) - $this->getTotalAmount(true));
} | php | {
"resource": ""
} |
q1781 | Cart.getWeight | train | public function getWeight()
{
$weight = 0;
foreach ($this->getCartItems() as $cartItem) {
$itemWeight = $cartItem->getProductSaleElements()->getWeight();
$itemWeight *= $cartItem->getQuantity();
$weight += $itemWeight;
}
return $weight;
} | php | {
"resource": ""
} |
q1782 | Cart.isVirtual | train | public function isVirtual()
{
foreach ($this->getCartItems() as $cartItem) {
if (0 < $cartItem->getProductSaleElements()->getWeight()) {
return false;
}
$product = $cartItem->getProductSaleElements()->getProduct();
if (!$product->getVirtual()) {
return false;
}
}
return true;
} | php | {
"resource": ""
} |
q1783 | ConfigurationPresenter.createComponentConfigurationForm | train | protected function createComponentConfigurationForm(): Form
{
$form = $this->formFactory->create();
$form->setAjaxRequest();
$form->addGroup('cms.settings.basic');
$form->addImageUpload('cmsLogo', 'cms.settings.logo', 'cms.settings.deleteLogo')
->setNamespace('cms')
->setPreview('300x100');
$form->addCheckbox('sendNewUserPassword', 'cms.settings.sendNewUserPassword');
$form->addCheckbox('sendChangePassword', 'cms.settings.sendChangePassword');
$form->addCheckbox('dockbarAdvanced', 'cms.settings.dockbarAdvanced');
$form->addSelectUntranslated('defaultLocale', 'cms.settings.defaultLocale', $this->localeService->fetch())
->setDefaultValue($this->localeService->defaultLocaleId);
$form->addMultiSelectUntranslated('allowedLocales', 'cms.settings.allowedLocales', $this->localeService->fetch())
->setDefaultValue($this->localeService->allowedLocaleIds)
->setRequired();
$form->addGroup('cms.settings.development');
if (!$this->tracy->isEnabled()) {
$form->addLink('debugOn', 'cms.settings.debugOn')
->link($this->link('debug!', true))
->setAjaxRequest()
->addClass('btn-success')
->setAttribute('data-ajax-off', 'history');
} else {
$form->addLink('debugOff', 'cms.settings.debugOff')
->link($this->link('debug!', false))
->setAjaxRequest()
->addClass('btn-danger')
->setAttribute('data-ajax-off', 'history');
}
$form->addCheckbox('mailPanel', 'cms.settings.mailPanel')
->setDefaultValue($this->configurator->mailPanel);
$form->getRenderer()->primaryButton = $form->addSubmit('save', 'form.save');
$form->onSuccess[] = [$this, 'configurationFormSucseeded'];
return $form;
} | php | {
"resource": ""
} |
q1784 | Option.init | train | public static function init( $name = 'boldgrid_settings', $key = 'library' ) {
self::$name = $name;
self::$key = $key;
self::$option = self::getOption();
} | php | {
"resource": ""
} |
q1785 | Option.set | train | public static function set( $key, $value ) {
self::$option[ self::$key ][ $key ] = $value;
return update_option( self::$name, self::$option );
} | php | {
"resource": ""
} |
q1786 | Option.delete | train | public static function delete( $key ) {
unset( self::$option[ self::$key ][ $key ] );
return update_option( self::$name, self::$option );
} | php | {
"resource": ""
} |
q1787 | Option.get | train | public static function get( $key = null, $default = array() ) {
return $key && ! empty( self::$option[ $key ] ) ? self::$option[ $key ] : $default;
} | php | {
"resource": ""
} |
q1788 | SecurityContext.hasRequiredRole | train | final public function hasRequiredRole(UserInterface $user = null, array $roles = [])
{
if ($user != null) {
// Check if user's roles matches required roles
$userRoles = $user->getRoles();
foreach ($userRoles as $role) {
if (\in_array($role, $roles)) {
return true;
}
}
}
return false;
} | php | {
"resource": ""
} |
q1789 | SecurityContext.isGranted | train | final public function isGranted(array $roles, array $resources, array $modules, array $accesses)
{
// Find a user which matches the required roles.
$user = $this->checkRole($roles);
if (null === $user) {
return false;
} else {
return $this->isUserGranted($roles, $resources, $modules, $accesses, $user);
}
} | php | {
"resource": ""
} |
q1790 | SecurityContext.checkRole | train | public function checkRole(array $roles)
{
// Find a user which matches the required roles.
$user = $this->getCustomerUser();
if (! $this->hasRequiredRole($user, $roles)) {
$user = $this->getAdminUser();
if (! $this->hasRequiredRole($user, $roles)) {
$user = null;
}
}
return $user;
} | php | {
"resource": ""
} |
q1791 | MelisCmsPageEditionSavePluginSessionListener.insertOrReplaceTag | train | private function insertOrReplaceTag($content, $search, $replace)
{
$newContent = null;
$regexSearch = "/(\<$search\>\<\!\[CDATA\[([0-9.])+\]\]\>\<\/$search\>)/";
if(preg_match($regexSearch, $content)) {
$newContent = preg_replace($regexSearch, $replace, $content);
}
else {
$newContent = $content . $replace;
}
return $newContent;
} | php | {
"resource": ""
} |
q1792 | MelisCmsPageEditionSavePluginSessionListener.updateMelisPlugin | train | private function updateMelisPlugin($pageId, $plugin, $pluginId, $content, $updateSettings = false)
{
$pluginContent = $content;
$pluginSessionSettings = isset($_SESSION['meliscms']['content-pages'][$pageId]['private:melisPluginSettings'][$pluginId]) ?
$_SESSION['meliscms']['content-pages'][$pageId]['private:melisPluginSettings'][$pluginId] : '';
$pluginSettings = (array) json_decode($pluginSessionSettings);
if($plugin == 'melisTag') {
$pattern = '/type\=\"([html|media|textarea]*\")/';
if(preg_match($pattern, $pluginContent, $matches)) {
$type = isset($matches[0]) ? $matches[0] : null;
if($type) {
// apply sizes
if($pluginSettings) {
/* $replacement = $type .' width_desktop="'.$pluginSettings['width_desktop'].
'" width_tablet="'.$pluginSettings['width_tablet'].
'" width_mobile="'.$pluginSettings['width_mobile'].'"';
$pluginContent = preg_replace($pattern, $replacement, $pluginContent); */
$pluginContent = $this->setPluginWidthXmlAttribute($pluginContent, $pluginSettings);
}
}
}
}
else {
$pattern = '\<'.$plugin.'\sid\=\"(.*?)*\"';
if(preg_match('/'.$pattern.'/', $pluginContent, $matches)) {
$id = isset($matches[0]) ? $matches[0] : null;
if($id) {
if($pluginSettings) {
/* $replacement = $id .' width_desktop="'.$pluginDesktop.
'" width_tablet="'.$pluginTablet.
'" width_mobile="'.$pluginMobile.'"';
$pluginContent = preg_replace('/'.$pattern.'/', $replacement, $pluginContent); */
$pluginContent = $this->setPluginWidthXmlAttribute($pluginContent, $pluginSettings);
}
}
}
}
if(isset($_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId])) {
$_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId] =
$this->getPluginContentWithInsertedContainerId($pageId, $plugin, $pluginId, $pluginContent);
$pluginContent = $_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId];
if($updateSettings) {
$_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId] = $this->reapplySettings($pageId, $plugin, $pluginId, $pluginContent);
}
if($plugin == 'melisTag') {
$content = $this->updateContent($pageId, $plugin, $pluginId, $pluginContent);
$_SESSION['meliscms']['content-pages'][$pageId][$plugin][$pluginId] = $content;
}
}
} | php | {
"resource": ""
} |
q1793 | MelisCmsPageEditionSavePluginSessionListener.setPluginWidthXmlAttribute | train | private function setPluginWidthXmlAttribute($pluginXml, $pluginSettings){
try {
$pluginDesktop = isset($pluginSettings['width_desktop']) ? $pluginSettings['width_desktop'] : 100;
$pluginTablet = isset($pluginSettings['width_tablet']) ? $pluginSettings['width_tablet'] : 100;
$pluginMobile = isset($pluginSettings['width_mobile']) ? $pluginSettings['width_mobile'] : 100;
// Parsing xml string to Xml object
$xml = simplexml_load_string($pluginXml);
// Adding/updating plugin xml attributes
if (isset($xml->attributes()->width_desktop))
$xml->attributes()->width_desktop = $pluginDesktop;
else
$xml->addAttribute('width_desktop', $pluginDesktop);
if (isset($xml->attributes()->width_tablet))
$xml->attributes()->width_tablet = $pluginTablet;
else
$xml->addAttribute('width_tablet', $pluginTablet);
if (isset($xml->attributes()->width_mobile))
$xml->attributes()->width_mobile = $pluginMobile;
else
$xml->addAttribute('width_mobile', $pluginMobile);
// Geeting the Plugin xml
$customXML = new \SimpleXMLElement($xml->asXML());
$dom = dom_import_simplexml($customXML);
$pluginXml = $dom->ownerDocument->saveXML($dom->ownerDocument->documentElement);
}catch (\Exception $e){}
return $pluginXml;
} | php | {
"resource": ""
} |
q1794 | Order.getWeight | train | public function getWeight()
{
$weight = 0;
/* browse all products */
foreach ($this->getOrderProducts() as $orderProduct) {
$weight += $orderProduct->getQuantity() * (double)$orderProduct->getWeight();
}
return $weight;
} | php | {
"resource": ""
} |
q1795 | Order.getUntaxedPostage | train | public function getUntaxedPostage()
{
if (0 < $this->getPostageTax()) {
$untaxedPostage = $this->getPostage() - $this->getPostageTax();
} else {
$untaxedPostage = $this->getPostage();
}
return $untaxedPostage;
} | php | {
"resource": ""
} |
q1796 | Order.hasVirtualProduct | train | public function hasVirtualProduct()
{
$virtualProductCount = OrderProductQuery::create()
->filterByOrderId($this->getId())
->filterByVirtual(1, Criteria::EQUAL)
->count()
;
return ($virtualProductCount !== 0);
} | php | {
"resource": ""
} |
q1797 | Order.setStatusHelper | train | public function setStatusHelper($statusCode)
{
if (null !== $ordeStatus = OrderStatusQuery::create()->findOneByCode($statusCode)) {
$this->setOrderStatus($ordeStatus)->save();
}
} | php | {
"resource": ""
} |
q1798 | Order.getPaymentModuleInstance | train | public function getPaymentModuleInstance()
{
if (null === $paymentModule = ModuleQuery::create()->findPk($this->getPaymentModuleId())) {
throw new TheliaProcessException("Payment module ID=" . $this->getPaymentModuleId() . " was not found.");
}
return $paymentModule->createInstance();
} | php | {
"resource": ""
} |
q1799 | Order.getDeliveryModuleInstance | train | public function getDeliveryModuleInstance()
{
if (null === $deliveryModule = ModuleQuery::create()->findPk($this->getDeliveryModuleId())) {
throw new TheliaProcessException("Delivery module ID=" . $this->getDeliveryModuleId() . " was not found.");
}
return $deliveryModule->createInstance();
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.