_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q248300 | AbstractView.addClass | validation | public function addClass($class)
{
$classes = $this->getClasses();
if (!in_array($class, $classes)) {
$classes[] = $class;
}
$this->setClasses($classes);
return $this;
} | php | {
"resource": ""
} |
q248301 | AbstractView.removeClass | validation | public function removeClass($class)
{
$classes = $this->getClasses();
if (false !== $index = array_search($class, $classes)) {
unset($classes[$index]);
}
$this->setClasses($classes);
return $this;
} | php | {
"resource": ""
} |
q248302 | AbstractView.setClasses | validation | private function setClasses(array $classes)
{
if (!empty($classes)) {
$this->vars['attr']['class'] = ' ' . trim(implode(' ', $classes));
} else {
unset($this->vars['attr']['class']);
}
} | php | {
"resource": ""
} |
q248303 | CustomerUpdater.updateCustomerBalance | validation | protected function updateCustomerBalance(PaymentInterface $payment, $amount = null)
{
if (null === $customer = $payment->getSale()->getCustomer()) {
// TODO Deals with customer change
return false;
}
$amount = $amount ?: $payment->getAmount();
if ($this->isAcceptedPayment($payment)) {
$amount = -$amount;
}
if ($payment->getMethod()->isCredit()) {
return $this->updateCreditBalance($customer, $amount, true);
} elseif ($payment->getMethod()->isOutstanding()) {
return $this->updateOutstandingBalance($customer, $amount, true);
}
return false;
} | php | {
"resource": ""
} |
q248304 | CustomerUpdater.getAcceptedStates | validation | protected function getAcceptedStates(PaymentInterface $payment)
{
$acceptedStates = PaymentStates::getPaidStates();
if ($payment->getMethod()->isOutstanding()) {
$acceptedStates[] = PaymentStates::STATE_EXPIRED;
}
return $acceptedStates;
} | php | {
"resource": ""
} |
q248305 | CustomerUpdater.supports | validation | protected function supports(PaymentInterface $payment)
{
if (null === $method = $payment->getMethod()) {
throw new RuntimeException("Payment method must be set.");
}
if ($method->isCredit() || $method->isOutstanding()) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q248306 | AuthActionsTrait.getAuthActions | validation | public function getAuthActions() {
if (!$this->_AuthActions) {
if (Configure::load('auth_actions') === false) {
trigger_error('AuthActions: Could not load config/auth_actions.php', E_USER_WARNING);
}
$actionConfig = Configure::read('auth_actions');
$publicActionsConfig = Configure::read('public_actions');
$options = Configure::read('auth_settings');
if (!is_array($options)) {
$options = [];
}
if (!is_array($publicActionsConfig)) {
$publicActionsConfig = [];
}
$this->_AuthActions = new AuthActions($actionConfig, $publicActionsConfig, $options);
}
return $this->_AuthActions;
} | php | {
"resource": ""
} |
q248307 | AuthActionsTrait.getUserRights | validation | public function getUserRights() {
if (!$this->_UserRights) {
if (Configure::load('user_rights') === false) {
trigger_error('UserRights: Could not load config/user_rights.php', E_USER_WARNING);
}
$rightsConfig = Configure::read('user_rights');
if (!is_array($rightsConfig)) {
$rightsConfig = [];
}
$this->_UserRights = new UserRights($rightsConfig);
}
return $this->_UserRights;
} | php | {
"resource": ""
} |
q248308 | AccountingListener.getAccountingFromEvent | validation | protected function getAccountingFromEvent(ResourceEventInterface $event)
{
$resource = $event->getResource();
if (!$resource instanceof AccountingInterface) {
throw new InvalidArgumentException('Expected instance of ' . AccountingInterface::class);
}
return $resource;
} | php | {
"resource": ""
} |
q248309 | Units.getUnits | validation | static function getUnits()
{
return [
static::PIECE,
// Length
static::METER,
static::CENTIMETER,
static::MILLIMETER,
static::INCH,
static::FOOT,
// Weight
static::KILOGRAM,
static::GRAM,
// Volume
static::CUBIC_METER,
static::LITER,
static::MILLILITER,
// Duration
static::DAY,
static::HOUR,
static::MINUTE,
static::SECOND,
];
} | php | {
"resource": ""
} |
q248310 | Units.isValid | validation | static function isValid($unit, $throw = false)
{
if (in_array($unit, static::getUnits(), true)) {
return true;
}
if ($throw) {
throw new InvalidArgumentException("Invalid unit '$unit'.");
}
return false;
} | php | {
"resource": ""
} |
q248311 | Units.round | validation | static function round($value, $unit = 'piece')
{
if (0 < $precision = static::getPrecision($unit)) {
$divider = pow(10, $precision);
return round(floor($value * $divider) / $divider, $precision);
}
return floor($value);
} | php | {
"resource": ""
} |
q248312 | TicketAttachmentEventListener.updateMessage | validation | protected function updateMessage(TicketMessageInterface $message)
{
$message->setUpdatedAt(new \DateTime());
$this->persistenceHelper->persistAndRecompute($message, true);
} | php | {
"resource": ""
} |
q248313 | TicketAttachmentEventListener.getAttachmentFromEvent | validation | protected function getAttachmentFromEvent(ResourceEventInterface $event)
{
$attachment = $event->getResource();
if (!$attachment instanceof TicketAttachmentInterface) {
throw new UnexpectedValueException("Expected instance of " . TicketAttachmentInterface::class);
}
return $attachment;
} | php | {
"resource": ""
} |
q248314 | StockUnitStates.isBetterAvailability | validation | static public function isBetterAvailability($stateA, $stateB)
{
if ($stateA === $stateB) {
return false;
}
switch ($stateA) {
// 'pending' is better than 'new' or 'closed'
case static::STATE_PENDING:
return in_array($stateB, [static::STATE_NEW, static::STATE_CLOSED], true);
// 'ready' is better than 'new', 'pending' or 'closed'
case static::STATE_READY:
return in_array($stateB, [static::STATE_NEW, static::STATE_PENDING, static::STATE_CLOSED], true);
}
return false;
} | php | {
"resource": ""
} |
q248315 | EcNvpConvertAction.addSaleDetails | validation | private function addSaleDetails(array &$details, Model\SaleInterface $sale)
{
if ($sale->getCurrency()->getCode() !== $this->currency) {
return;
}
if (0 !== Money::compare($sale->getGrandTotal(), $details['PAYMENTREQUEST_0_AMT'], $this->currency)) {
return;
}
$this->calculator->calculateSale($sale);
$this->line = 0;
$lineTotals = 0;
// Items
foreach ($sale->getItems() as $item) {
$lineTotals += $this->addItemDetails($details, $item);
}
// Discounts
foreach ($sale->getAdjustments(Model\AdjustmentTypes::TYPE_DISCOUNT) as $discount) {
$lineTotals += $this->addDiscountDetails($details, $discount);
}
// Lines total
$details['PAYMENTREQUEST_0_ITEMAMT'] = $this->format($lineTotals);
// Shipping
$details['PAYMENTREQUEST_0_SHIPPINGAMT'] = $this->format($sale->getShipmentResult()->getTotal());
// Taxes
//$details['PAYMENTREQUEST_0_TAXAMT'] = $this->format($sale->getFinalResult()->getTax());
} | php | {
"resource": ""
} |
q248316 | EcNvpConvertAction.addItemDetails | validation | private function addItemDetails(array &$details, Model\SaleItemInterface $item)
{
$total = 0;
if (!($item->isCompound() && !$item->hasPrivateChildren())) {
$itemResult = $item->getResult();
$details['L_PAYMENTREQUEST_0_NAME' . $this->line] = $item->getTotalQuantity() . 'x ' . $item->getDesignation();
$details['L_PAYMENTREQUEST_0_NUMBER' . $this->line] = $item->getReference();
if (!empty($description = $item->getDescription())) {
$details['L_PAYMENTREQUEST_0_DESC' . $this->line] = $description;
}
$details['L_PAYMENTREQUEST_0_AMT' . $this->line] = $this->format($itemResult->getTotal());
//$details['L_PAYMENTREQUEST_0_TAXAMT' . $this->line] = $this->format($itemResult->getTax());
//$details['L_PAYMENTREQUEST_0_ITEMURL' . $this->itemNum] = '';
$total = $itemResult->getTotal();
$this->line++;
}
foreach ($item->getChildren() as $child) {
$total += $this->addItemDetails($details, $child);
}
return $total;
} | php | {
"resource": ""
} |
q248317 | EcNvpConvertAction.addDiscountDetails | validation | private function addDiscountDetails(array &$details, Model\SaleAdjustmentInterface $discount)
{
$discountResult = $discount->getResult();
$details['L_PAYMENTREQUEST_0_NAME' . $this->line] = $discount->getDesignation();
$details['L_PAYMENTREQUEST_0_AMT' . $this->line] = '-' . $this->format($discountResult->getTotal());
//$details['L_PAYMENTREQUEST_0_TAXAMT' . $this->line] = '-' . $this->format($discountResult->getTax());
$this->line++;
return -$discountResult->getTotal();
} | php | {
"resource": ""
} |
q248318 | SaleDocumentUtil.getSaleEditableDocumentTypes | validation | static public function getSaleEditableDocumentTypes(SaleInterface $sale)
{
$types = [];
foreach (DocumentTypes::getTypes() as $type) {
if (!static::isSaleSupportsDocumentType($sale, $type)) {
continue;
}
foreach ($sale->getAttachments() as $attachment) {
if ($attachment->getType() === $type) {
continue 2;
}
}
$types[] = $type;
}
return $types;
} | php | {
"resource": ""
} |
q248319 | SaleDocumentUtil.isSaleSupportsDocumentType | validation | static public function isSaleSupportsDocumentType(SaleInterface $sale, $type)
{
if (!DocumentTypes::isValidType($type)) {
return false;
}
if (empty($classes = DocumentTypes::getClasses($type))) {
return false;
}
foreach ($classes as $class) {
if (is_subclass_of($sale, $class)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q248320 | Recipient.getTypes | validation | public static function getTypes()
{
return [
self::TYPE_WEBSITE,
self::TYPE_USER,
self::TYPE_ADMINISTRATOR,
self::TYPE_IN_CHARGE,
self::TYPE_CUSTOMER,
self::TYPE_SALESMAN,
self::TYPE_ACCOUNTABLE,
self::TYPE_SUPPLIER,
];
} | php | {
"resource": ""
} |
q248321 | SaleTransformSubscriber.onPreCopy | validation | public function onPreCopy(SaleTransformEvent $event)
{
$source = $event->getSource();
if ($source instanceof OrderInterface) {
// Prevent if order is not 'new'
if ($source->getState() !== OrderStates::STATE_NEW) {
$event->addMessage(new ResourceMessage(
'ekyna_commerce.sale.message.transform_prevented',
ResourceMessage::TYPE_ERROR
));
}
}
} | php | {
"resource": ""
} |
q248322 | SaleTransformSubscriber.onPostCopy | validation | public function onPostCopy(SaleTransformEvent $event)
{
$source = $event->getSource();
$target = $event->getTarget();
// Origin number
$target->setOriginNumber($source->getNumber());
// Sample
if ($source instanceof OrderInterface && $target instanceof OrderInterface) {
$target->setSample($source->isSample());
}
// Abort if source sale has no customer
if (null === $customer = $source->getCustomer()) {
return;
}
// If target sale is order and source customer has parent
if ($target instanceof OrderInterface && $customer->hasParent()) {
// TODO Duplicate code
/** @see \Ekyna\Component\Commerce\Order\EventListener\OrderListener::fixCustomers() */
// Sets the parent as customer
$target->setCustomer($customer->getParent());
// Sets the origin customer
if (null === $target->getOriginCustomer()) {
$target->setOriginCustomer($customer);
}
}
} | php | {
"resource": ""
} |
q248323 | Request.uri | validation | public function uri($uri = NULL): string {
if ($uri === NULL) {
return empty($this->_uri) ? '/' : $this->_uri;
}
return $this->_uri = $uri;
} | php | {
"resource": ""
} |
q248324 | Request.method | validation | public function method($method = NULL) {
if ($method === NULL) {
// Act as a getter
return $this->_method;
}
// Act as a setter
$this->_method = strtoupper($method);
return $this;
} | php | {
"resource": ""
} |
q248325 | Request.delete_cookie | validation | public function delete_cookie($name) {
// Remove the cookie
unset($_COOKIE[$name]);
// Nullify the cookie and make it expire
return setcookie($name, null, -86400, $this->cookie_path, $this->cookie_domain, $this->cookie_secure, $this->cookie_httponly);
} | php | {
"resource": ""
} |
q248326 | ManyToManyRelationRecordsFormInput.setDbQueryConditionsForDefaultOptionsLoader | validation | public function setDbQueryConditionsForDefaultOptionsLoader($conditonsAndOptions) {
if (
!is_array($conditonsAndOptions)
&& !($conditonsAndOptions instanceof DbExpr)
&& !($conditonsAndOptions instanceof \Closure)
) {
throw new \InvalidArgumentException(
'$conditonsAndOptions argument must be a string, DbExpr or a Closure'
);
}
$this->dbQueryConditionsForDefaultOptionsLoader = $conditonsAndOptions;
return $this;
} | php | {
"resource": ""
} |
q248327 | ManyToManyRelationRecordsFormInput.setOptionLabelColumnForDefaultOptionsLoader | validation | public function setOptionLabelColumnForDefaultOptionsLoader($columnNameOrClosure) {
if (
!is_string($columnNameOrClosure)
&& !($columnNameOrClosure instanceof DbExpr)
&& !($columnNameOrClosure instanceof \Closure)
) {
throw new \InvalidArgumentException(
'$columnNameOrClosure argument must be a string, DbExpr or a Closure'
);
}
$this->optionLabelColumnForDefaultOptionsLoader = $columnNameOrClosure;
return $this;
} | php | {
"resource": ""
} |
q248328 | ResetsPasswordsViaAccessKey.loadFromPasswordRecoveryAccessKey | validation | static public function loadFromPasswordRecoveryAccessKey(string $accessKey) {
try {
$data = \Crypt::decrypt($accessKey);
} catch (DecryptException $exc) {
return false;
}
if (empty($data)) {
return false;
}
$data = json_decode($data, true);
$now = new \DateTime('now', new \DateTimeZone('UTC'));
if (
empty($data)
|| !is_array($data)
|| !isset($data['added_keys'])
|| !is_array($data['added_keys'])
|| empty($data['account_id'])
|| empty($data['expires_at'])
|| $data['expires_at'] < $now->getTimestamp()
) {
return false;
}
/** @var ResetsPasswordsViaAccessKey|CmfDbRecord $user */
$user = static::newEmptyRecord();
$conditions = [
$user::getPrimaryKeyColumnName() => $data['account_id'],
];
$additionalColumns = $data['added_keys'];
foreach ($additionalColumns as $columnName) {
if (!array_key_exists($columnName, $data)) {
return false;
}
$fieldType = $user::getColumn($columnName)->getType();
switch ($fieldType) {
case Column::TYPE_DATE:
$conditions[$columnName . '::date'] = DbExpr::create("``$data[$columnName]``::date");
break;
case Column::TYPE_TIME:
$conditions[$columnName . '::time'] = DbExpr::create("``$data[$columnName]``::time");
break;
case Column::TYPE_TIMESTAMP:
$conditions[] = DbExpr::create("`{$columnName}`::timestamp(0) = ``{$data[$columnName]}``::timestamp(0)");
break;
default:
$conditions[$columnName] = $data[$columnName];
}
}
if (!$user->fromDb($conditions)->existsInDb()) {
return false;
}
return $user;
} | php | {
"resource": ""
} |
q248329 | Router.error | validation | public function error(Callable $action = null)
{
if ($action) $this->errorAction = $action;
return $this->errorAction;
} | php | {
"resource": ""
} |
q248330 | Router.defaultHeader | validation | public function defaultHeader(array $headers = [])
{
$this->defaultHeaders = array_merge($this->defaultHeaders, $headers);
return $this->defaultHeaders;
} | php | {
"resource": ""
} |
q248331 | Router.removeDefaultHeader | validation | public function removeDefaultHeader($headers = "")
{
foreach ($headers as $header)
foreach ($this->defaultHeaders as $h => $v)
if ($header === $h) unset($this->defaultHeaders[$h]);
return $this->defaultHeaders;
} | php | {
"resource": ""
} |
q248332 | Router.match | validation | protected function match(Request $request)
{
foreach ($this->routes as $route)
{
if ($route->method() === $request->method() && $route->match($request->url()))
{
if ($action = $route->action())
{
try
{
$response = $action($request, $route->args());
if ($response !== false) return $response;
}
catch (AbortRouteException $abort)
{
return $abort->response();
}
}
else
// Match found but no action to perform
return null;
}
}
// No match found
return false;
} | php | {
"resource": ""
} |
q248333 | Router.add | validation | protected function add($url, $method, Callable $action)
{
$url = $this->base !== "" && $url === "/" ? $this->base : $this->base.$url;
$route = new Route($url, $method, $action);
$this->routes[] = $route;
return $route;
} | php | {
"resource": ""
} |
q248334 | InvoiceValidator.checkHierarchyIntegrity | validation | private function checkHierarchyIntegrity(InvoiceInterface $invoice)
{
// [ Invoice <-> Sale <-> Shipment ] integrity
if (null !== $shipment = $invoice->getShipment()) {
if ($invoice->getSale() !== $shipment->getSale()) {
throw new ValidationFailedException();
}
// Credit <-> Return
if (InvoiceTypes::isCredit($invoice) && !$shipment->isReturn()) {
throw new ValidationFailedException();
}
// Invoice <-> Shipment
if (InvoiceTypes::isInvoice($invoice) && $shipment->isReturn()) {
throw new ValidationFailedException();
}
}
} | php | {
"resource": ""
} |
q248335 | AbstractSaleItemListener.loadItem | validation | private function loadItem(Model\SaleItemInterface $item)
{
$item->getAdjustments()->toArray();
$children = $item->getChildren()->toArray();
foreach ($children as $child) {
$this->loadItem($child);
}
} | php | {
"resource": ""
} |
q248336 | AbstractSaleItemListener.throwIllegalOperationIfItemIsImmutable | validation | private function throwIllegalOperationIfItemIsImmutable(ResourceEventInterface $event)
{
if ($event->getHard()) {
return;
}
$item = $this->getSaleItemFromEvent($event);
// Stop if item is immutable.
if ($item->isImmutable()) {
throw new IllegalOperationException('ekyna_commerce.sale.message.immutable_element');
}
} | php | {
"resource": ""
} |
q248337 | Blocks.get | validation | public function get(string $name): Block {
if (isset($this->_blocks[$name]))
return $this->_blocks[$name];
$this->_blocks[$name] = new $this->block_class($name);
return $this->_blocks[$name];
} | php | {
"resource": ""
} |
q248338 | SubjectNormalizerHelper.normalizeStock | validation | public function normalizeStock(StockSubjectInterface $subject, $format = null, array $context = [])
{
$translator = $this->constantHelper->getTranslator();
$formatter = $this->getFormatter();
if (null !== $eda = $subject->getEstimatedDateOfArrival()) {
$eda = $formatter->date($eda);
} else {
$eda = $translator->trans('ekyna_core.value.undefined');
}
$stockUnits = $this->findStockUnits($subject);
return [
'mode_label' => $this->constantHelper->renderStockSubjectModeLabel($subject),
'mode_badge' => $this->constantHelper->renderStockSubjectModeBadge($subject),
'state_label' => $this->constantHelper->renderStockSubjectStateLabel($subject),
'state_badge' => $this->constantHelper->renderStockSubjectStateBadge($subject),
'in' => $formatter->number($subject->getInStock()),
'available' => $formatter->number($subject->getAvailableStock()),
'virtual' => $formatter->number($subject->getVirtualStock()),
'floor' => $formatter->number($subject->getStockFloor()),
'geocode' => $subject->getGeocode(),
'replenishment' => $formatter->number($subject->getReplenishmentTime()),
'eda' => $eda,
'moq' => $formatter->number($subject->getMinimumOrderQuantity()),
'quote_only' => $subject->isQuoteOnly()
? $translator->trans('ekyna_core.value.yes')
: $translator->trans('ekyna_core.value.no'),
'end_of_life' => $subject->isEndOfLife()
? $translator->trans('ekyna_core.value.yes')
: $translator->trans('ekyna_core.value.no'),
'stock_units' => $this->normalizer->normalize($stockUnits, $format, $context),
];
} | php | {
"resource": ""
} |
q248339 | SubjectNormalizerHelper.findStockUnits | validation | private function findStockUnits(StockSubjectInterface $subject)
{
/** @var StockUnitRepositoryInterface $repository */
$repository = $this->entityManager->getRepository($subject::getStockUnitClass());
/** @var StockUnitInterface[] $stockUnits */
$stockUnits = array_merge(
$repository->findNotClosedBySubject($subject),
$repository->findLatestClosedBySubject($subject)
);
// Sort by "created/closed at" date desc
usort($stockUnits, function (StockUnitInterface $a, StockUnitInterface $b) {
if ($a->getState() === StockUnitStates::STATE_CLOSED && $b->getState() !== StockUnitStates::STATE_CLOSED) {
return 1;
}
if ($a->getState() !== StockUnitStates::STATE_CLOSED && $b->getState() === StockUnitStates::STATE_CLOSED) {
return -1;
}
if ($a->getState() === StockUnitStates::STATE_CLOSED && $b->getState() === StockUnitStates::STATE_CLOSED) {
$aDate = $a->getClosedAt()->getTimestamp();
$bDate = $b->getClosedAt()->getTimestamp();
if ($aDate > $bDate) {
return -1;
}
if ($aDate < $bDate) {
return 1;
}
}
$aDate = $a->getCreatedAt()->getTimestamp();
$bDate = $b->getCreatedAt()->getTimestamp();
if ($aDate > $bDate) {
return -1;
}
if ($aDate < $bDate) {
return 1;
}
return 0;
});
return $stockUnits;
} | php | {
"resource": ""
} |
q248340 | PrioritizeHelper.ceilComparison | validation | private function ceilComparison(UnitCandidate $a, UnitCandidate $b, $property, $quantity)
{
if ($a->{$property} >= $quantity && $b->{$property} < $quantity) {
return -1;
}
if ($a->{$property} < $quantity && $b->{$property} >= $quantity) {
return 1;
}
return false;
} | php | {
"resource": ""
} |
q248341 | PrioritizeHelper.equalComparison | validation | private function equalComparison(UnitCandidate $a, UnitCandidate $b, $property, $quantity)
{
if ($a->{$property} == $quantity && $b->{$property} != $quantity) {
return -1;
}
if ($a->{$property} != $quantity && $b->{$property} == $quantity) {
return 1;
}
return false;
} | php | {
"resource": ""
} |
q248342 | DocumentTypes.getClasses | validation | static public function getClasses($type)
{
switch ($type) {
case static::TYPE_FORM:
return [CartInterface::class];
case static::TYPE_QUOTE:
return [QuoteInterface::class];
case static::TYPE_PROFORMA:
return [QuoteInterface::class, OrderInterface::class];
case static::TYPE_CONFIRMATION:
return [OrderInterface::class];
case static::TYPE_VOUCHER:
return [];
default:
throw new InvalidArgumentException("Unexpected type '$type'.");
}
} | php | {
"resource": ""
} |
q248343 | URL.site | validation | public static function site(string $uri = '', $protocol = null): string {
// Chop off possible scheme, host, port, user and pass parts
$path = preg_replace('~^[-a-z0-9+.]++://[^/]++/?~', '', trim($uri, '/'));
if (preg_match('/[^\x00-\x7F]/S', $path)) {
// Encode all non-ASCII characters, as per RFC 1738
$path = preg_replace_callback('~([^/]+)~', '\mii\util\URL::_rawurlencode_callback', $path);
}
// Concat the URL
return URL::base($protocol) . $path;
} | php | {
"resource": ""
} |
q248344 | URL.query | validation | public static function query(array $params = null, $use_get = null) {
if ($use_get) {
if ($params === NULL) {
// Use only the current parameters
$params = $_GET;
} else {
// Merge the current and new parameters
$params = Arr::merge($_GET, $params);
}
}
if (empty($params)) {
// No query parameters
return '';
}
// Note: http_build_query returns an empty string for a params array with only NULL values
$query = http_build_query($params, '', '&');
// Don't prepend '?' to an empty string
return ($query === '') ? '' : ('?' . $query);
} | php | {
"resource": ""
} |
q248345 | URL.title | validation | public static function title($title, $separator = '-', $ascii_only = FALSE) {
if ($ascii_only === TRUE) {
// Transliterate non-ASCII characters
$title = UTF8::transliterate_to_ascii($title);
// Remove all characters that are not the separator, a-z, 0-9, or whitespace
$title = preg_replace('![^' . preg_quote($separator) . 'a-z0-9\s]+!', '', strtolower($title));
} else {
// Remove all characters that are not the separator, letters, numbers, or whitespace
$title = preg_replace('![^' . preg_quote($separator) . '\pL\pN\s]+!u', '', UTF8::strtolower($title));
}
// Replace all separator characters and whitespace by a single separator
$title = preg_replace('![' . preg_quote($separator) . '\s]+!u', $separator, $title);
// Trim separators from the beginning and end
return trim($title, $separator);
} | php | {
"resource": ""
} |
q248346 | Config.onParse | validation | public function onParse($finalText) {
// if a specific post-parse function was defined, it is called
$func = $this->getParam('postParseFunction');
if (isset($func))
$finalText = $func($finalText);
// add footnotes' content if needed
if ($this->getParam('addFootnotes')) {
$footnotes = $this->getFootnotes();
if (!empty($footnotes))
$finalText .= "\n" . $footnotes;
}
// ???
$finalText .= str_repeat('</section>', count($this->_sectionLevel));
return ($finalText);
} | php | {
"resource": ""
} |
q248347 | PaymentCalculator.calculateTotalByState | validation | protected function calculateTotalByState(PaymentSubjectInterface $subject, $state)
{
PaymentStates::isValidState($state, true);
$currency = $subject->getCurrency()->getCode();
$total = 0;
foreach ($subject->getPayments() as $payment) {
if ($payment->getState() === $state) {
$total += $this->convertPaymentAmount($payment, $currency);
}
}
return $total;
} | php | {
"resource": ""
} |
q248348 | Money.round | validation | static public function round($amount, $currency)
{
$precision = static::getPrecision($currency);
$roundingIncrement = static::getRoundingIncrement($currency);
$amount = round($amount, $precision, \PHP_ROUND_HALF_EVEN);
if (0 < $roundingIncrement && 0 < $precision) {
$roundingFactor = $roundingIncrement / pow(10, $precision);
$amount = round($amount / $roundingFactor) * $roundingFactor;
}
return $amount;
} | php | {
"resource": ""
} |
q248349 | Money.getPrecision | validation | static public function getPrecision($currency)
{
if (isset(static::$precisions[$currency])) {
return static::$precisions[$currency];
}
return static::$precisions[$currency] = static::getCurrencyBundle()->getFractionDigits($currency);
} | php | {
"resource": ""
} |
q248350 | Money.getRoundingIncrement | validation | static public function getRoundingIncrement($currency)
{
if (isset(static::$increments[$currency])) {
return static::$increments[$currency];
}
return static::$increments[$currency] = static::getCurrencyBundle()->getRoundingIncrement($currency);
} | php | {
"resource": ""
} |
q248351 | TicketEventListener.getTicketFromEvent | validation | protected function getTicketFromEvent(ResourceEventInterface $event)
{
$ticket = $event->getResource();
if (!$ticket instanceof TicketInterface) {
throw new UnexpectedValueException("Expected instance of " . TicketInterface::class);
}
return $ticket;
} | php | {
"resource": ""
} |
q248352 | StockAdjustmentReasons.isValidReason | validation | static public function isValidReason($reason, $throw = true)
{
if (in_array($reason, static::getReasons(), true)) {
return true;
}
if ($throw) {
throw new InvalidArgumentException("Invalid stock adjustment reason.");
}
return false;
} | php | {
"resource": ""
} |
q248353 | AuthActions.isAuthorized | validation | public function isAuthorized($user, $plugin, $controller, $action) {
$isAuthorized = false;
if ($plugin) {
$plugin = Inflector::camelize($plugin);
}
if ($this->isPublicAction($plugin, $controller, $action)) {
$isAuthorized = true;
} elseif (isset($user['role']) && !empty($controller) && !empty($action)) {
if ($this->_options['camelizedControllerNames']) {
$controller = Inflector::camelize($controller);
} else {
$controller = Inflector::underscore($controller);
}
$key = $controller;
if (!empty($plugin)) {
$key = $plugin . '.' . $key;
}
if (isset($this->_rightsConfig[$key]['*']) && $this->_rightsConfig[$key]['*'] == '*') {
$isAuthorized = true;
} elseif (isset($this->_rightsConfig[$key]['*'])
&& in_array($user['role'], $this->_rightsConfig[$key]['*'])) {
$isAuthorized = true;
} elseif (isset($this->_rightsConfig[$key][$action])
&& in_array($user['role'], $this->_rightsConfig[$key][$action])) {
$isAuthorized = true;
}
}
return $isAuthorized;
} | php | {
"resource": ""
} |
q248354 | AuthActions.urlAllowed | validation | public function urlAllowed($user, $url) {
if (empty($url)) {
return false;
}
if (is_array($url)) {
// prevent plugin confusion
$url = Hash::merge([
'plugin' => null
], $url);
$url = Router::url($url);
// strip off the base path
$url = Router::normalize($url);
}
$route = Router::parse($url);
if (empty($route['controller']) || empty($route['action'])) {
return false;
}
return $this->isAuthorized($user, $route['plugin'], $route['controller'], $route['action']);
} | php | {
"resource": ""
} |
q248355 | StockSubjectModes.isBetterMode | validation | static public function isBetterMode($modeA, $modeB)
{
// TODO Find something more explicit than 'better' (availability ?)
// TODO assert valid states ?
if ($modeA === static::MODE_DISABLED) {
return $modeB !== static::MODE_DISABLED;
} elseif ($modeA === static::MODE_JUST_IN_TIME) {
return in_array($modeB, [static::MODE_MANUAL, static::MODE_AUTO], true);
}
return false;
} | php | {
"resource": ""
} |
q248356 | AbstractSaleRepository.getOneQueryBuilder | validation | protected function getOneQueryBuilder($alias = null, $indexBy = null)
{
return $this
->createQueryBuilder($alias, $indexBy)
->select(
$alias,
'customer',
'customer_group',
'invoice_address',
'delivery_address',
'shipment_method',
'currency'
)
->leftJoin($alias . '.customer', 'customer')
->leftJoin($alias . '.customerGroup', 'customer_group')
->leftJoin($alias . '.invoiceAddress', 'invoice_address')
->leftJoin($alias . '.deliveryAddress', 'delivery_address')
->leftJoin($alias . '.shipmentMethod', 'shipment_method')
->leftJoin($alias . '.currency', 'currency')
->setMaxResults(1);
} | php | {
"resource": ""
} |
q248357 | OutstandingWatcher.watch | validation | public function watch(Repository\PaymentRepositoryInterface $paymentRepository)
{
if (null === $term = $this->termRepository->findLongest()) {
return false;
}
$today = new \DateTime();
$today->setTime(0, 0, 0);
$fromDate = clone $today;
$fromDate->modify('-1 year');
$states = [Model\PaymentStates::STATE_AUTHORIZED, Model\PaymentStates::STATE_CAPTURED];
/** @var Model\PaymentMethodInterface $method */
$method = $this->methodRepository->findOneBy([
'factoryName' => Constants::FACTORY_NAME,
]);
if (!$method || !$method->isOutstanding()) {
return false;
}
$result = false;
$payments = $paymentRepository->findByMethodAndStates($method, $states, $fromDate);
foreach ($payments as $payment) {
$sale = $payment->getSale();
// Sale may not have a outstanding limit date
if (null === $date = $sale->getOutstandingDate()) {
continue;
}
// If outstanding limit date is past
$diff = $date->diff($today);
if (0 < $diff->days && !$diff->invert) {
$payment->setState(Model\PaymentStates::STATE_EXPIRED);
$this->persist($payment);
$result = true;
}
}
return $result;
} | php | {
"resource": ""
} |
q248358 | SupplierProductRepository.getFindBySubjectQuery | validation | protected function getFindBySubjectQuery()
{
if (null !== $this->findBySubjectQuery) {
return $this->findBySubjectQuery;
}
$qb = $this->createFindBySubjectQueryBuilder();
return $this->findBySubjectQuery = $qb->getQuery();
} | php | {
"resource": ""
} |
q248359 | SupplierProductRepository.getGetAvailableSumBySubjectQuery | validation | protected function getGetAvailableSumBySubjectQuery()
{
if (null !== $this->getAvailableSumBySubjectQuery) {
return $this->getAvailableSumBySubjectQuery;
}
$as = $this->getAlias();
$qb = $this->createFindBySubjectQueryBuilder();
$qb
->andWhere($qb->expr()->gte($as . '.availableStock', 0))
->select('SUM(' . $as . '.availableStock) as available');
return $this->getAvailableSumBySubjectQuery = $qb->getQuery();
} | php | {
"resource": ""
} |
q248360 | SupplierProductRepository.getGetMinEdaBySubjectQuery | validation | protected function getGetMinEdaBySubjectQuery()
{
if (null !== $this->getMinEdaBySubjectQuery) {
return $this->getMinEdaBySubjectQuery;
}
$as = $this->getAlias();
$qb = $this->createFindBySubjectQueryBuilder();
$qb
->andWhere($qb->expr()->isNotNull($as . '.estimatedDateOfArrival'))
->andWhere($qb->expr()->orX(
$qb->expr()->gte($as . '.orderedStock', 0),
$qb->expr()->gte($as . '.availableStock', 0)
))
->select('MIN(' . $as . '.estimatedDateOfArrival) as eda');
return $this->getMinEdaBySubjectQuery = $qb->getQuery();
} | php | {
"resource": ""
} |
q248361 | SupplierProductRepository.getFindBySubjectAndSupplierQuery | validation | protected function getFindBySubjectAndSupplierQuery()
{
if (null !== $this->findBySubjectAndSupplierQuery) {
return $this->findBySubjectAndSupplierQuery;
}
$qb = $this->createFindBySubjectQueryBuilder();
return $this->findBySubjectAndSupplierQuery = $qb
->andWhere($qb->expr()->eq($this->getAlias() . '.supplier', ':supplier'))
->getQuery();
} | php | {
"resource": ""
} |
q248362 | SupplierProductRepository.createFindBySubjectQueryBuilder | validation | private function createFindBySubjectQueryBuilder()
{
$as = $this->getAlias();
$qb = $this->createQueryBuilder();
return $qb
->andWhere($qb->expr()->eq($as . '.subjectIdentity.provider', ':provider'))
->andWhere($qb->expr()->eq($as . '.subjectIdentity.identifier', ':identifier'));
} | php | {
"resource": ""
} |
q248363 | PeskyCmfLanguageDetectorServiceProvider.detectAndApplyLanguage | validation | protected function detectAndApplyLanguage() {
if ($this->config('autodetect', true)) {
/** @var LanguageDetector $detector */
$detector = $this->getLanguageDetector();
$language = $detector->getLanguageFromCookie();
if (!$language || strlen($language) > 5 || !in_array($language, $this->getSupportedLanguages(), true)) {
$language = $detector->getDriver()->detect();
if (!$language || strlen($language) > 5) {
$language = $this->request->getDefaultLocale();
}
}
$this->applyNewLanguage($language, true);
}
} | php | {
"resource": ""
} |
q248364 | TicketMessageEventListener.updateTicket | validation | protected function updateTicket(TicketMessageInterface $message)
{
$ticket = $message->getTicket()->setUpdatedAt(new \DateTime());
if ($message->isLatest() && ($ticket->getState() !== TicketStates::STATE_CLOSED)) {
if ($message->isCustomer()) {
if ($ticket->getState() === TicketStates::STATE_PENDING) {
$ticket->setState(TicketStates::STATE_OPENED);
}
} elseif ($ticket->getState() === TicketStates::STATE_OPENED) {
$ticket->setState(TicketStates::STATE_PENDING);
}
}
$this->persistenceHelper->persistAndRecompute($ticket, false);
} | php | {
"resource": ""
} |
q248365 | TicketMessageEventListener.getMessageFromEvent | validation | protected function getMessageFromEvent(ResourceEventInterface $event)
{
$message = $event->getResource();
if (!$message instanceof TicketMessageInterface) {
throw new UnexpectedValueException("Expected instance of " . TicketMessageInterface::class);
}
return $message;
} | php | {
"resource": ""
} |
q248366 | AddressUtil.equals | validation | static public function equals(AddressInterface $source, AddressInterface $target)
{
if (!($source->getCompany() === $target->getCompany()
&& $source->getGender() === $target->getGender()
&& $source->getFirstName() === $target->getFirstName()
&& $source->getLastName() === $target->getLastName()
&& $source->getStreet() === $target->getStreet()
&& $source->getComplement() === $target->getComplement()
&& $source->getSupplement() === $target->getSupplement()
&& $source->getExtra() === $target->getExtra()
&& $source->getCity() === $target->getCity()
&& $source->getPostalCode() === $target->getPostalCode()
&& $source->getDigicode1() === $target->getDigicode1()
&& $source->getDigicode2() === $target->getDigicode2()
&& $source->getIntercom() === $target->getIntercom())) {
return false;
}
$sourceCountryId = $source->getCountry() ? $source->getCountry()->getId() : null;
$targetCountryId = $target->getCountry() ? $target->getCountry()->getId() : null;
if ($sourceCountryId != $targetCountryId) {
return false;
}
$sourceStateId = $source->getState() ? $source->getState()->getId() : null;
$targetStateId = $target->getState() ? $target->getState()->getId() : null;
if ($sourceStateId != $targetStateId) {
return false;
}
$sourcePhone = (string) $source->getPhone();
$targetPhone = (string) $target->getPhone();
if ($sourcePhone !== $targetPhone) {
return false;
}
$sourceMobile = (string) $source->getMobile();
$targetMobile = (string) $target->getMobile();
if ($sourceMobile !== $targetMobile) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q248367 | AddressUtil.copy | validation | static public function copy(AddressInterface $source, AddressInterface $target)
{
$target
->setCompany($source->getCompany())
->setGender($source->getGender())
->setFirstName($source->getFirstName())
->setLastName($source->getLastName())
->setStreet($source->getStreet())
->setComplement($source->getComplement())
->setSupplement($source->getSupplement())
->setExtra($source->getExtra())
->setCity($source->getCity())
->setPostalCode($source->getPostalCode())
->setCountry($source->getCountry())
->setState($source->getState())
->setDigicode1($source->getDigicode1())
->setDigicode2($source->getDigicode2())
->setIntercom($source->getIntercom())
->setLatitude($source->getLatitude())
->setLongitude($source->getLongitude());
if (is_object($phone = $source->getPhone())) {
$target->setPhone(clone $phone);
} else {
$target->setPhone($phone);
}
if (is_object($mobile = $source->getMobile())) {
$target->setMobile(clone $mobile);
} else {
$target->setMobile($mobile);
}
} | php | {
"resource": ""
} |
q248368 | VatNumberResult.getDetails | validation | public function getDetails()
{
return [
'valid' => $this->valid,
'country' => $this->country,
'number' => $this->number,
'name' => $this->name,
'address' => $this->address,
'date' => $this->date,
];
} | php | {
"resource": ""
} |
q248369 | OpeningHour.addRanges | validation | public function addRanges(string $from, string $to)
{
$this->ranges[] = [
'from' => $from,
'to' => $to,
];
return $this;
} | php | {
"resource": ""
} |
q248370 | NotifiableTrait.hasNotifications | validation | public function hasNotifications($type = null)
{
if (null !== $type) {
NotificationTypes::isValidType($type);
return $this->getNotifications($type)->count();
}
return 0 < $this->notifications->count();
} | php | {
"resource": ""
} |
q248371 | NotifiableTrait.getNotifications | validation | public function getNotifications($type = null)
{
if (null !== $type) {
NotificationTypes::isValidType($type);
return $this
->notifications
->filter(function (NotificationInterface $n) use ($type) {
return $n->getType() === $type;
});
}
return $this->notifications;
} | php | {
"resource": ""
} |
q248372 | SupplierOrderListener.updateTotals | validation | protected function updateTotals(SupplierOrderInterface $order)
{
$changed = false;
$tax = $this->calculator->calculatePaymentTax($order);
if ($tax != $order->getTaxTotal()) {
$order->setTaxTotal($tax);
$changed = true;
}
$payment = $this->calculator->calculatePaymentTotal($order);
if ($payment != $order->getPaymentTotal()) {
$order->setPaymentTotal($payment);
$changed = true;
}
if (null !== $order->getCarrier()) {
$forwarder = $this->calculator->calculateForwarderTotal($order);
if ($forwarder != $order->getForwarderTotal()) {
$order->setForwarderTotal($forwarder);
$changed = true;
}
} else {
if (0 != $order->getForwarderFee()) {
$order->setForwarderFee(0);
$changed = true;
}
if (0 != $order->getCustomsTax()) {
$order->setCustomsTax(0);
$changed = true;
}
if (0 != $order->getCustomsVat()) {
$order->setCustomsVat(0);
$changed = true;
}
if (0 != $order->getForwarderTotal()) {
$order->setForwarderTotal(0);
$changed = true;
}
if (null !== $order->getForwarderDate()) {
$order->setForwarderDate(null);
$changed = true;
}
if (null !== $order->getForwarderDueDate()) {
$order->setForwarderDueDate(null);
$changed = true;
}
}
return $changed;
} | php | {
"resource": ""
} |
q248373 | SupplierOrderListener.updateExchangeRate | validation | protected function updateExchangeRate(SupplierOrderInterface $order)
{
// TODO Remove when supplier order payments will be implemented.
if (null !== $order->getExchangeRate()) {
return false;
}
if (!SupplierOrderStates::isStockableState($order->getState())) {
return false;
}
$date = new \DateTime();
$rate = $this->currencyConverter->getRate(
$this->currencyConverter->getDefaultCurrency(),
$order->getCurrency()->getCode(),
$date
);
$order
->setExchangeRate($rate)
->setExchangeDate($date);
return true;
} | php | {
"resource": ""
} |
q248374 | SupplierOrderListener.getSupplierOrderFromEvent | validation | protected function getSupplierOrderFromEvent(ResourceEventInterface $event)
{
$order = $event->getResource();
if (!$order instanceof SupplierOrderInterface) {
throw new InvalidArgumentException("Expected instance of SupplierOrderInterface.");
}
return $order;
} | php | {
"resource": ""
} |
q248375 | InvoiceBuilder.findOrCreateGoodLine | validation | public function findOrCreateGoodLine(
Invoice\InvoiceInterface $invoice,
Common\SaleItemInterface $item,
$available,
$expected = null
) {
$line = null;
if (0 >= $available) {
return $line;
}
// Existing line lookup
foreach ($invoice->getLinesByType(Document\DocumentLineTypes::TYPE_GOOD) as $invoiceLine) {
if ($invoiceLine->getSaleItem() === $item) {
$line = $invoiceLine;
}
}
// Not found, create it
if (null === $line) {
$line = $this->createLine($invoice);
$line
->setInvoice($invoice)
->setType(Document\DocumentLineTypes::TYPE_GOOD)
->setSaleItem($item)
->setDesignation($item->getDesignation())
->setDescription($item->getDescription())
->setReference($item->getReference());
}
// Set available and expected quantity
$line->setAvailable($available);
$line->setExpected($expected);
if (Invoice\InvoiceTypes::isInvoice($invoice) && null === $invoice->getId()) {
// Set default quantity for new non return shipment items
$line->setQuantity(min($expected, $available));
}
return $line;
} | php | {
"resource": ""
} |
q248376 | Margin.getPercent | validation | public function getPercent(): float
{
$amount = $this->getAmount();
if (0 < $this->sellingPrice) {
return round($amount * 100 / $this->sellingPrice, 2);
}
return 0;
} | php | {
"resource": ""
} |
q248377 | Margin.merge | validation | public function merge(Margin $margin): void
{
$this->purchaseCost += $margin->getPurchaseCost();
$this->sellingPrice += $margin->getSellingPrice();
$this->average = $this->average || $margin->isAverage();
} | php | {
"resource": ""
} |
q248378 | DefaultNumberGenerator.readNumber | validation | private function readNumber()
{
// Open
if (false === $this->handle = fopen($this->filePath, 'c+')) {
throw new RuntimeException("Failed to open file {$this->filePath}.");
}
// Exclusive lock
if (!flock($this->handle, LOCK_EX)) {
throw new RuntimeException("Failed to lock file {$this->filePath}.");
}
return fread($this->handle, $this->length);
} | php | {
"resource": ""
} |
q248379 | SaleStepValidator.getConstraintsForStep | validation | protected function getConstraintsForStep($step)
{
$constraints = [new Valid()];
if ($step === static::SHIPMENT_STEP) {
$constraints[] = new Constraints\SaleShipmentStep();
}
if ($step === static::PAYMENT_STEP) {
$constraints[] = new Constraints\SaleShipmentStep();
$constraints[] = new Constraints\RelayPoint();
$constraints[] = new Constraints\SalePaymentStep();
}
return $constraints;
} | php | {
"resource": ""
} |
q248380 | SaleStepValidator.getGroupsForStep | validation | protected function getGroupsForStep($step)
{
$groups = ['Default'];
if ($step === static::CHECKOUT_STEP) {
$groups[] = 'Checkout';
$groups[] = 'Identity';
$groups[] = 'Availability';
} elseif ($step === static::SHIPMENT_STEP) {
$groups[] = 'Availability';
}
return $groups;
} | php | {
"resource": ""
} |
q248381 | SupplierDeliveryItemListener.handleQuantityChange | validation | protected function handleQuantityChange(SupplierDeliveryItemInterface $item)
{
$changeSet = $this->persistenceHelper->getChangeSet($item);
// Delta quantity (difference between new and old)
if (null === $orderItem = $item->getOrderItem()) {
throw new RuntimeException("Failed to retrieve order item.");
}
if (null !== $stockUnit = $orderItem->getStockUnit()) {
// TODO use packaging format
if (0 != $deltaQuantity = floatval($changeSet['quantity'][1]) - floatval($changeSet['quantity'][0])) {
// Update stock unit received quantity
$this->stockUnitUpdater->updateReceived($stockUnit, $deltaQuantity, true);
}
} elseif ($orderItem->hasSubjectIdentity()) {
throw new RuntimeException("Failed to retrieve stock unit.");
}
// Trigger the supplier order update
if (null === $order = $orderItem->getOrder()) {
throw new RuntimeException("Failed to retrieve order.");
}
$this->scheduleSupplierOrderContentChangeEvent($order);
} | php | {
"resource": ""
} |
q248382 | PayumBuilderPass.registerFactories | validation | private function registerFactories(ContainerBuilder $container)
{
$defaultConfig = [];
$builder = $container->getDefinition('payum.builder');
$builder->addMethodCall('addGatewayFactoryConfig', [
Offline\Constants::FACTORY_NAME,
$defaultConfig,
]);
$builder->addMethodCall('addGatewayFactory', [
Offline\Constants::FACTORY_NAME,
[Offline\OfflineGatewayFactory::class, 'build'],
]);
$builder->addMethodCall('addGatewayFactoryConfig', [
Outstanding\Constants::FACTORY_NAME,
$defaultConfig,
]);
$builder->addMethodCall('addGatewayFactory', [
Outstanding\Constants::FACTORY_NAME,
[Outstanding\OutstandingGatewayFactory::class, 'build'],
]);
$builder->addMethodCall('addGatewayFactoryConfig', [
Credit\Constants::FACTORY_NAME,
$defaultConfig,
]);
$builder->addMethodCall('addGatewayFactory', [
Credit\Constants::FACTORY_NAME,
[Credit\CreditGatewayFactory::class, 'build'],
]);
} | php | {
"resource": ""
} |
q248383 | PayumBuilderPass.registerActions | validation | private function registerActions(ContainerBuilder $container)
{
// Payzen convert action
if (class_exists('Ekyna\Component\Payum\Payzen\PayzenGatewayFactory')) {
// Convert action
$definition = new Definition('Ekyna\Component\Commerce\Bridge\Payum\Payzen\Action\ConvertAction');
$definition->addTag('payum.action', ['factory' => 'payzen', 'prepend' => true]);
$container->setDefinition('ekyna_commerce.payum.action.payzen.convert_payment', $definition);
// Fraud level action
$definition = new Definition('Ekyna\Component\Commerce\Bridge\Payum\Payzen\Action\FraudLevelAction');
$definition->addTag('payum.action', ['factory' => 'payzen', 'prepend' => true]);
$container->setDefinition('ekyna_commerce.payum.action.payzen.fraud_level', $definition);
}
// Sips
if (class_exists('Ekyna\Component\Payum\Sips\SipsGatewayFactory')) {
// Convert action
$definition = new Definition('Ekyna\Component\Commerce\Bridge\Payum\Sips\Action\ConvertAction');
$definition->addTag('payum.action', ['factory' => 'atos_sips', 'prepend' => true]);
$container->setDefinition('ekyna_commerce.payum.action.sips.convert_payment', $definition);
}
// PayPal EC NVP
if (class_exists('Payum\Paypal\ExpressCheckout\Nvp\PaypalExpressCheckoutGatewayFactory')) {
// Convert action
$definition = new Definition('Ekyna\Component\Commerce\Bridge\Payum\Paypal\Action\EcNvpConvertAction');
$definition->setArgument(0, new Reference('ekyna_commerce.common.amount_calculator'));
if ($container->has('ekyna_setting.manager') && class_exists('Ekyna\Bundle\AdminBundle\Settings\GeneralSettingsSchema')) {
$definition->setArgument(1, new Expression(
"service('ekyna_setting.manager').getParameter('general.site_name')"
));
}
$definition->addTag('payum.action', ['factory' => 'paypal_express_checkout', 'prepend' => true]);
$container->setDefinition('ekyna_commerce.payum.action.paypal_ec_nvp.convert_payment', $definition);
}
// Global actions
$actions = [
'capture_payment' => Action\CaptureAction::class,
'notify_payment' => Action\NotifyAction::class,
'status_payment' => Action\StatusAction::class,
];
foreach ($actions as $name => $class) {
$definition = new Definition($class);
$definition->addTag('payum.action', ['all' => true, 'prepend' => true]);
$container->setDefinition('ekyna_commerce.payum.action.' . $name, $definition);
}
} | php | {
"resource": ""
} |
q248384 | StockAssignmentDispatcher.sortAssignments | validation | private function sortAssignments(array $assignments, $direction = SORT_DESC)
{
usort($assignments, function (StockAssignmentInterface $a, StockAssignmentInterface $b) use ($direction) {
$aDate = $a->getSaleItem()->getSale()->getCreatedAt();
$bDate = $b->getSaleItem()->getSale()->getCreatedAt();
if ($aDate == $bDate) {
return 0;
}
if ($direction === SORT_ASC) {
return $aDate < $bDate ? -1 : 1;
}
return $aDate > $bDate ? -1 : 1;
});
return $assignments;
} | php | {
"resource": ""
} |
q248385 | Iac_Profile_Settings.remove_author_meta_values | validation | public static function remove_author_meta_values() {
global $blog_id;
if ( isset( $blog_id ) && ! empty( $blog_id ) ) {
$blogusers = get_users( array( 'blog_id' => $blog_id ) );
foreach ( $blogusers as $user_object ) {
delete_user_meta( $user_object->ID, 'post_subscription' );
delete_user_meta( $user_object->ID, 'comment_subscription' );
}
}
} | php | {
"resource": ""
} |
q248386 | Iac_Profile_Settings.add_custom_profile_fields | validation | public function add_custom_profile_fields( $user ) {
$user_settings = apply_filters( 'iac_get_user_settings', array(), $user->ID );
$nonce = wp_create_nonce( 'iac_user_settings' );
?>
<h3><?php _e( 'Informer?', $this->get_textdomain() ); ?></h3>
<table class="form-table">
<tr id="post_subscription">
<th>
<label for="post_subscription_checkbox"><?php _e( 'Posts subscription', $this->get_textdomain() ); ?></label>
</th>
<td>
<input type="checkbox" id="post_subscription_checkbox" name="post_subscription" value="1"
<?php checked( '1', $user_settings[ 'inform_about_posts' ] ); ?> />
<span class="description"><?php _e( 'Inform about new posts via e-mail, without your own posts.', $this->get_textdomain() ); ?></span>
</td>
</tr>
<tr id="comment_subscription">
<th>
<label for="comment_subscription_checkbox"><?php _e( 'Comments subscription', $this->get_textdomain() ); ?></label>
</th>
<td>
<input type="checkbox" id="comment_subscription_checkbox" name="comment_subscription" value="1"
<?php checked( '1', $user_settings[ 'inform_about_comments' ] ); ?> />
<span class="description"><?php _e( 'Inform about new comments via e-mail, without your own comments.', $this->get_textdomain() ); ?></span>
<input type="hidden" name="iac_nonce" value="<?php echo $nonce;?>" />
</td>
</tr>
</table>
<?php } | php | {
"resource": ""
} |
q248387 | Iac_Profile_Settings.save_custom_profile_fields | validation | public function save_custom_profile_fields( $user_id ) {
if ( 'POST' !== $_SERVER[ 'REQUEST_METHOD' ] || ! isset( $_POST[ 'iac_nonce' ] ) ) {
return;
}
if ( ! wp_verify_nonce( $_POST[ 'iac_nonce' ], 'iac_user_settings' ) ) {
return;
}
do_action(
'iac_save_user_settings',
$user_id,
isset( $_POST[ 'post_subscription' ] )
? $_POST[ 'post_subscription' ]
: NULL
,
isset( $_POST[ 'comment_subscription' ] )
? $_POST[ 'comment_subscription' ]
: NULL
);
} | php | {
"resource": ""
} |
q248388 | Iac_Profile_Settings.get_user_settings | validation | public function get_user_settings( $default = array(), $user_id = NULL ) {
if ( ! $user_id )
return $default;
$default_opt_in = apply_filters( 'iac_default_opt_in', FALSE );
$default = $default_opt_in
? '1'
: '0';
$settings = array(
'inform_about_posts' => get_user_meta( $user_id, 'post_subscription', TRUE ),
'inform_about_comments' => get_user_meta( $user_id, 'comment_subscription', TRUE )
);
foreach( $settings as $k => $v ) {
if ( '' === $v )
$settings[ $k ] = $default;
}
return $settings;
} | php | {
"resource": ""
} |
q248389 | Price.getTotal | validation | public function getTotal($discounted = true)
{
$base = $this->base;
if ($discounted && $this->hasDiscounts()) {
foreach ($this->discounts as $discount) {
$base -= $this->calculateAdjustment($discount, $base);
}
}
$total = $base;
if (!empty($this->taxes) && $this->mode === VatDisplayModes::MODE_ATI) {
foreach ($this->taxes as $tax) {
$total += $this->calculateAdjustment($tax, $base);
}
}
return $total;
} | php | {
"resource": ""
} |
q248390 | Price.calculateAdjustment | validation | private function calculateAdjustment(AdjustmentDataInterface $adjustment, $base)
{
if ($adjustment->getMode() === AdjustmentModes::MODE_PERCENT) {
return Money::round($base * $adjustment->getAmount() / 100, $this->currency);
}
if ($adjustment->getMode() === AdjustmentModes::MODE_FLAT) {
return $adjustment->getAmount();
}
throw new InvalidArgumentException("Unexpected adjustment mode.");
} | php | {
"resource": ""
} |
q248391 | SubjectIdentity.clear | validation | public function clear()
{
$this->provider = null;
$this->identifier = null;
$this->subject = null;
} | php | {
"resource": ""
} |
q248392 | SubjectIdentity.equals | validation | public function equals(SubjectIdentity $identity)
{
return $this->provider === $identity->getProvider()
&& $this->identifier === $identity->getIdentifier();
} | php | {
"resource": ""
} |
q248393 | SubjectIdentity.copy | validation | public function copy(SubjectIdentity $identity)
{
$this->provider = $identity->getProvider();
$this->identifier = $identity->getIdentifier();
} | php | {
"resource": ""
} |
q248394 | ACL.add_rule | validation | public function add_rule($access, $role, $action): void {
$roles = (array)$role;
foreach ($roles as $r) {
$action = (array)$action;
foreach ($action as $a) {
$this->_rules[$r][$a] = $access;
}
}
} | php | {
"resource": ""
} |
q248395 | ACL.match | validation | protected function match($role, $action): bool {
$roles = $actions = ['*'];
$allow = false;
if ($role != '*')
array_unshift($roles, $role);
if ($action != '*')
array_unshift($actions, $action);
// Ищем наиболее подходящее правило. Идем от частного к общему.
foreach ($roles as $_role) {
foreach ($actions as $_action) {
if (isset($this->_rules[$_role][$_action])) {
$allow = $this->_rules[$_role][$_action];
break 2;
}
}
}
return $allow === true;
} | php | {
"resource": ""
} |
q248396 | StockSubjectUpdater.nullDateIfLowerThanToday | validation | private function nullDateIfLowerThanToday(\DateTime $eda = null)
{
if (null === $eda) {
return null;
}
$today = new \DateTime();
$today->setTime(0, 0, 0);
if ($eda < $today) {
return null;
}
return $eda;
} | php | {
"resource": ""
} |
q248397 | StockSubjectUpdater.setSubjectData | validation | private function setSubjectData(
StockSubjectInterface $subject,
$inStock = .0,
$availableStock = .0,
$virtualStock = .0,
\DateTime $eda = null
) {
$changed = false;
if ($inStock != $subject->getInStock()) { // TODO use packaging format (bccomp for float)
$subject->setInStock($inStock);
$changed = true;
}
if ($availableStock != $subject->getAvailableStock()) { // TODO use packaging format (bccomp for float)
$subject->setAvailableStock($availableStock);
$changed = true;
}
if ($virtualStock != $subject->getVirtualStock()) { // TODO use packaging format (bccomp for float)
$subject->setVirtualStock($virtualStock);
$changed = true;
}
if ($eda !== $subject->getEstimatedDateOfArrival()) {
$subject->setEstimatedDateOfArrival($eda);
$changed = true;
}
return $changed;
} | php | {
"resource": ""
} |
q248398 | StockSubjectUpdater.setSubjectState | validation | private function setSubjectState(StockSubjectInterface $subject, $state)
{
if ($subject->getStockState() != $state) {
$subject->setStockState($state);
return true;
}
return false;
} | php | {
"resource": ""
} |
q248399 | Expression.compile | validation | public function compile(Database $db = NULL): string {
if ($db === null) {
// Get the database instance
$db = \Mii::$app->db;
}
$value = $this->value();
if (!empty($this->_parameters)) {
// Quote all of the parameter values
$params = array_map([$db, 'quote'], $this->_parameters);
// Replace the values in the expression
$value = strtr($value, $params);
}
return $value;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.