_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q257900
Address.toString
test
public function toString($separator = ', ') { $fields = array( $this->Company, $this->getName(), $this->Address, $this->AddressLine2, $this->City, $this->State, $this->PostalCode, $this->Country ); $this->extend('updateToString', $fields); return implode($separator, array_filter($fields)); }
php
{ "resource": "" }
q257901
ShopUserInfo.getAddress
test
public function getAddress() { $address = null; if ($data = $this->getLocationData()) { $address = Address::create(); $address->update($data); $address->ID = 0; //ensure not in db } return $address; }
php
{ "resource": "" }
q257902
CartPageController.CartForm
test
public function CartForm() { $cart = $this->Cart(); if (!$cart) { return false; } $form = CartForm::create($this, 'CartForm', $cart); $this->extend('updateCartForm', $form); return $form; }
php
{ "resource": "" }
q257903
Weight.value
test
public function value($subtotal = 0) { $totalWeight = $this->Weight(); if (!$totalWeight) { return $this->Amount = 0; } $amount = 0; $table = $this->config()->weight_cost; if (!empty($table) && is_array($table)) { // ensure table is sorted ksort($table, SORT_NUMERIC); // set the amount to the highest value. In case the weight is higher than the max value in // the table, use the highest shipping cost and not 0! $amount = end($table); reset($table); foreach ($table as $weight => $cost) { if ($totalWeight <= $weight) { $amount = $cost; break; } } } return $this->Amount = $amount; }
php
{ "resource": "" }
q257904
Weight.Weight
test
public function Weight() { if ($this->weight) { return $this->weight; } $weight = 0; $order = $this->Order(); if ($order && $orderItems = $order->Items()) { foreach ($orderItems as $orderItem) { if ($product = $orderItem->Product()) { $weight = $weight + ($product->Weight * $orderItem->Quantity); } } } return $this->weight = $weight; }
php
{ "resource": "" }
q257905
OrderItemList.Sum
test
public function Sum($field, $onproduct = false) { $total = 0; foreach ($this->getIterator() as $item) { $quantity = ($field === 'Quantity') ? 1 : $item->Quantity; if (!$onproduct) { $total += $item->$field * $quantity; } elseif ($item->hasMethod($field)) { $total += $item->$field() * $quantity; } elseif ($product = $item->Product()) { $total += $product->$field * $quantity; } } return $total; }
php
{ "resource": "" }
q257906
OrderItemList.SubTotal
test
public function SubTotal() { $result = 0; foreach ($this->getIterator() as $item) { $result += $item->Total(); } return $result; }
php
{ "resource": "" }
q257907
Variation.onBeforeWrite
test
public function onBeforeWrite() { parent::onBeforeWrite(); if (isset($_POST['ProductAttributes']) && is_array($_POST['ProductAttributes'])) { $this->AttributeValues()->setByIDList(array_values($_POST['ProductAttributes'])); } $img = $this->Image(); if ($img && $img->exists()) { $img->doPublish(); } }
php
{ "resource": "" }
q257908
CheckoutPageController.getViewer
test
public function getViewer($action) { if (CheckoutPage::config()->first_step && $action == 'index') { $action = CheckoutPage::config()->first_step; } return parent::getViewer($action); }
php
{ "resource": "" }
q257909
OrderItem.Product
test
public function Product($forcecurrent = false) { //TODO: this might need some unit testing to make sure it compliles with comment description //ie use live if in cart (however I see no logic for checking cart status) if ($this->ProductID && $this->ProductVersion && !$forcecurrent) { return Versioned::get_version(Product::class, $this->ProductID, $this->ProductVersion); } elseif ($this->ProductID && $product = Versioned::get_one_by_stage( Product::class, 'Live', '"SilverShop_Product"."ID" = ' . $this->ProductID ) ) { return $product; } return null; }
php
{ "resource": "" }
q257910
ProductVariationsExtension.updateCMSFields
test
public function updateCMSFields(FieldList $fields) { $fields->addFieldsToTab('Root.Variations', [ ListboxField::create( 'VariationAttributeTypes', _t(__CLASS__ . '.Attributes', "Attributes"), AttributeType::get()->map('ID', 'Title')->toArray() ) ->setDescription(_t( __CLASS__ . '.AttributesDescription', 'These are fields to indicate the way(s) each variation varies. Once selected, they can be edited on each variation.' )), GridField::create( 'Variations', _t(__CLASS__ . '.Variations', 'Variations'), $this->owner->Variations(), GridFieldConfig_RecordEditor::create() ) ]); if ($this->owner->Variations()->exists()) { $fields->addFieldToTab( 'Root.Pricing', LabelField::create( 'variationspriceinstructinos', _t( __CLASS__ . '.VariationsInfo', 'Price - Because you have one or more variations, the price can be set in the "Variations" tab.' ) ) ); $fields->removeFieldFromTab('Root.Pricing', 'BasePrice'); $fields->removeFieldFromTab('Root.Main', 'InternalItemID'); } }
php
{ "resource": "" }
q257911
ProductVariationsExtension.getVariationByAttributes
test
public function getVariationByAttributes(array $attributes) { if (!is_array($attributes)) { return null; } $attrs = array_filter(array_values($attributes)); $set = Variation::get()->filter('ProductID', $this->owner->ID); foreach ($attrs as $i => $valueid) { $alias = "A$i"; $set = $set->innerJoin( 'SilverShop_Variation_AttributeValues', "\"SilverShop_Variation\".\"ID\" = \"$alias\".\"SilverShop_VariationID\"", $alias )->where(["\"$alias\".\"SilverShop_AttributeValueID\" = ?" => $valueid]); } return $set->first(); }
php
{ "resource": "" }
q257912
ProductVariationsExtension.generateVariationsFromAttributes
test
public function generateVariationsFromAttributes(AttributeType $attributetype, array $values) { //TODO: introduce transactions here, in case objects get half made etc //if product has variation attribute types if (!empty($values)) { //TODO: get values dataobject set $avalues = $attributetype->convertArrayToValues($values); $existingvariations = $this->owner->Variations(); if ($existingvariations->exists()) { //delete old variation, and create new ones - to prevent modification of exising variations foreach ($existingvariations as $oldvariation) { $oldvalues = $oldvariation->AttributeValues(); foreach ($avalues as $value) { $newvariation = $oldvariation->duplicate(); $newvariation->InternalItemID = $this->owner->InternalItemID . '-' . $newvariation->ID; $newvariation->AttributeValues()->addMany($oldvalues); $newvariation->AttributeValues()->add($value); $newvariation->write(); $existingvariations->add($newvariation); } $existingvariations->remove($oldvariation); $oldvariation->AttributeValues()->removeAll(); $oldvariation->delete(); $oldvariation->destroy(); //TODO: check that old variations actually stick around, as they will be needed for past orders etc } } else { foreach ($avalues as $value) { $variation = Variation::create(); $variation->ProductID = $this->owner->ID; $variation->Price = $this->owner->BasePrice; $variation->write(); $variation->InternalItemID = $this->owner->InternalItemID . '-' . $variation->ID; $variation->AttributeValues()->add($value); $variation->write(); $existingvariations->add($variation); } } } }
php
{ "resource": "" }
q257913
ProductVariationsExtension.onAfterDelete
test
public function onAfterDelete() { $remove = false; // if a record is staged or live, leave it's variations alone. if (!property_exists($this, 'owner')) { $remove = true; } else { $staged = Versioned::get_by_stage($this->owner->ClassName, 'Stage') ->byID($this->owner->ID); $live = Versioned::get_by_stage($this->owner->ClassName, 'Live') ->byID($this->owner->ID); if (!$staged && !$live) { $remove = true; } } if ($remove) { foreach ($this->owner->Variations() as $variation) { $variation->delete(); $variation->destroy(); } } }
php
{ "resource": "" }
q257914
CheckoutComponentConfig.getComponentByType
test
public function getComponentByType($type) { foreach ($this->components as $component) { if ($this->namespaced) { if ($component->Proxy() instanceof $type) { return $component->Proxy(); } } else { if ($component instanceof $type) { return $component; } } } }
php
{ "resource": "" }
q257915
CheckoutComponentConfig.getFormFields
test
public function getFormFields() { $fields = FieldList::create(); foreach ($this->getComponents() as $component) { if ($cfields = $component->getFormFields($this->order)) { $fields->merge($cfields); } else { user_error('getFields on ' . get_class($component) . ' must return a FieldList'); } } return $fields; }
php
{ "resource": "" }
q257916
CheckoutComponentConfig.validateData
test
public function validateData($data) { $result = ValidationResult::create(); foreach ($this->getComponents() as $component) { try { $component->validateData($this->order, $this->dependantData($component, $data)); } catch (ValidationException $e) { //transfer messages into a single result foreach ($e->getResult()->getMessages() as $code => $message) { if (is_numeric($code)) { $code = null; } if ($this->namespaced) { $code = $component->namespaceFieldName($code); } $result->addError($message['message'], $code); } } } $this->order->extend('onValidateDataOnCheckout', $result); if (!$result->isValid()) { throw new ValidationException($result); } return true; }
php
{ "resource": "" }
q257917
CheckoutComponentConfig.getData
test
public function getData() { $data = array(); foreach ($this->getComponents() as $component) { $orderdata = $component->getData($this->order); if (is_array($orderdata)) { $data = array_merge($data, $orderdata); } else { user_error('getData on ' . $component->name() . ' must return an array'); } } return $data; }
php
{ "resource": "" }
q257918
CheckoutComponentConfig.setData
test
public function setData($data) { foreach ($this->getComponents() as $component) { $component->setData($this->order, $this->dependantData($component, $data)); } }
php
{ "resource": "" }
q257919
CheckoutComponentConfig.dependantData
test
protected function dependantData($component, $data) { if (!$this->namespaced) { //no need to try and get un-namespaced dependant data return $data; } $dependantdata = array(); foreach ($component->dependsOn() as $dependanttype) { $dependant = null; foreach ($this->components as $check) { if (get_class($check->Proxy()) == $dependanttype) { $dependant = $check; break; } } if (!$dependant) { user_error("Could not find a $dependanttype component, as depended by " . $component->name()); } $dependantdata = array_merge( $dependantdata, $component->namespaceData($dependant->unnamespaceData($data)) ); } return array_merge($dependantdata, $data); }
php
{ "resource": "" }
q257920
ShoppingCart.current
test
public function current() { $session = ShopTools::getSession(); //find order by id saved to session (allows logging out and retaining cart contents) if (!$this->order && $sessionid = $session->get(self::config()->cartid_session_name)) { $this->order = Order::get()->filter( [ 'Status' => 'Cart', 'ID' => $sessionid, ] )->first(); } if (!$this->calculateonce && $this->order) { $this->order->calculate(); $this->calculateonce = true; } return $this->order ? $this->order : null; }
php
{ "resource": "" }
q257921
ShoppingCart.setCurrent
test
public function setCurrent(Order $cart) { if (!$cart->IsCart()) { trigger_error('Passed Order object is not cart status', E_ERROR); } $this->order = $cart; $session = ShopTools::getSession(); $session->set(self::config()->cartid_session_name, $cart->ID); return $this; }
php
{ "resource": "" }
q257922
ShoppingCart.findOrMake
test
protected function findOrMake() { if ($this->current()) { return $this->current(); } $this->order = Order::create(); if (Member::config()->login_joins_cart && ($member = Security::getCurrentUser())) { $this->order->MemberID = $member->ID; } $this->order->write(); $this->order->extend('onStartOrder'); $session = ShopTools::getSession(); $session->set(self::config()->cartid_session_name, $this->order->ID); return $this->order; }
php
{ "resource": "" }
q257923
ShoppingCart.add
test
public function add(Buyable $buyable, $quantity = 1, $filter = []) { $order = $this->findOrMake(); // If an extension throws an exception, error out try { $order->extend('beforeAdd', $buyable, $quantity, $filter); } catch (Exception $exception) { return $this->error($exception->getMessage()); } if (!$buyable) { return $this->error(_t(__CLASS__ . '.ProductNotFound', 'Product not found.')); } $item = $this->findOrMakeItem($buyable, $quantity, $filter); if (!$item) { return false; } if (!$item->_brandnew) { $item->Quantity += $quantity; } else { $item->Quantity = $quantity; } // If an extension throws an exception, error out try { $order->extend('afterAdd', $item, $buyable, $quantity, $filter); } catch (Exception $exception) { return $this->error($exception->getMessage()); } $item->write(); $this->message(_t(__CLASS__ . '.ItemAdded', 'Item has been added successfully.')); return $item; }
php
{ "resource": "" }
q257924
ShoppingCart.remove
test
public function remove(Buyable $buyable, $quantity = null, $filter = []) { $order = $this->current(); if (!$order) { return $this->error(_t(__CLASS__ . '.NoOrder', 'No current order.')); } // If an extension throws an exception, error out try { $order->extend('beforeRemove', $buyable, $quantity, $filter); } catch (Exception $exception) { return $this->error($exception->getMessage()); } $item = $this->get($buyable, $filter); if (!$item || !$this->removeOrderItem($item, $quantity)) { return false; } // If an extension throws an exception, error out // TODO: There should be a rollback try { $order->extend('afterRemove', $item, $buyable, $quantity, $filter); } catch (Exception $exception) { return $this->error($exception->getMessage()); } $this->message(_t(__CLASS__ . '.ItemRemoved', 'Item has been successfully removed.')); return true; }
php
{ "resource": "" }
q257925
ShoppingCart.removeOrderItem
test
public function removeOrderItem(OrderItem $item, $quantity = null) { $order = $this->current(); if (!$order) { return $this->error(_t(__CLASS__ . '.NoOrder', 'No current order.')); } if (!$item || $item->OrderID != $order->ID) { return $this->error(_t(__CLASS__ . '.ItemNotFound', 'Item not found.')); } //if $quantity will become 0, then remove all if (!$quantity || ($item->Quantity - $quantity) <= 0) { $item->delete(); $item->destroy(); } else { $item->Quantity -= $quantity; $item->write(); } return true; }
php
{ "resource": "" }
q257926
ShoppingCart.setQuantity
test
public function setQuantity(Buyable $buyable, $quantity = 1, $filter = []) { if ($quantity <= 0) { return $this->remove($buyable, $quantity, $filter); } $item = $this->findOrMakeItem($buyable, $quantity, $filter); if (!$item || !$this->updateOrderItemQuantity($item, $quantity, $filter)) { return false; } return $item; }
php
{ "resource": "" }
q257927
ShoppingCart.updateOrderItemQuantity
test
public function updateOrderItemQuantity(OrderItem $item, $quantity = 1, $filter = []) { $order = $this->current(); if (!$order) { return $this->error(_t(__CLASS__ . '.NoOrder', 'No current order.')); } if (!$item || $item->OrderID != $order->ID) { return $this->error(_t(__CLASS__ . '.ItemNotFound', 'Item not found.')); } $buyable = $item->Buyable(); // If an extension throws an exception, error out try { $order->extend('beforeSetQuantity', $buyable, $quantity, $filter); } catch (Exception $exception) { return $this->error($exception->getMessage()); } $item->Quantity = $quantity; // If an extension throws an exception, error out try { $order->extend('afterSetQuantity', $item, $buyable, $quantity, $filter); } catch (Exception $exception) { return $this->error($exception->getMessage()); } $item->write(); $this->message(_t(__CLASS__ . '.QuantitySet', 'Quantity has been set.')); return true; }
php
{ "resource": "" }
q257928
ShoppingCart.findOrMakeItem
test
private function findOrMakeItem(Buyable $buyable, $quantity = 1, $filter = []) { $order = $this->findOrMake(); if (!$buyable || !$order) { return null; } $item = $this->get($buyable, $filter); if (!$item) { $member = Security::getCurrentUser(); $buyable = $this->getCorrectBuyable($buyable); if (!$buyable->canPurchase($member, $quantity)) { return $this->error( _t( __CLASS__ . '.CannotPurchase', 'This {Title} cannot be purchased.', '', ['Title' => $buyable->i18n_singular_name()] ) ); //TODO: produce a more specific message } $item = $buyable->createItem($quantity, $filter); $item->OrderID = $order->ID; $item->write(); $order->Items()->add($item); $item->_brandnew = true; // flag as being new } return $item; }
php
{ "resource": "" }
q257929
ShoppingCart.get
test
public function get(Buyable $buyable, $customfilter = array()) { $order = $this->current(); if (!$buyable || !$order) { return null; } $buyable = $this->getCorrectBuyable($buyable); $filter = array( 'OrderID' => $order->ID, ); $itemclass = Config::inst()->get(get_class($buyable), 'order_item'); $relationship = Config::inst()->get($itemclass, 'buyable_relationship'); $filter[$relationship . 'ID'] = $buyable->ID; $required = ['OrderID', $relationship . 'ID']; if (is_array($itemclass::config()->required_fields)) { $required = array_merge($required, $itemclass::config()->required_fields); } $query = new MatchObjectFilter($itemclass, array_merge($customfilter, $filter), $required); $item = $itemclass::get()->where($query->getFilter())->first(); if (!$item) { return $this->error(_t(__CLASS__ . '.ItemNotFound', 'Item not found.')); } return $item; }
php
{ "resource": "" }
q257930
ShoppingCart.archiveorderid
test
public function archiveorderid($requestedOrderId = null) { $session = ShopTools::getSession(); $sessionId = $session->get(self::config()->cartid_session_name); $order = Order::get() ->filter('Status:not', 'Cart') ->byId($sessionId); if ($order && !$order->IsCart()) { OrderManipulationExtension::add_session_order($order); } // in case there was no order requested // OR there was an order requested AND it's the same one as currently in the session, // then clear the cart. This check is here to prevent clearing of the cart if the user just // wants to view an old order (via AccountPage). if (!$requestedOrderId || ($sessionId == $requestedOrderId)) { $this->clear(); } }
php
{ "resource": "" }
q257931
FlatTax.value
test
public function value($incoming) { $this->Rate = self::config()->rate; //inclusive tax requires a different calculation return self::config()->exclusive ? $incoming * $this->Rate : $incoming - round($incoming / (1 + $this->Rate), Order::config()->rounding_precision); }
php
{ "resource": "" }
q257932
ShopTools.price_for_display
test
public static function price_for_display($price) { $currency = ShopConfigExtension::get_site_currency(); $field = DBMoney::create_field(DBMoney::class, 0, 'Price'); $field->setAmount($price); $field->setCurrency($currency); return $field; }
php
{ "resource": "" }
q257933
ProductBulkLoader.imageByFilename
test
public function imageByFilename(&$obj, $val, $record) { $filename = trim(strtolower(Convert::raw2sql($val))); $filenamedashes = str_replace(' ', '-', $filename); if ($filename && $image = Image::get()->whereAny( [ "LOWER(\"FileFilename\") LIKE '%$filename%'", "LOWER(\"FileFilename\") LIKE '%$filenamedashes%'" ] )->first() ) { //ignore case if ($image instanceof Image && $image->exists()) { return $image; } } return null; }
php
{ "resource": "" }
q257934
ProductBulkLoader.setContent
test
public function setContent(&$obj, $val, $record) { $val = trim($val); if ($val) { $paragraphs = explode("\n", $val); $obj->Content = '<p>' . implode('</p><p>', $paragraphs) . '</p>'; } }
php
{ "resource": "" }
q257935
ShopConfigExtension.getCountriesList
test
public function getCountriesList($prefixisocode = false) { $countries = self::config()->iso_3166_country_codes; asort($countries); if ($allowed = $this->owner->AllowedCountries) { $allowed = json_decode($allowed); if (!empty($allowed)) { $countries = array_intersect_key($countries, array_flip($allowed)); } } if ($prefixisocode) { foreach ($countries as $key => $value) { $countries[$key] = "$key - $value"; } } return $countries; }
php
{ "resource": "" }
q257936
ShopConfigExtension.getSingleCountry
test
public function getSingleCountry($fullname = false) { $countries = $this->getCountriesList(); if (count($countries) == 1) { if ($fullname) { return array_pop($countries); } else { reset($countries); return key($countries); } } return null; }
php
{ "resource": "" }
q257937
ShopConfigExtension.countryCode2name
test
public static function countryCode2name($code) { $codes = self::config()->iso_3166_country_codes; if (isset($codes[$code])) { return $codes[$code]; } return $code; }
php
{ "resource": "" }
q257938
ViewableCartExtension.Cart
test
public function Cart() { $order = ShoppingCart::curr(); if (!$order || !$order->Items() || !$order->Items()->exists()) { return false; } return $order; }
php
{ "resource": "" }
q257939
AttributeType.convertArrayToValues
test
public function convertArrayToValues(array $values) { $set = ArrayList::create(); foreach ($values as $value) { $val = $this->Values()->find('Value', $value); if (!$val) { //TODO: ignore case, if possible $val = AttributeValue::create(); $val->Value = $value; $val->TypeID = $this->ID; $val->write(); } $set->push($val); } return $set; }
php
{ "resource": "" }
q257940
AttributeType.getDropDownField
test
public function getDropDownField($emptystring = null, $values = null) { $values = ($values) ? $values : $this->Values()->sort(['Sort' => 'ASC', 'Value' => 'ASC']); if ($values->exists()) { $field = DropdownField::create( 'ProductAttributes[' . $this->ID . ']', $this->Name, $values->map('ID', 'Value') ); if ($emptystring) { $field->setEmptyString($emptystring); } return $field; } return null; }
php
{ "resource": "" }
q257941
ProductCategory.ProductsShowable
test
public function ProductsShowable($recursive = true) { // Figure out the categories to check $groupids = array($this->ID); if (!empty($recursive) && self::config()->include_child_groups) { $groupids += $this->AllChildCategoryIDs(); } $products = Product::get()->filterAny( [ 'ParentID' => $groupids, 'ProductCategories.ID' => $groupids ] ); if (self::config()->must_have_price) { if (Product::has_extension(ProductVariationsExtension::class)) { $products = $products->filterAny( [ 'BasePrice:GreaterThan' => 0, 'Variations.Price:GreaterThan' => 0 ] ); } else { $products = $products->filter('BasePrice:GreaterThan', 0); } } $this->extend('updateProductsShowable', $products); return $products; }
php
{ "resource": "" }
q257942
ProductCategory.AllChildCategoryIDs
test
public function AllChildCategoryIDs() { $ids = [$this->ID]; $allids = []; do { $ids = ProductCategory::get() ->filter('ParentID', $ids) ->getIDList(); $allids += $ids; } while (!empty($ids)); return $allids; }
php
{ "resource": "" }
q257943
ProductCategory.ChildCategories
test
public function ChildCategories($recursive = false) { $ids = array($this->ID); if ($recursive) { $ids += $this->AllChildCategoryIDs(); } return ProductCategory::get()->filter('ParentID', $ids); }
php
{ "resource": "" }
q257944
ProductCategory.GroupsMenu
test
public function GroupsMenu() { if ($this->Parent() instanceof ProductCategory) { return $this->Parent()->GroupsMenu(); } return ProductCategory::get() ->filter('ParentID', $this->ID); }
php
{ "resource": "" }
q257945
ProductCategory.NestedTitle
test
public function NestedTitle($level = 10, $separator = ' > ', $field = 'MenuTitle') { $item = $this; while ($item && $level > 0) { $parts[] = $item->{$field}; $item = $item->Parent; $level--; } return implode($separator, array_reverse($parts)); }
php
{ "resource": "" }
q257946
OrderGridFieldDetailForm_ItemRequest.ItemEditForm
test
public function ItemEditForm() { $form = parent::ItemEditForm(); $printlink = $this->Link('printorder') . '?print=1'; $printwindowjs = <<<JS window.open('$printlink', 'print_order', 'toolbar=0,scrollbars=1,location=1,statusbar=0,menubar=0,resizable=1,width=800,height=600,left = 50,top = 50');return false; JS; $form->Actions()->push( LiteralField::create( 'PrintOrder', "<button class=\"no-ajax grid-print-button btn action btn-primary font-icon-print\" onclick=\"javascript:$printwindowjs\">" . _t('SilverShop\Model\Order.Print', 'Print') . '</button>' ) ); return $form; }
php
{ "resource": "" }
q257947
OrderGridFieldDetailForm_ItemRequest.printorder
test
public function printorder() { Requirements::clear(); //include print javascript, if print argument is provided if (isset($_REQUEST['print']) && $_REQUEST['print']) { Requirements::customScript('if(document.location.href.indexOf(\'print=1\') > 0) {window.print();}'); } $title = _t('SilverShop\Model\Order.Invoice', 'Invoice'); if ($id = $this->popupController->getRequest()->param('ID')) { $title .= " #$id"; } return $this->record->customise( [ 'SiteConfig' => SiteConfig::current_site_config(), 'Title' => $title, ] )->renderWith('SilverShop\Admin\OrderAdmin_Printable'); }
php
{ "resource": "" }
q257948
CheckoutStep.nextstep
test
private function nextstep() { $steps = $this->owner->getSteps(); $found = false; foreach ($steps as $step => $class) { //determine if this is the current step if (method_exists($this, $step)) { $found = true; } elseif ($found) { return $step; } } return null; }
php
{ "resource": "" }
q257949
OrdersAdmin.getList
test
public function getList() { $list = parent::getList(); if ($this->modelClass == Order::class) { // Exclude hidden statuses $list = $list->exclude('Status', Order::config()->hidden_status); $this->extend('updateList', $list); } return $list; }
php
{ "resource": "" }
q257950
OrdersAdmin.getEditForm
test
public function getEditForm($id = null, $fields = null) { $form = parent::getEditForm($id, $fields); if ($this->modelClass == Order::class) { /** @var GridFieldConfig $config */ $config = $form ->Fields() ->fieldByName($this->sanitiseClassName($this->modelClass)) ->getConfig(); $config ->getComponentByType(GridFieldSortableHeader::class) ->setFieldSorting([ 'StatusI18N' => 'Status' ]); $config ->getComponentByType(GridFieldDetailForm::class) ->setItemRequestClass(OrderGridFieldDetailForm_ItemRequest::class); //see below } if ($this->modelClass == OrderStatusLog::class) { /** @var GridFieldConfig $config */ $config = $form ->Fields() ->fieldByName($this->sanitiseClassName($this->modelClass)) ->getConfig(); // Remove add new button $config->removeComponentsByType($config->getComponentByType(GridFieldAddNewButton::class)); } return $form; }
php
{ "resource": "" }
q257951
CheckoutFieldFactory.getSubset
test
private function getSubset(FieldList $fields, $subset = array()) { if (empty($subset)) { return $fields; } $subfieldlist = FieldList::create(); foreach ($subset as $field) { if ($field = $fields->fieldByName($field)) { $subfieldlist->push($field); } } return $subfieldlist; }
php
{ "resource": "" }
q257952
OrderModifier.modify
test
public function modify($subtotal, $forcecalculation = false) { $order = $this->Order(); $value = ($order->IsCart() || $forcecalculation) ? $this->value($subtotal) : $this->Amount; switch ($this->Type) { case 'Chargable': $subtotal += $value; break; case 'Deductable': $subtotal -= $value; break; case 'Ignored': break; } $value = round($value, Order::config()->rounding_precision); $this->Amount = $value; return $subtotal; }
php
{ "resource": "" }
q257953
SteppedCheckoutExtension.setupSteps
test
public static function setupSteps($steps = null) { if (!is_array($steps)) { //default steps $steps =[ 'membership' => Membership::class, 'contactdetails' => ContactDetails::class, 'shippingaddress' => Address::class, 'billingaddress' => Address::class, 'paymentmethod' => PaymentMethod::class, 'summary' => Summary::class, ]; } CheckoutPage::config()->steps = $steps; if (!CheckoutPage::config()->first_step) { reset($steps); CheckoutPage::config()->first_step = key($steps); } //initiate extensions CheckoutPageController::add_extension(SteppedCheckoutExtension::class); foreach ($steps as $action => $classname) { CheckoutPageController::add_extension($classname); } }
php
{ "resource": "" }
q257954
SteppedCheckoutExtension.onAfterInit
test
public function onAfterInit() { $action = $this->owner->getRequest()->param('Action'); $steps = $this->getSteps(); if (!ShoppingCart::curr() && !empty($action) && isset($steps[$action])) { Controller::curr()->redirect($this->owner->Link()); return; } }
php
{ "resource": "" }
q257955
SteppedCheckoutExtension.IsCurrentStep
test
public function IsCurrentStep($name) { if ($this->owner->getAction() === $name) { return true; } elseif (!$this->owner->getAction() || $this->owner->getAction() === 'index') { return $this->actionPos($name) === 0; } return false; }
php
{ "resource": "" }
q257956
SteppedCheckoutExtension.actionPos
test
private function actionPos($incoming) { $count = 0; foreach ($this->getSteps() as $action => $step) { if ($action == $incoming) { return $count; } $count++; } }
php
{ "resource": "" }
q257957
CartPage.find_link
test
public static function find_link($urlSegment = false, $action = false, $id = false) { $base = CartPageController::config()->url_segment; if ($page = self::get()->first()) { $base = $page->Link(); } return Controller::join_links($base, $action, $id); }
php
{ "resource": "" }
q257958
ProductCategoryController.Products
test
public function Products($recursive = true) { $products = $this->ProductsShowable($recursive); //sort the products $products = $this->getSorter()->sortList($products); //paginate the products, if necessary $pagelength = ProductCategory::config()->page_length; if ($pagelength > 0) { $products = PaginatedList::create($products, $this->request); $products->setPageLength($pagelength); $products->TotalCount = $products->getTotalItems(); } return $products; }
php
{ "resource": "" }
q257959
ShopCurrency.TrimCents
test
public function TrimCents() { $val = $this->value; if (floor($val) == $val) { return floor($val); } return $val; }
php
{ "resource": "" }
q257960
Product.getCMSFields
test
public function getCMSFields() { $self = $this; $this->beforeUpdateCMSFields( function (FieldList $fields) use ($self) { $fields->fieldByName('Root.Main.Title') ->setTitle(_t(__CLASS__ . '.PageTitle', 'Product Title')); $fields->addFieldsToTab('Root.Main', [ TextField::create('InternalItemID', _t(__CLASS__ . '.InternalItemID', 'Product Code/SKU'), '', 30), DropdownField::create('ParentID', _t(__CLASS__ . '.Category', 'Category'), $self->getCategoryOptions()) ->setDescription(_t(__CLASS__ . '.CategoryDescription', 'This is the parent page or default category.')), ListboxField::create( 'ProductCategories', _t(__CLASS__ . '.AdditionalCategories', 'Additional Categories'), $self->getCategoryOptionsNoParent() ), TextField::create('Model', _t(__CLASS__ . '.Model', 'Model'), '', 30), CheckboxField::create('Featured', _t(__CLASS__ . '.Featured', 'Featured Product')), CheckboxField::create('AllowPurchase', _t(__CLASS__ . '.AllowPurchase', 'Allow product to be purchased'), 1), ], 'Content'); $fields->addFieldsToTab( 'Root.Pricing', [ TextField::create('BasePrice', $this->fieldLabel('BasePrice')) ->setDescription(_t(__CLASS__ . '.PriceDesc', 'Base price to sell this product at.')) ->setMaxLength(12), ] ); $fieldSubstitutes = [ 'LengthUnit' => $self::config()->length_unit ]; $fields->addFieldsToTab( 'Root.Shipping', [ TextField::create( 'Weight', _t( __CLASS__ . '.WeightWithUnit', 'Weight ({WeightUnit})', '', [ 'WeightUnit' => self::config()->weight_unit ] ), '', 12 ), TextField::create( 'Height', _t(__CLASS__ . '.HeightWithUnit', 'Height ({LengthUnit})', '', $fieldSubstitutes), '', 12 ), TextField::create( 'Width', _t(__CLASS__ . '.WidthWithUnit', 'Width ({LengthUnit})', '', $fieldSubstitutes), '', 12 ), TextField::create( 'Depth', _t(__CLASS__ . '.DepthWithUnit', 'Depth ({LengthUnit})', '', $fieldSubstitutes), '', 12 ), ] ); if (!$fields->dataFieldByName('Image')) { $fields->addFieldToTab( 'Root.Images', UploadField::create('Image', _t(__CLASS__ . '.Image', 'Product Image')) ); } } ); return parent::getCMSFields(); }
php
{ "resource": "" }
q257961
Product.getCategoryOptions
test
private function getCategoryOptions() { $categories = ProductCategory::get()->map('ID', 'NestedTitle')->toArray(); $categories = [ 0 => _t('SilverStripe\CMS\Model\SiteTree.PARENTTYPE_ROOT', 'Top-level page'), ] + $categories; if ($this->ParentID && !($this->Parent() instanceof ProductCategory)) { $categories = [ $this->ParentID => $this->Parent()->Title . ' (' . $this->Parent()->i18n_singular_name() . ')', ] + $categories; } return $categories; }
php
{ "resource": "" }
q257962
Product.getCategoryOptionsNoParent
test
private function getCategoryOptionsNoParent() { $ancestors = $this->getAncestors()->column('ID'); $categories = ProductCategory::get(); if (!empty($ancestors)) { $categories = $categories->exclude('ID', $ancestors); } return $categories->map('ID', 'NestedTitle')->toArray(); }
php
{ "resource": "" }
q257963
Product.getCategoryIDs
test
public function getCategoryIDs() { $ids = array(); //ancestors foreach ($this->getAncestors() as $ancestor) { $ids[$ancestor->ID] = $ancestor->ID; } //additional categories $ids += $this->ProductCategories()->getIDList(); return $ids; }
php
{ "resource": "" }
q257964
Product.sellingPrice
test
public function sellingPrice() { $price = $this->BasePrice; //TODO: this is not ideal, because prices manipulations will not happen in a known order $this->extend('updateSellingPrice', $price); //prevent negative values $price = $price < 0 ? 0 : $price; // NOTE: Ideally, this would be dependent on the locale but as of // now the Silverstripe Currency field type has 2 hardcoded all over // the place. In the mean time there is an issue where the displayed // unit price can not exactly equal the multiplied price on an order // (i.e. if the calculated price is 3.145 it will display as 3.15. // so if I put 10 of them in my cart I will expect the price to be // 31.50 not 31.45). return round($price, Order::config()->rounding_precision); }
php
{ "resource": "" }
q257965
Product.Image
test
public function Image() { $image = $this->getComponent('Image'); $this->extend('updateImage', $image); if ($image && $image->exists()) { return $image; } $image = SiteConfig::current_site_config()->DefaultProductImage(); if ($image && $image->exists()) { return $image; } return null; }
php
{ "resource": "" }
q257966
PaymentForm.submitpayment
test
public function submitpayment($data, $form) { $data = $form->getData(); $cancelUrl = $this->getFailureLink() ? $this->getFailureLink() : $this->controller->Link(); $order = $this->config->getOrder(); // final recalculation, before making payment $order->calculate(); // handle cases where order total is 0. Note that the order will appear // as "paid", but without a Payment record attached. if ($order->GrandTotal() == 0 && Order::config()->allow_zero_order_total) { if (!$this->orderProcessor->placeOrder()) { $form->sessionMessage($this->orderProcessor->getError()); return $this->controller->redirectBack(); } return $this->controller->redirect($this->getSuccessLink()); } // try to place order before payment, if configured if (Order::config()->place_before_payment) { if (!$this->orderProcessor->placeOrder()) { $form->sessionMessage($this->orderProcessor->getError()); return $this->controller->redirectBack(); } $cancelUrl = $this->orderProcessor->getReturnUrl(); } // if we got here from checkoutSubmit and there's a namespaced Component that provides payment data, // we need to strip the inputs down to only the checkout component. $components = $this->config->getComponents(); if ($components->first() instanceof CheckoutComponentNamespaced) { foreach ($components as $component) { if ($component->Proxy()->providesPaymentData()) { $data = array_merge($data, $component->unnamespaceData($data)); } } } $gateway = Checkout::get($order)->getSelectedPaymentMethod(false); $fieldFactory = new GatewayFieldsFactory($gateway); // This is where the payment is actually attempted $paymentResponse = $this->orderProcessor->makePayment( $gateway, $fieldFactory->normalizeFormData($data), $this->getSuccessLink(), $cancelUrl ); $response = null; if ($this->controller->hasMethod('processPaymentResponse')) { $response = $this->controller->processPaymentResponse($paymentResponse, $form); } elseif ($paymentResponse && !$paymentResponse->isError()) { $response = $paymentResponse->redirectOrRespond(); } else { $form->sessionMessage($this->orderProcessor->getError(), 'bad'); $response = $this->controller->redirectBack(); } return $response; }
php
{ "resource": "" }
q257967
OrderActionsForm.dopayment
test
public function dopayment($data, $form) { if (self::config()->allow_paying && $this->order && $this->order->canPay() ) { // Save payment data from form and process payment $data = $form->getData(); $gateway = (!empty($data['PaymentMethod'])) ? $data['PaymentMethod'] : null; if (!GatewayInfo::isManual($gateway)) { $processor = OrderProcessor::create($this->order); $fieldFactory = new GatewayFieldsFactory(null); $response = $processor->makePayment( $gateway, $fieldFactory->normalizeFormData($data), $processor->getReturnUrl() ); if ($response && !$response->isError()) { return $response->redirectOrRespond(); } else { $form->sessionMessage($processor->getError(), 'bad'); } } else { $form->sessionMessage(_t(__CLASS__ . '.ManualNotAllowed', 'Manual payment not allowed'), 'bad'); } return $this->controller->redirectBack(); } $form->sessionMessage( _t(__CLASS__ . '.CouldNotProcessPayment', 'Payment could not be processed.'), 'bad' ); return $this->controller->redirectBack(); }
php
{ "resource": "" }
q257968
OrderActionsForm.docancel
test
public function docancel($data, $form) { if (self::config()->allow_cancelling && $this->order->canCancel() ) { $this->order->Status = 'MemberCancelled'; $this->order->write(); if (self::config()->email_notification) { OrderEmailNotifier::create($this->order)->sendCancelNotification(); } $this->controller->sessionMessage( _t(__CLASS__ . '.OrderCancelled', 'Order sucessfully cancelled'), 'warning' ); if (Security::getCurrentUser() && $link = $this->order->Link()) { $this->controller->redirect($link); } else { $this->controller->redirectBack(); } } }
php
{ "resource": "" }
q257969
OrderActionsForm.getCCFields
test
protected function getCCFields(array $gateways) { $fieldFactory = new GatewayFieldsFactory(null, array('Card')); $onsiteGateways = array(); $allRequired = array(); foreach ($gateways as $gateway => $title) { if (!GatewayInfo::isOffsite($gateway)) { $required = GatewayInfo::requiredFields($gateway); $onsiteGateways[$gateway] = $fieldFactory->getFieldName($required); $allRequired += $required; } } $allRequired = array_unique($allRequired); $allRequired = $fieldFactory->getFieldName(array_combine($allRequired, $allRequired)); if (empty($onsiteGateways)) { return null; } $ccFields = $fieldFactory->getCardFields(); // Remove all the credit card fields that aren't required by any gateway foreach ($ccFields->dataFields() as $name => $field) { if ($name && !in_array($name, $allRequired)) { $ccFields->removeByName($name, true); } } $lookupField = LiteralField::create( '_CCLookupField', sprintf( '<span class="gateway-lookup" data-gateways=\'%s\'></span>', json_encode($onsiteGateways, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ) ); $ccFields->push($lookupField); return CompositeField::create($ccFields)->setTag('fieldset')->addExtraClass('credit-card'); }
php
{ "resource": "" }
q257970
OrderManipulationExtension.add_session_order
test
public static function add_session_order(Order $order) { $history = self::get_session_order_ids(); if (!is_array($history)) { $history = array(); } $history[$order->ID] = $order->ID; ShopTools::getSession()->set(self::$sessname, $history); }
php
{ "resource": "" }
q257971
OrderManipulationExtension.get_session_order_ids
test
public static function get_session_order_ids() { $history = ShopTools::getSession()->get(self::$sessname); if (!is_array($history)) { $history = null; } return $history; }
php
{ "resource": "" }
q257972
OrderManipulationExtension.orderfromid
test
public function orderfromid() { $request = $this->owner->getRequest(); $id = (int)$request->param('ID'); if (!$id) { $id = (int)$request->postVar('OrderID'); } return $this->allorders()->byID($id); }
php
{ "resource": "" }
q257973
OrderManipulationExtension.ActionsForm
test
public function ActionsForm() { if ($order = $this->orderfromid()) { $form = OrderActionsForm::create($this->owner, 'ActionsForm', $order); $form->extend('updateActionsForm', $order); if (!$form->Actions()->exists()) { return null; } return $form; } return null; }
php
{ "resource": "" }
q257974
ShopMemberFactory.create
test
public function create($data) { $result = ValidationResult::create(); if (!Checkout::member_creation_enabled()) { $result->addError( _t('SilverShop\Checkout\Checkout.MembershipIsNotAllowed', 'Creating new memberships is not allowed') ); throw new ValidationException($result); } $idfield = Config::inst()->get(Member::class, 'unique_identifier_field'); if (!isset($data[$idfield]) || empty($data[$idfield])) { $result->addError( _t( 'SilverShop\Checkout\Checkout.IdFieldNotFound', 'Required field not found: {IdentifierField}', 'Identifier is the field that holds the unique user-identifier, commonly this is \'Email\'', ['IdentifierField' => $idfield] ) ); throw new ValidationException($result); } if (!isset($data['Password']) || empty($data['Password'])) { $result->addError(_t('SilverShop\Checkout\Checkout.PasswordRequired', 'A password is required')); throw new ValidationException($result); } $idval = $data[$idfield]; if ($member = MemberExtension::get_by_identifier($idval)) { // get localized field labels $fieldLabels = $member->fieldLabels(false); // if a localized value exists, use this for our error-message $fieldLabel = isset($fieldLabels[$idfield]) ? $fieldLabels[$idfield] : $idfield; $result->addError( _t( 'SilverShop\Checkout\Checkout.MemberExists', 'A member already exists with the {Field} {Identifier}', '', ['Field' => $fieldLabel, 'Identifier' => $idval] ) ); throw new ValidationException($result); } /** @var Member $member */ $member = Member::create()->update($data); // 3.2 changed validate to protected which made this fall through the DataExtension and error out $validation = $member->doValidate(); if (!$validation->isValid()) { //TODO need to handle i18n here? foreach ($validation->getMessages() as $message) { $result->addError($message['message']); } } if (!$result->isValid()) { throw new ValidationException($result); } return $member; }
php
{ "resource": "" }
q257975
MemberExtension.get_by_identifier
test
public static function get_by_identifier($idvalue) { return Member::get()->filter( Member::config()->unique_identifier_field, $idvalue )->first(); }
php
{ "resource": "" }
q257976
MemberExtension.afterMemberLoggedIn
test
public function afterMemberLoggedIn() { if (Member::config()->login_joins_cart && $order = ShoppingCart::singleton()->current()) { $order->MemberID = $this->owner->ID; $order->write(); } }
php
{ "resource": "" }
q257977
MemberExtension.getPastOrders
test
public function getPastOrders() { return Order::get() ->filter('MemberID', $this->owner->ID) ->filter('Status:not', Order::config()->hidden_status); }
php
{ "resource": "" }
q257978
ShopQuantityField.AJAXLinkHiddenField
test
public function AJAXLinkHiddenField() { if ($quantitylink = $this->item->setquantityLink()) { return HiddenField::create( $this->MainID() . '_Quantity_SetQuantityLink' )->setValue($quantitylink)->addExtraClass('ajaxQuantityField_qtylink'); } }
php
{ "resource": "" }
q257979
AddressBook.getExistingAddressFields
test
public function getExistingAddressFields() { $member = Security::getCurrentUser(); if ($member && $member->AddressBook()->exists()) { $addressoptions = $member->AddressBook()->sort('Created', 'DESC')->map('ID', 'toString')->toArray(); $addressoptions['newaddress'] = _t('SilverShop\Model\Address.CreateNewAddress', 'Create new address'); $fieldtype = count($addressoptions) > 3 ? DropdownField::class : OptionsetField::class; $label = _t("SilverShop\Model\Address.Existing{$this->addresstype}Address", "Existing {$this->addresstype} Address"); return FieldList::create( $fieldtype::create( $this->addresstype . 'AddressID', $label, $addressoptions, $member->{'Default' . $this->addresstype . 'AddressID'} )->addExtraClass('existingValues') ); } return null; }
php
{ "resource": "" }
q257980
Order.getCMSFields
test
public function getCMSFields() { $fields = FieldList::create(TabSet::create('Root', Tab::create('Main'))); $fs = '<div class="field">'; $fe = '</div>'; $parts = array( DropdownField::create('Status', $this->fieldLabel('Status'), self::get_order_status_options()), LiteralField::create('Customer', $fs . $this->renderWith('SilverShop\Admin\OrderAdmin_Customer') . $fe), LiteralField::create('Addresses', $fs . $this->renderWith('SilverShop\Admin\OrderAdmin_Addresses') . $fe), LiteralField::create('Content', $fs . $this->renderWith('SilverShop\Admin\OrderAdmin_Content') . $fe), ); if ($this->Notes) { $parts[] = LiteralField::create('Notes', $fs . $this->renderWith('SilverShop\Admin\OrderAdmin_Notes') . $fe); } $fields->addFieldsToTab('Root.Main', $parts); $this->extend('updateCMSFields', $fields); if ($payments = $fields->fieldByName('Root.Payments.Payments')) { $fields->removeByName('Payments'); $fields->insertAfter('Content', $payments); $payments->addExtraClass('order-payments'); } return $fields; }
php
{ "resource": "" }
q257981
Order.getDefaultSearchContext
test
public function getDefaultSearchContext() { $context = parent::getDefaultSearchContext(); $fields = $context->getFields(); $validStates = self::config()->placed_status; $statusOptions = array_filter(self::get_order_status_options(), function ($k) use ($validStates) { return in_array($k, $validStates); }, ARRAY_FILTER_USE_KEY); $fields->push( // TODO: Allow filtering by multiple statuses DropdownField::create('Status', $this->fieldLabel('Status')) ->setSource($statusOptions) ->setHasEmptyDefault(true) ); // add date range filtering $fields->insertBefore( 'Status', DateField::create('DateFrom', _t(__CLASS__ . '.DateFrom', 'Date from')) ); $fields->insertBefore( 'Status', DateField::create('DateTo', _t(__CLASS__ . '.DateTo', 'Date to')) ); // get the array, to maniplulate name, and fullname seperately $filters = $context->getFilters(); $filters['DateFrom'] = GreaterThanFilter::create('Placed'); $filters['DateTo'] = LessThanFilter::create('Placed'); // filter customer need to use a bunch of different sources $filters['Name'] = MultiFieldPartialMatchFilter::create( 'FirstName', false, ['SplitWords'], [ 'Surname', 'Member.FirstName', 'Member.Surname', 'BillingAddress.FirstName', 'BillingAddress.Surname', 'ShippingAddress.FirstName', 'ShippingAddress.Surname', ] ); $context->setFilters($filters); $this->extend('updateDefaultSearchContext', $context); return $context; }
php
{ "resource": "" }
q257982
Order.getComponents
test
public function getComponents($componentName, $id = null) { $components = parent::getComponents($componentName, $id); if ($componentName === 'Items' && get_class($components) !== UnsavedRelationList::class) { $query = $components->dataQuery(); $components = OrderItemList::create(OrderItem::class, 'OrderID'); $components->setDataQuery($query); $components = $components->forForeignID($this->ID); } return $components; }
php
{ "resource": "" }
q257983
Order.calculate
test
public function calculate() { if (!$this->IsCart()) { return $this->Total; } $calculator = OrderTotalCalculator::create($this); return $this->Total = $calculator->calculate(); }
php
{ "resource": "" }
q257984
Order.getModifier
test
public function getModifier($className, $forcecreate = false) { $calculator = OrderTotalCalculator::create($this); return $calculator->getModifier($className, $forcecreate); }
php
{ "resource": "" }
q257985
Order.TotalOutstanding
test
public function TotalOutstanding($includeAuthorized = true) { return round( $this->GrandTotal() - ($includeAuthorized ? $this->TotalPaidOrAuthorized() : $this->TotalPaid()), self::config()->rounding_precision ); }
php
{ "resource": "" }
q257986
Order.Link
test
public function Link() { if (Security::getCurrentUser()) { $link = Controller::join_links(AccountPage::find_link(), 'order', $this->ID); } $link = CheckoutPage::find_link(false, 'order', $this->ID); $this->extend('updateLink', $link); return $link; }
php
{ "resource": "" }
q257987
Order.canPay
test
public function canPay($member = null) { $extended = $this->extendedCan(__FUNCTION__, $member); if ($extended !== null) { return $extended; } if (!in_array($this->Status, self::config()->payable_status)) { return false; } if ($this->TotalOutstanding(true) > 0 && empty($this->Paid)) { return true; } return false; }
php
{ "resource": "" }
q257988
Order.canDelete
test
public function canDelete($member = null) { $extended = $this->extendedCan(__FUNCTION__, $member); if ($extended !== null) { return $extended; } return false; }
php
{ "resource": "" }
q257989
Order.canView
test
public function canView($member = null) { $extended = $this->extendedCan(__FUNCTION__, $member); if ($extended !== null) { return $extended; } return true; }
php
{ "resource": "" }
q257990
Order.getName
test
public function getName() { $firstname = $this->FirstName ? $this->FirstName : $this->Member()->FirstName; $surname = $this->FirstName ? $this->Surname : $this->Member()->Surname; return implode(' ', array_filter(array($firstname, $surname))); }
php
{ "resource": "" }
q257991
Order.getBillingAddress
test
public function getBillingAddress() { if (!$this->SeparateBillingAddress && $this->ShippingAddressID === $this->BillingAddressID) { return $this->getShippingAddress(); } else { return $this->getAddress('Billing'); } }
php
{ "resource": "" }
q257992
Order.generateReference
test
public function generateReference() { $reference = str_pad($this->ID, self::$reference_id_padding, '0', STR_PAD_LEFT); $this->extend('generateReference', $reference); $candidate = $reference; //prevent generating references that are the same $count = 0; while (Order::get()->filter('Reference', $candidate)->count() > 0) { $count++; $candidate = $reference . '' . $count; } $this->Reference = $candidate; }
php
{ "resource": "" }
q257993
Order.onBeforeWrite
test
protected function onBeforeWrite() { parent::onBeforeWrite(); if (!$this->getField('Reference') && in_array($this->Status, self::$placed_status)) { $this->generateReference(); } // perform status transition if ($this->isInDB() && $this->isChanged('Status')) { $this->statusTransition( empty($this->original['Status']) ? 'Cart' : $this->original['Status'], $this->Status ); } // While the order is unfinished/cart, always store the current locale with the order. // We do this everytime an order is saved, because the user might change locale (language-switch). if ($this->Status == 'Cart') { $this->Locale = ShopTools::get_current_locale(); } }
php
{ "resource": "" }
q257994
Order.onBeforeDelete
test
protected function onBeforeDelete() { foreach ($this->Items() as $item) { $item->delete(); } foreach ($this->Modifiers() as $modifier) { $modifier->delete(); } foreach ($this->OrderStatusLogs() as $logEntry) { $logEntry->delete(); } // just remove the payment relations… // that way payment objects still persist (they might be relevant for book-keeping?) $this->Payments()->removeAll(); parent::onBeforeDelete(); }
php
{ "resource": "" }
q257995
Order.provideI18nEntities
test
public function provideI18nEntities() { $entities = parent::provideI18nEntities(); // collect all the payment status values foreach ($this->dbObject('Status')->enumValues() as $value) { $key = strtoupper($value); $entities[__CLASS__ . ".STATUS_$key"] = array( $value, "Translation of the order status '$value'", ); } return $entities; }
php
{ "resource": "" }
q257996
CartEditField.Field
test
public function Field($properties = array()) { $editables = $this->editableItems(); $customcartdata = array( 'Items' => $editables, ); // NOTE: this was originally incorrect - passing just $editables and $customcartdata // which broke modules like Display_Logic. $this->extend('onBeforeRender', $this, $editables, $customcartdata); return SSViewer::execute_template( $this->template, $this->cart->customise($customcartdata), array('Editable' => true) ); }
php
{ "resource": "" }
q257997
CartEditField.editableItems
test
protected function editableItems() { $editables = ArrayList::create(); foreach ($this->items as $item) { $buyable = $item->Buyable(); if (!$buyable) { continue; } // If the buyable is a variation, use the belonging product instead for variation-form generation if ($buyable instanceof Variation) { $buyable = $buyable->Product(); } $name = $this->name . "[$item->ID]"; $quantity = TextField::create( $name . '[Quantity]', 'Quantity', $item->Quantity ) ->addExtraClass('numeric') ->setAttribute('type', 'number') ->setAttribute('min', '0'); $variationfield = false; if ($buyable->hasMany('Variations')) { $variations = $buyable->Variations(); if ($variations->exists()) { $variationfield = DropdownField::create( $name . '[ProductVariationID]', _t('SilverShop\Model\Variation\Variation.SINGULARNAME', 'Variation'), $variations->map('ID', 'Title'), $item->ProductVariationID ); } } $remove = CheckboxField::create($name . '[Remove]', _t('SilverShop\Generic.Remove', 'Remove')); $editables->push( $item->customise( array( 'QuantityField' => $quantity, 'VariationField' => $variationfield, 'RemoveField' => $remove, ) ) ); } if (is_callable($this->editableItemsCallback)) { $callback = $this->editableItemsCallback; $editables = $callback($editables); } return $editables; }
php
{ "resource": "" }
q257998
AccountPage.find_link
test
public static function find_link($urlSegment = false) { $page = self::get_if_account_page_exists(); return ($urlSegment) ? $page->URLSegment : $page->Link(); }
php
{ "resource": "" }
q257999
AccountPage.get_order_link
test
public static function get_order_link($orderID, $urlSegment = false) { $page = self::get_if_account_page_exists(); return ($urlSegment ? $page->URLSegment . '/' : $page->Link()) . 'order/' . $orderID; }
php
{ "resource": "" }