diff --git a/.gitattributes b/.gitattributes index ad81fb500..e2a25ba08 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,2 @@ docs/ export-ignore docs_user/ export-ignore -.travis.yml export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..0330d2db5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,16 @@ +name: CI + +on: + push: + pull_request: + workflow_dispatch: + +jobs: + ci: + name: CI + uses: silverstripe/gha-ci/.github/workflows/ci.yml@v1 + with: + composer_require_extra: + phpunit/phpunit:^9.5 + silverstripe/silverstripe-omnipay:dev-master + php-http/discovery:^1.18.1 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 504474fe1..000000000 --- a/.travis.yml +++ /dev/null @@ -1,45 +0,0 @@ -language: php - -dist: trusty - -env: - global: - - COMPOSER_ROOT_VERSION=3.0.x-dev - -matrix: - include: - # - php: 7.3 - # env: DB=MYSQL INSTALLER_VERSION=4.4.x-dev PHPCS_TEST=1 PHPUNIT_TEST=1 - - php: 7.3 - env: DB=MYSQL INSTALLER_VERSION=4.4.x-dev PHPUNIT_TEST=1 - - php: 7.3 - env: DB=PGSQL INSTALLER_VERSION=4.4.x-dev PHPUNIT_TEST=1 - - php: 7.3 - env: DB=MYSQL INSTALLER_VERSION=4.4.x-dev PHPUNIT_COVERAGE_TEST=1 - -before_script: - - phpenv rehash - - phpenv config-rm xdebug.ini || true - - echo 'memory_limit = 3096M' >> ~/.phpenv/versions/$(phpenv version-name)/etc/conf.d/travis.ini - - export PATH=~/.composer/vendor/bin:$PATH - - composer validate - - if [[ $DB == PGSQL ]]; then composer require silverstripe/postgresql:^2.2 --no-update; fi - - composer install --prefer-source --no-interaction --no-progress --no-suggest --optimize-autoloader --verbose --profile - - composer require --no-update silverstripe/installer:$INSTALLER_VERSION - - if [[ $PHPCS_TEST ]]; then composer require squizlabs/php_codesniffer:^3 --prefer-dist --no-interaction --no-progress --no-suggest -o; fi - -script: - - if [[ $PHPUNIT_TEST ]]; then vendor/bin/phpunit; fi - - if [[ $PHPUNIT_COVERAGE_TEST ]]; then phpdbg -qrr vendor/bin/phpunit --coverage-clover=coverage.xml; fi - - if [[ $PHPCS_TEST ]]; then vendor/bin/phpcs -s src/ tests/; fi - -after_success: - - if [[ $PHPUNIT_COVERAGE_TEST ]]; then bash <(curl -s https://codecov.io/bash) -f coverage.xml; fi - -notifications: - webhooks: - urls: - - 'https://webhooks.gitter.im/e/a3720004986a0f249abc' - on_success: change - on_failure: always - on_start: false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d1e3c5fe3..efc686b65 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,7 +5,7 @@ This module only moves forward as we each build the features we need. We love pu ### Here is a quick list of ways you can contribute: * __Test the latest code__. Install it and try it out. - * __Code new features and bug fixes__. Make sure to check our [Trello board](https://trello.com/b/85ZyINqI/silvershop-development-planning) for upcoming features. Submit github pull requests. Don't forget to write PHPUnit tests that ensure your code runs. All pull requests are automatically tested [via TravisCI](https://travis-ci.org/silvershop/silvershop-core/pull_requests). + * __Code new features and bug fixes__. Make sure to check our [Trello board](https://trello.com/b/85ZyINqI/silvershop-development-planning) for upcoming features. Submit github pull requests. Don't forget to write PHPUnit tests that ensure your code runs. * __Submit issues and ideas__. These can be bugs, or ideas. Be descriptive and detailed. Its better to discuss and design ideas before writing code. Please first check the [list of existing issues](https://github.com/silvershop/silvershop-core/issues) to make sure an identical one doesn't exist already. * __Write documentation__. Both the developer and user documentation can have pieces missing. Documentation is stored in the repository under `/shop/docs`, and `/shop/docs_user`. Documentation gets displayed at http://docs.ss-shop.org * __Provide translations__. This will allow people speaking other languages to use the shop module. diff --git a/ChangeLog.md b/ChangeLog.md deleted file mode 100644 index 57d79d95d..000000000 --- a/ChangeLog.md +++ /dev/null @@ -1,607 +0,0 @@ -# SilverShop ChangeLog - -## Unreleased 3.x - -- Add new `VisibleToCustomer` flag to `OrderStatusLog`. Use it alongside the existing `SentToCustomer` flags to allow developers to store additional admin-only log messages attached to orders. -- Add new `order_is_required` config flag to `OrderStatusLog`, set to true by default (for backwards-compatibility). Set it to `false` to allow `OrderStatusLog` objects to be created that are not linked to any particular `Order` object. - -## 3.0.0 - -Introduces SilverStripe 4 support and full namespaces. - -### Removals - - - Removed all Dashboard classes. The dashboard module is not yet ready for SilverStripe 4. - This functionality should be added via a separate module whenever the need for it arises. - - `ShopAccountFormValidator` was removed. It was there to fix a core issue that no longer exists in SS4 - - `Zone` and regions have been moved out to the `silvershop-shipping` module - - `CostPrice` was removed from `Product` as it is not used and creates confusion for content-authors. - - `ShopEmail` was removed, as it's no longer needed with the new SwiftMailer API. - -## 2.3.1 - -Fix a bug (regression) where the variation-form was no longer displayed in cart. - -## 2.3.0 - - - Fix issue with unset failover object. Improve travis config. (#611) - - Migrate to using beforeUpdateCMSFields - - Use Buyable instead of Product in CartEditField (#606) - - Placed added to group by (#603) - - Fix message encoding issue with VariationForm (#601) - - Fix issue with potentailly non-existing failover object. (#600) - - Allow extensions to hook into the permission methods of Order. (#599) - - Some minor documentation improvements. Added a section about CSV import and additional categories (#592) - - Fix issue in CheckoutStep_Summary.php (#591) - - Fix issue where VariationForm fields had no form value set (#589) - -## 2.2.1 - -Security Update: Updated indirect PHPMailer dependency that fixes a critical security issue. - -## 2.2.0 - - * Fix GlobalTaxModifier (Roman Schmid) - * Improve/enable custom properties on OrderItems. (Roman Schmid) - * fix price in templates (rasstislav) - * Ensure payment forms use the field renaming feature added to the omnipay module. Updated composer.json (Roman Schmid) - * removed old code from SimpleShippingModifier. It now simply looks at order shipping adress country to determine the shipping cost (Sander Hagenaars) - * Fix variation title so it can be extended (Adrian Stein) - * Improving the PHPDocs (Chris Lock) - * Setting the Type in constructor (Bram de Leeuw) - * Added a config hook to use a custom notifier (#570) (Chris Lock) - * Fix german translation file. (Roman Schmid) - -## 2.1.1 - - * Fix issue (introduced with 2.1) where Order receipt was never sent #563 - * Minor templating update. - -## 2.1 - - * Order-Status Email notifications #534 - * Improve previewing and developing of Email templates #551 - * append symbol setting for European style currencies #549 - * Improve order-hooks #557 - * FIX: Set Order->Paid Date alongside Order->Status - * FIX: Add reverse relation for addresses - * Updates to templates (validating markup, proper indentation) - * Improvements to documentation and example files. - -## 2.0 - - * Overhaul of the localization of the module. (#379, #381, #383, #384, #408, #410, #411, #451, #453, #456, #457, #470, #486) - * Better Addressbook UI (#452) - * Use `::create` syntax for object instantiation (#415) - * Shop Emails use inline CSS by using Emogrifier (#466) - * Order-calculations and order-placement are now wrapped in Database transactions (#506) - * Products that have Variations can not be added to cart, only a Variation can (#516) - * Products with no price (`0.0`) will now be displayed if they have Variations (#516) - * Variations without a price will no longer show up, unless `Product.allow_zero_price` is set to `true` (#516) - * Updated codebase to use the 2.0 version of silverstripe-omnipay - -## 1.3.1 - - * Improve variation-form performance (#512) - * Fix Cart template issue showing up in SilverStripe 3.4 (#503) - * Better extensibility of ShoppingCart (#494) - * Some documentation improvements - -## 1.3.0 - - * Update to SilverShop organization, cleaned up config files, updated composer.json and readme files. - * Added support for including `OnsitePaymentCheckoutComponent` on first page of single page checkout (#266). - * Fixed issue with address duplication due to blank or readonly fields (#431) - * Names on shipping and billing address will now default to the main order name (#435) - * `transactionId` now changes for subsequent payments on the same order (#439) - * Physical properties have been added to variations (#437) - * WeightShippingModifier can now be configured via Config files (#462) - * Added support for partial postcodes within GB (#440) - * Cleaned up order-receipt email styles (#441, #469) - * Security tokens can now be disabled for shopping-cart links (#482) - * Fixed issue where cart was cleared after viewing archived order (#492) - * Several other small fixes and improvements. - -## 1.2.0 - - * Translations updated from old format - * Additional extension hooks added - * Templates updated to use the correct translation keys - * Other improvements to the default tmeplates - * `Object::create` syntax is used more consistently to allow use of the Injector - * Fixes some compatibility bugs with SS3.2 - * Fixed bug where some admin notifications were sent to customer - * Reformatted code to use spaces instead of tabs as a first step towards PSR-2 - -## 1.1.1 - - * Tests pass against SilverStripe 3.2 and increased coverage slightly - * Better use of Object::create and therefore the injector - * Fixes a few issue with translatability - * Added function to check if checkout step exists - * Added some extension hooks - -### Enhancements: - - * Include jQuery javascript requirement in AddressBookCheckoutComponent - * Use `getRequiredFields` in the Address' validate method. - * Added CheckoutStep_Summary component config extension hook. - * Support DI in PaymentForm and CheckoutComponent - * Add extension point for ProductsShowable - * Change new Form to Form::create - -### Bug Fixes: - - * Changed PriceRange value to be use sellingPrice not Price - * Increased Scrutinizer code coverage timeout - * Don't return a form if no actions are present in OrderManipulation - * FIX: ensure required fields are correctly looked up in the config - * Added translation to 2 missing strings - -## 1.1.0 - - * Units for physical measurements are customisable - * Hooks for better ajax support (see markguinn/silverstripe-ajax and markguinn/silverstripe-shop-ajax for one implementation) - * 2 new reports and 3 new dashboard panels - * Order processing emails refactored into OrderEmailNotifier (with some deprecations for 2.0) - * Fixed several issues with checkout - * Code cleanup in several places, most notably CartForm - * Bugs fixed - -## 1.0.0 - - * Upgraded to SilverStripe version 3. - * Switched from Payment module to Omnipay module. - * Single form and multi-step checkout system. - * Documentation has been updated. - * Many shop sub-modules have been developed and updated and improved in conjunction with this release. - -### Enhancements: - - * Added analytics to suggested modules - * Added a bunch of add-on modules to README - * Added gitter integration with travis - * shop period report was failing in postgres Added test to reveal issue with ShopPeriodReport in prostgres - * Added ability to update ProductCategory_Controller's ListSorter - * Introduced place_before_payment config on Order to allow configuring checkout to place order before making payment. - * Populate OrdersAdmin search form with selected Statuses. Added some comments - * Added classes to OrderAdmin_* templates to allow for better styling - * Added CONTRIBUTING.md - * Added recipe for setting default admin panel to orders - * Added total outstanding to orderadmin subtotals. Other small template improvements - * Added open graph type function to set products to type 'product'. Allow specifying a minimum size the open graph image must be - * Added in open graph image function to Product. This will be picked up by the open graph module, if it is installed. - * Added 'SelectedPaymentMethod' to CheckoutStep_PaymentMethod, for including in templates. - * Merge pull request #257 from markguinn/patch-1 - * Added 1.0.x-dev branch alias to composer.json - * Creating an order instance should use the Injector - * Allow order to hook into validate data on checkout - * Added 'payablecart' fixture to yaml Orders - * Added subtitle to order items - * Added comment to Order->getModifier - * Added in extraDataObjects flag for test which newly has classes implementing TestOnly interface - * Add for use in email templates - * Added hook for updateVariationAddToCartAjax and updateVariationAddToCart - * Added hook for updateVariationAddToCartAjax and updateVariationAddToCart - * added updateVariationAddToCartMessage hook - * Added ability to define title separator for getTitle - * Added another cart to shop.yml fixture Converted ShopTest to a helper class. - * Added hack to allow overriding Address required_fields - * Added set MemberID on order in OrderProcessor (if not already set). This helps to ensure member is set, when a member is logge - * Merge pull request #242 from markguinn/feature-default-image - * Added default product image - * Added discount submodule suggestion to composer.json. Removed old composer silverstripe-payment config. - * Added country drop down to Address CMSFields - * Tidied OrderManipulation to use ss3 ORM. Improved OrderActionsForm a bit also. Added some testing. - * use correct config variables in OrderActionsForm …remove redundant config fields from OrderManipulation. Added some tests - * Added CheckoutPage_payment template for independently styling the on-site payment entry page. - * Added suggested submodule: comparison - * Added instructions for populating shop - * Added default ID to product of ‘-1’ . This will hide products from the site tree when they are created in model admin. Useful - * Added forTemplate function to ShopCurrency. - * Added CMS icons for orders, catalog, and zone sections - * Updated statics in ProductAttributeValue Added ‘Product’ reverse belongs_many_many relationship to ProductAttributeType - * Added some extra data to dummyproducts.yml - * Created CartForm, allowing for adjusting cart items by submitting a form. The Cart template is still used, and is embedde - * Allow choosing type of quantity field for order items. - * Added missing config to CheckoutComponentTest - * Added ‘dependson’ functionality to checkout components. This meant that I could allow creating new memberships. - * checkout component base class - * Added error message to redirect url get param for CheckoutStep_Summary - * Added note about payment module status - * Added some badges for various services - * Added onPayment and onPaid extension points in OrderProcessor - * Added InternalItemID to ProductVariation searchable fields - * Added updateProductCMSFields hook for better control of product fields Added updateSellingPrice hook to ProductVariation Swapp - * Added allowed actions to Product_Controller for compatibility with silverstripe 3.1 - * Added summary fields to Zone - * Updated DeleteProductsTask to show delete count - * create international zone task, useful for quickly creating an international zone that can be customised to exclude some - * Introduced helper class "SortControl", for managing data that can be used in sort drop downs, and produce appropriate SQL - * Allow setting default string to som - * Allow the shop base folder to be something other than 'shop' - * Improved popularity calculation algorithm to factor in age of sales and age of product - * Added total to 'othercart' in shop yml test fixture - * Created task to recalculate product popularity (based on sales numbers) - * Added Product report, Customer report. Fixed sorting in ShopSales Report - * Added ability to set individual payment status' in order admin. - * Added more useful testing data to shop.yml fixture file. - * Created a ShopSalesReport for observing sales for specific periods - * Added more data to shop.yml and Addresses.yml fixture files - * Added minor note about contributing to read me. - GrandTotal functions. Added docs to explain rounding. - * Added cart page to shop fixture, and ProductVersion to order items. - * Added option to PopulateShopTask to create an international Zone, with every AllowedCountry enabled. This is a quick way - * Added 'docreateaccount' to list of CheckoutStep_Membership allowed actions - * Provided hooks for all CheckoutStep forms - * Added SetLocationForm, which is useful for getting location data from the user. - -### API Changes: - - * Merge pull request #263 from silverstripe-iterators/pulls/zero-order-fix - * API Mark Order.Paid= on $allow_zero_order_total - * Added category functions to Product for fetching categories, or category ids associated with a product. - * Merge pull request #252 from silverstripe-iterators/pulls/cart-task - * API Fixed CartCleanupTask, define time in mins rather than relative - * changed ShoppingCart add and setQuantity functions to return the new/existing item, rather than returning true. - * Removed deprecated code from Order. Updated example_config.php and test_config.php accordingly - * Converted OrderItemsList to subclass of HasManyList, instead of being an extension. Overrode getComponents function in Or - * allow defining saveablefields on the AddProductForm, for security, and to allow setting fields like UnitPrice - * Created ShopPeriodReport, which can be used to create reports that apply to a specific period, and results can be grouped - * Added XML function to ShopCountry, for displaying as XML - * renamed OrderItem->place to OrderItem->onPlacement, to be consistent with other events. - * created alias ShopConfig::current() which is just SiteConfig::current_site_config() - * Added onPayment function to orderItem. This is called whenever an order's payments are completed, and can be overloaded l - * Removed Address City aliases: Suburb, County, District …they are not exactly synonymous, and could be added as separate f - * Enforce rounding when setting order 'Total'. Tidied up Total and GrandTotal functions. Added docs to explain rounding. - * Deprecated 'maximum ignorable sales payments difference' field, in favour of using rounding precision instead. - -### Bug Fixes: - - * Merge pull request #300 from markguinn/patch-member-addresses-rc2 - * Merge pull request #302 from markguinn/patch-calc-bug - * Fixes a variable name error in OrderTotalCalculator - * Fixes a checkout bug: Given a single-page checkout and given the membership component comes after the address book components, - * use buyable's createItem function instead of creating an "OrderItem" for shop quantity field. - * Merge pull request #282 from markguinn/patch-shoppingcart-error - * Fixes small bug in ShoppingCart, triggered if the session goes expires and then a user clicks a remove product link - * Fixed ShopPaymentTest, and updated composer requirement to omnipay 1.1 - * Check if buyable exists before getting image from it (OrderItem->Image) Fixes #248 - * shop period report was failing in postgres Added test to reveal issue with ShopPeriodReport in prostgres - * ShopPeriodReport SQLQueryList closure should be php 5.3 compatible. - * omnipay's transactionId represents the order reference. The transactionReference should be reserved for data that gateway - * missing member breaks parameterFields function in unit tests - * start/end dates in ShopPeriodReports weren't being used in the correct format. - * Fixed pagination, sorting etc by creating/requiring a special kind of 'SQLQueryLsit' Fixed product report link Removed Week gr - * Merge pull request #278 from markguinn/patch-print-order-fix - * Fixed bug when printing order in admin - * removed OrderModifierLazyLoadFix extension call from OrderModifier - * Removed hack that for core that has been fixed in - * Travis will test master branch of cms/framework, but failure is allowed. - * getSelectedPaymentMethod throws error if nice=true, and method is not in list - * insert payments grid field after Content, instead of before Notes, because sometimes Notes field doesn't exist. - * Print functionality broke edit saving. made print button have an icon. - * Reintroduced print from CMS functionality fixes #45 fixes #167 - * make open graph image url absolute - * Merge pull request #271 from webtorque7/master - * Fix recursive ChildCategories on ProductCategory - * Merge pull request #264 from halkyon/sessids_fix - * Merge commit 'ed68ce113385bb6ab3faee85a90fbef5390a8550' - * Removed AccountNavigation $LinkingMode template calls, because they don't work. fixes #235 thanks @nimeso! - * Fixing case where add_session_order() isn't called on $0 orders - * display full country name in address readonly field updated shopconfig->getSingleCountry to allow returning full country - * address country was not saving properly with previous `getSingleCountry` improvement - * Country address field should not be required if it is the only field available (and is read-only). - * If there is only one country allowed, then we need to ensure that country overrides ShopUserInfo location. - * shipping address checkout step should update billing address, if "separate billing" is not selected. - * Merge pull request #260 from markguinn/patch-payment-bug1 - * Removed bad null return from OrderTotalCalculator - * Fixed bug in payment form - * added missing getCategoryIDs and getCategories functions to ProductVariations. relates to 7eee4a11c33cf581524a61d44195f7a - * Get proper message from correct object in payment form - * Removed unnecessary 'setWhere' that was breaking ShopSalesReport - * Merge pull request #254 from silverstripe-iterators/pulls/fix-cartcleanuptest - * Fixed SQL case sensitivity in CartCleanupTaskTest - * Select Order.Paid field when using having in ShopPeriodReport. Fixes #253 - * Updated ShopPeriodReport to hopefully finally be compatible with pgsql - * don't throw an error when trying to recalculate an order that isn't cart. - * made ShopPeriodReport cross-db compatible. Disabled reporting by week, as this is hard to support. - * Merge pull request #251 from madmatt/pulls/ProductImageTest-fix - * Create assets/ directory in ProductImageTest if it doesn't exist - * cart wasn't recalculating when needed. - * Fixed 'receipt_email' configuration - * Fixed OrderStatusLog usage - * Error message shows 'Email' now, and passed through to processPaymentResponse - * Fix staging site not allowing any products to be tested. - * make lazy loading hack work with pgsql - * Fix travis tests by installing phpunit via composer - * a hack solution to get around existing lazy loading issue see: https://github.com/silverstripe/silverstripe-framework/iss - * Fixed reference to login_joins_cart fixes #249 thanks @nimeso - * allow changing payment currency fixes #239 - * Make sure billing address is set, even if it isn't entered. Fixes #247 - * Offsite payments were preventing order from being viewed. Fixed by 'archiving' shopping cart session id to order manipula - * Fixes bug where product reports itself as in the cart when it's not - * Make sure order receipt is only sent once order updating has finished (so that sent data is correct). Fixes: #238 - * order outstanding payments were not working relates to: #229 - * Use correct cancel url configuration name. don't allow cart orders to show up in AccountPage - * updated CustomProductTest to work with fixed Buyable canPurchase api - * Fixes for issues picked up by scrutinizer - * scrutinizer config file - * Don't allow Order->calculate function to be called if it's status is not 'Cart'. Clear current order from the cart when placin - * don't allow manual payments on orderActionsForm. - * updated payment functionality, according to omnipay changes - * updated scrutiniser timing fixed README stats badges - * OrderManipulation allorders typo - * OrderManipulation orderfromid was return a boolean, rather than int fixes #224 - * fixed various issues that were failing unit tests - * use correct config variables in OrderActionsForm …remove redundant config fields from OrderManipulation. Added some tests - * reorganised the OrderActionsForm to work better Started a unit test to check the actions form. - * If only one payment method fix - * Removed ability to hide products from the tree.^P This can be left to a recipe for edge-case development. fixes #210 - * Display category nesting in ProductCategories field. - * Fixed sort options on category page - * Merge pull request #213 from nimeso/patch-3 - * Fixed Image function if variation deleted - * updated FeaturedProduct references - * statics config changes fixes #209 - * allow removing items via CartForm by entering 0 or less for quantity. VaraitionField was always causing a ‘change’, - * update order after offsite payment has been made - * Fixed Cart template to hide additional column, when not needed. - * removed debugging code - * use proper function when getting selectedPayment type - * test product variation subtitle wasn’t working. - * Removed deprecated code - * use record editor for product variations. Fixes #193 - * NEW: Allow choosing type of quantity field for order items. - * complete orders through OrderProcessor, according to latest checkout changes - * OrderManipulation extension incorrectly applied to AccountPage, instead of AccountPage_Controller - * only validate membership data if membership data is required, or password is not empty - * order processor test correctly logs out admin user when necessary - * all unit tests now passing - * fixed most unit tests to comply with latest changes - * FIX for issue #200: shopping cart couldn’t retrieve product variations. relates to: #200, #208, #146, #179 - * canPay check was failing - * Fixed issues when running tests with mysql. Tidied some tests. Moved a few things to use the new ORM. - * instantiation chaining isn’t available until PHP5.4 - * travis shop install dir incorrect - * Added missing extension - * broken SteppedCheckoutPage template - * updated old `control` tag with `with` - * Merge pull request #188 from markguinn/patch-popularity-div-by-zero - * Fix to popularity calculation returns null if product was bought today. - * Merge pull request #183 from moveforward/134-keep-variations - * fixes #134 - variations deleted if owner is deleted (not staged) - * Merge pull request #182 from moveforward/181-checkout-link - * fixes #181 - corrects link in template - * Merge pull request #179 from moveforward/146-buyablefromrequest - * fixes #146 only live products returned for add to cart - * payments reference typo in Order.php - * updated configuration settings references on OrderForm.php - * CustomerGroup exists check was incorrect - * restore reference to $item->MainID in DropdownShopQuantityField - * composer payment require was incorrect - * Fixed up composer requirement to use proper version of payment - * Cleared out some deprecated and unused code fixes #147 - * check sellingPrice instead of Price when deciding if ProductVariation ->canPurchase - * removed old reference to FixVersioned. Thanks @nimeso. - * get CMS search fields working again. Modified scaffolded search context, and restricted orderAdmin listings to only those - * updated old references to Product_Image - * Removed Product_Image subclass, in favour of extending Image. Fixed the ShopMigrationTask - * updated composer file to install to proper directory. Renamed packagist repo to include 'silverstripe-' - * Merge pull request #154 from nimeso/ss3-fixes-1 - * Required fields for OrderForm were broken - * Fixed styling of orders in CMS - * only add live products to cart. fixes #146 - * temp fix for product bulk loader. Actual fix blocked by https://github.com/silverstripe/sapphire/pull/1781 - * updated Zone cmsFieldsTo use Grid field - * Re-introduced ProductBulkLoader fixes #136 - * Merge pull request #142 from nimeso/orderitemlist_fix - * quantiy function to use new method name - * Fixed routes.yml for shoppingcart controller Changed all references Director::redirect… to Controller::curr()->redirect Fixed - * Fixed structure of template list - * Prevent RestrictionRegionCountryDropdownField from being set to visitor country. NEW: Allow setting default string to som - * unchecked order status checkboxes were including 'Cart' statuses. Forced only specific statuses, if none are checked. BUG - * Run completePayment code in OrderProcessor regardless of whether a receipt has been sent. - * ShopSalesReport - exclude orders with no "paid" date from the report - * Fixed member not saving to order in SteppedCheckout. Updated unit tests. - * Fixed SQL escaping issue in RegionRestriction code - * Fixed tests that broke when shop.yml fixture was updated. - * fixed incorrect request function - * correctly calculate weights etc via OrderItemList - * Fixed CheckoutTest usage of assertType, which is incompatible with newer versions of PHPUnit - * use readonly field for country election when there is only one, or none. - * Various fixes to get unit tests working for SS3. Removed some unused files and code. fixes #119 - * useless function in OrderActionsForm causing segmentation fault - * Email subject order ID wasn't showing up, because Reference is a string, not a number. (sprintf %s instead of %$d) - -## 0.8.5 - -### Enhancements: - - * added hook to product link function - * Added AddProductForm to Product_Controller. Improved AddProductForm to better support the 'buyables' concept. - * improved debugging display for shoppingcart/debug. Colouring and showing item details. - * Added security token to shopping cart links, and request handling. This helps prevent CSRF attacks. - * Create unique links for updating carts with customized order items. Introduced $Buyable url param for better custom product handling, and removed OtherID url param. - * Introduced .htaccess file for added security - * Also added check for valid payment type, and items can be purchased. - * Introduced OrderItemList, an extension of ComponentSet that provides Quantity and Plural functions to allow displaying cart total quantity. Updated SideCart.ss template to make use of these new functions. - * Introduced heavy products report for finding products that might have incorrect weights. - * Added $Form to cart template. Refactored SideCart to display better. - * Improved ShopMigrationTask to handle Product VaraitionAttributeTypes relationship name change. Removed payment migration code, as it should in the payment module. - * Introduced optional SQL-based delete for cart cleanup task. Its less safe, but it's faster. - * Allow a different template to be used when rendering orders in the CMS. Re-introduced order.css file to provide good default order styling. - * Created an config option for choosing where to direct after cart manipulations. - * Created PopulateShopTask to populate the database with some dummy categories, products, and variations. - * Custom product testing and documentation. - * Enforced the buyable interface within shopping cart. Removed references to product variation. Introduced buyable_relationship static variable on OrderItem as a way to recognizese associations for custom buyable objects. - * Default template and css updates, additions and removals. - * created AddProductForm for adding products via a form submission. This should help with preventing carts from being created for no reason. Relates to #7 - * Template improvements, including adding images and subtitle to order content. - * Introduced filtering / parameter system for cart items. This allows adding customized products to the cart, and have quantities automatically update, rather than adding completely new order items. fixes #22 - * Removed custom debug statements. These were confusing, because they only provided a sub-set of the full debug information that developers are used to. - * updated Order_Content_Editable template to use better styling approaches. - * Complete rewrite of ShoppingCart. Split into two classes: ShoppingCart and ShoppingCart_Controller. The ShoppingCart class is a singleton and provides restricted access to an order for adding/removing items, and clearing the cart completely. - * cleaned up OrderItems. Removed some remaining bits of session-based cart functionality/variables that were not needed. - * used Object::useCustomClass to swap Currency with EcommerceCurrency, for template purposes. Renamed all occurrences of EcommerceCurrency back to plain old Currency. Introduced CanBeFreeCurrency class, which simply displays "FREE" when it's value is 0; - * moved migration code from requireDefaultRecords to ShopMigrationTask - * Further overhaul of modifiers system. Renamed $order->CalculateModifiers() to $order->calculate(), as it applies to totals also. Fixed all modifiers and tests to use new format. - * Moved default record creation into PopulateShopTask. - * Major changes to modifiers system. They now are calculated via Order->CalculateModifiers, rather than internally. This is because they rely on a continuous calculation from the items SubTotal..through each modifier, and eventually producing the total. - -### API Changes: - - * Made ShoppingCart_Controller direct function static, to allow it to be called from outside classes. - * Split Order - Attributes relationship into Order - Items and Order - Modifiers so that sets can be distinctly retrieved and updated with the built in ComponentSet functionality. - * Renamed EcommercePayment to ShopPayment. - * Added cart and checkout links to ViewableCart. Added find_link to CartPage, along with the ability to display a cart without a CartPage. - * Decoupled order processing from Order and OrderForm. Decoupled email creation from Order. Created OrderProcessor to handle processing / fulfillment. fixes #23 fixes #3 - * Renamed ProductGroup to ProductCategory. This new name better suits the purpose the class serves. - -### Bug Fixes: - - * moved development admin to using proper url rule, rather than the decorator approach. The bug was that the 'shop' action was allowed on any controller. - * fixed invalid reference when getting OrderItem links - * fixed null reference for terms page on order form - * Terms and conditions are now checked properly. - * fixed links and function references in ShopDatabaseAdmin relates to renaming in 7843309144a42eed230ddf1816f1a5601a36093f - * typo in product variation code - * fixed order printing bug. - * got variations working again with the new shopping cart improvements. - * MatchObjectFilter was including has_ones that it shouldn't. - * cart contents showing on checkout page. MINOR: Removed sessionID from order. Past orders are now stored in a session array instead. - * orders now calculate during migration task, if they don't have a Total - * Temporary solution for fixing Versioned, to allow storing product versions against order items. Fixes issue #15 - * updated reference to deprecated ShoppingCart function. Fixes issue #20 - * introduced an interim fix for versioned issue. Added static variable to disable using versioned. - * remove modifiers that aren't in Order::. Deprecatd CartValue now points to TableValue, instead of TableTitle - * Fixed ability to remove modifiers. - -## 0.8.3 - - * Renamed module to 'shop', and changed all 'ecommerce' directory references to 'shop', in line with new name for the module. - * Added in CalculatedTotal to OrderAttribute for the purpose of permanantly storing old values, and helping with order read speed. - * Made VariaionForm the default way to add product variations. - * Allowed checkout page to not require a page model. - * updated documentation to include packages, and sub packages for phpdoc - * Ability to add product attribute values from product edit page, rather than model admin. - * Removed OrderFormWithoutShippingAddress, and OrderFormWithShippingAddress - -## 0.8.2 - - * Modified order form to allow orders to be placed without becoming a member in the process. - * Introduced EcommerceRole::associate_to_current_order() for choosing to join order to member on login. - * Added CartPage action and template "finished", which displays the order just placed. - * Copied all ecommerce member fields to Order, so that orders can be placed without member. - * Added docs folder, along with some developer and user documentation - * Introduced mysite/dev/ecommerce to get quick access to ecommerce dev tools - * Began updating test suite - * Introduced the ability to pay and cancel incomplete orders - * Introduced ECOMMERCE_DIR constant to allow ecommerce directory to be different. Note that some paths are still make use of 'ecommerce'. - -## 0.7 - 0.8.1 - - * Variations working again - * Re-structured default templates to be more hierartical and extensible. Removed redundant templates. - * Implemented new reciept design - * Updated CMS Order interface - * Introduced FullBillingAddress and FullShippingAddress functions on Order to provide ways to get combined address fields. - - * Merged in DBCart, Burnbright, and SunnySideUp branches - * Depricated AllowPurchase function on Product & ProductVariation in favour of canPurcahse. SilverStripe has can____ capabilites built in, and AllowPurchase was overriding the DB field. - * Improved ProductBulkLoader to allow setting ProductGroup, and linking up an image of the product. - * Merged ShoppingCart and ShoppingCart_Controller into one class - * Introduced filters/paremeters system for more complex cart situations - -0.6.1 - - * Modified code to work with SS 2.4, and payment trunk as @ revision 103257. This mainly involved supporting the Money class. - * Separated out unnecessary css styling. The default style is very much tied to black candy. (This can be put into a theme) - * Improved efficiency of ProductGroup to make one database call to retrieve products. All ProductGroup children are retrieved by default, rather than just the immediate children. - * Removed 'ShowInMenus' condition for displaying group products. - * Added sorting controls to ProductGroup pages - * Added pagination to default ProductGroup template - * Removed separation of featured and non-featured products. The default sort is set to show featured products, then the rest by title (similar to TradeMe.co.nz) - * Tidied up invoice printing - * Got the 'all orders' SS report working again - * Added 'Store' model admin for orders - * Show products in multiple categories (does not yet include recursive sub-category products) - * Variations of the same product can now be added to the cart together - * Prevented order payment form showing on checkout template if nothing is in shopping cart. - * Re-ordered CMS fields so they are more visible (eg price, weight, model) - * Updated sitetree icons (product = package, checkout = shopping cart, account = contact card) - * Include shopping cart page type - * Removed quantity selectors from products on group page, as they can be updated using the cart on the left. - * Added support for calculating and storing the number of products sold - -0.6 - - * Data model changes (see http://doc.silverstripe.com/doku.php?id=ecommerce:overview&s=ecommerce) - * PHP files moved into folders for grouping of models, controllers and forms - * Fixed undefined find_link() function on AccountPage_Controller - * Check that the member can create a member with the unique field - * Added translation for Arabic (Saudi Arabia) - thanks to Talal - * Fixed template call to Text::LimitWordCountPlainText() - * Fixed ID quoting in Product_Controller->addVariation() - * #3939 Ability to show all products in ProductGroup - * Fixed ShoppingCart index item to be the product ID - * Re-added link methods back to Product_OrderItem from OrderItem - * More agressive checking of Payment before creating a new Order on OrderForm - * Added empty statics to various ecommerce classes to support decoration of statics via DataObjectDecorator - * Creation of OrderItem with Product data record properly - * Fixed Order::isPaid() to correspond to the Status enum field - * If EcommerceRole::findCountry() cannot find the user's country, don't cause an error - * Fixed Order->_ModifiersSubTotal() to exclude classes properly - * Stopped errors occurring if calling shoppingcart/additem without an index ID - * Fixed failing from address in the email for status updates - * Fixed order status log not working properly - * Changed reports to use TableListField, and fixed printing - * Removed old CheckoutPage.js code that was broken, replaced with working version - * Renamed MemberForm to ShopAccountForm since this is too general - * Removed specifically set CMS fields, these are now scaffolded. - * Moved payment class URL rules to payment module _config.php - * Product title not displayed in Receipt Email. Ticket #3680 - * Fixed price still showing even if price set to 0 in product - * Moved Eway.js from ecommerce to payment module - * Moved Eway payments to payments module - * Removed restrictive decimal for Tax Rate field and replaced with double type - * Gracefully degrade if member is not logged in on MemberForm - * Fixed setRelationAutoSetting method that may not exist in old SS version - * Add payment decorator to ecommerce, since payment classes now split into payments module - * Added information about payment module being required - * Separate payments into a separate module ("payment" module) - * disable two deprecated functions in ecommerce/code/_config.php - * Fixing usage of deprecated APIs - * Make sure array in set_payment_methods() is associative - * Cleaned up OrderReport to use non-deprecated APIs, refactored to use TableListField - * Update i18n entities since the Report class was renamed - * Updated ecommerce report classes to reflect change from Report to SSReport - * removed ecommerce jquery directory that isn't being used anymore - * Removed javascript that shouldn't be done until we've got more of a stable platform - * Instead of hardcoding css/js requirements into Report.php - * Deleted ViewAllProducts.ss which was a relic of the now deleted DataReport API - * Removed "abstract" Report class, which is now in the cms module - * documentation of vital methods on Payment class - * added links to examples for LiveAmount() on OrderModifier - * Added documentation to OrderModifier::is_chargable - * If amount for an OrderModifier is not chargable, then show a minus sign - * added a better description to OrderModifier->TableTitle - * Lots of code documentation and cleanup of code - * Changed Order_Attribute to OrderAttribute, since this is operates on its own separate from Order - * If a product can't be purchased, should still be able to see them but just can't add to cart - * Paystation Hosted Payment added (now in "payment" module) - * Fixed boundary condition in SimpleShippingModifier - * jQuery code to replace existing prototype in ecommerce - * Fixed requirement of $_SERVER[REMOTE_ADDR] for Payment class - * Product version is now retained when product added to cart (so price changes don't affect orders) - * Fixed bug with TaxModifier::AddedCharge() - -0.5.1 - - * Use the Session class rather than accessing $_SESSION directly - * Template changes for 2.1.0 - * Use themes - -0.5 - - * Initial release diff --git a/README.md b/README.md index 23c6a6e4c..d0af34179 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,11 @@ The SilverShop module aims to provide developers with a framework for building, and customising ecommerce-based projects. It includes facilities for customers to browse products and place orders, and for administrators to manage products and orders. -We've put a strong focus on testing, and thanks to TravisCI, you can see the [build status](https://travis-ci.org/silvershop/silvershop-core) of this project, running on MySQL, SQLite, Postgres, as well as a few different versions of PHP. +We've put a strong focus on testing. You can see the [![build status](https://github.com/silvershop/silvershop-core/actions/workflows/ci.yml/badge.svg)](https://github.com/silvershop/silvershop-core/actions/workflows/ci.yml) of this project, running on MySQL, SQLite, Postgres, as well as a few different versions of PHP. [![Latest Stable Version](https://poser.pugx.org/silvershop/core/v/stable.png)](https://packagist.org/packages/silvershop/core) [![Latest Unstable Version](https://poser.pugx.org/silvershop/core/v/unstable.png)](https://packagist.org/packages/silvershop/core) -[![Build Status](https://travis-ci.org/silvershop/silvershop-core.svg?branch=master)](http://travis-ci.org/silvershop/silvershop-core) +[![CI](https://github.com/silvershop/silvershop-core/actions/workflows/ci.yml/badge.svg)](https://github.com/silvershop/silvershop-core/actions/workflows/ci.yml) [![Code Coverage](https://scrutinizer-ci.com/g/silvershop/silvershop-core/badges/coverage.png?s=1abe84b468ef3d96646a0546954adba8131d6459)](https://scrutinizer-ci.com/g/silvershop/silvershop-core/) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/silvershop/silvershop-core/badges/quality-score.png?s=d60753d6cca3817e80aca3dbb79eb5bd4140c981)](https://scrutinizer-ci.com/g/silvershop/silvershop-core/) [![Total Downloads](https://poser.pugx.org/silvershop/core/downloads.png)](https://packagist.org/packages/silvershop/core) diff --git a/client/dist/javascript/CheckoutPage.nojquery.js b/client/dist/javascript/CheckoutPage.nojquery.js new file mode 100644 index 000000000..6e540c5c2 --- /dev/null +++ b/client/dist/javascript/CheckoutPage.nojquery.js @@ -0,0 +1,41 @@ +/** + * Addressbook checkout component + * This handles a dropdown or radio buttons containing existing addresses or payment methods, + * with one of the options being "create a new ____". When that last option is selected, the + * other fields need to be shown, otherwise they need to be hidden. + */ +function onExistingValueChange() { + let existingValues = document.querySelectorAll('.hasExistingValues'); + if(!existingValues) return; + + existingValues.forEach(function (container, idx) { + let toggle = document.querySelector('.existingValues select, .existingValues input:checked'); + + // visible if the value is not an ID (numeric) + let toggleState = Number.isNaN(parseInt(toggle.value)); + let toggleFields = container.querySelectorAll(".field:not(.existingValues)"); + + // animate the fields - hide or show + if (toggleFields && toggleFields.length > 0) { + toggleFields.forEach(field => { + field.style.display = toggleState ? '' : 'none'; + }) + } + + // clear them out + toggleFields.forEach(field => { + field.querySelectorAll('input, select, textarea').forEach(f => { + f.value = ''; + f.disabled = toggleState ? '' : 'disabled'; + }); + }); + }); +} + +let selectors = document.querySelectorAll('.existingValues select'); +if(selectors) selectors.forEach(selector => selector.addEventListener('change', onExistingValueChange)); + +let inputs = document.querySelectorAll('.existingValues input[type=radio]') +if(inputs) inputs.forEach(input => input.addEventListener('click', onExistingValueChange)); + +onExistingValueChange(); // handle initial state diff --git a/composer.json b/composer.json index b57b846a2..6913c1dae 100644 --- a/composer.json +++ b/composer.json @@ -21,18 +21,18 @@ } ], "require": { - "silverstripe/cms": "^4", - "silverstripe/asset-admin": "*", - "silverstripe/silverstripe-omnipay": "^3@dev", - "silvershop/silverstripe-listsorter": "^3@dev", - "silvershop/silverstripe-sqlquerylist": "^2@dev", - "symbiote/silverstripe-gridfieldextensions": "^3.2" + "silverstripe/cms": "^5", + "silverstripe/silverstripe-omnipay": "^3@dev | dev-main#8f277fa5ef513ded38e55ed3c56778feada26174", + "silvershop/silverstripe-listsorter": "^3", + "silvershop/silverstripe-sqlquerylist": "^3", + "symbiote/silverstripe-gridfieldextensions": "^4" }, "require-dev": { - "phpunit/phpunit": "^5.7", - "guzzle/plugin-mock": "^3.1", - "omnipay/dummy": "^2.1", - "omnipay/paymentexpress": "^2.1" + "phpunit/phpunit": "^9.5", + "php-http/guzzle7-adapter": "^1", + "omnipay/dummy": "dev-master", + "omnipay/paymentexpress": "dev-master", + "squizlabs/php_codesniffer": "^3.7.2" }, "replace": { "burnbright/silverstripe-shop": "1.*" @@ -46,16 +46,12 @@ "suggest": { "bummzack/silverstripe-omnipay-ui": "Adds UI Components to manage payments in the SilverStripe CMS.", "silvershop/discounts": "Create coupons and generic discounts to be applied at checkout.", - "silvershop/shipping": "Provide various shipping methods.", - "silvershop/coloredvariations": "Select colours for variations", - "burnbright/silverstripe-shop-geocoding": "Geocoding support for addresses and visitors.", - "burnbright/silverstripe-shop-googleanalytics": "Records shop sales sales in google analytics.", - "markguinn/silverstripe-shop-ajax": "Basic ajax behaviours for add to cart, etc" + "silvershop/shipping": "Provide various shipping methods." }, "extra": { "snapshot": "https://raw.github.com/silvershop/silvershop-core/gh-pages/assets/screenshots/shipping%20estimate%20form.png", "branch-alias": { - "dev-master": "3.x-dev" + "dev-main": "4.x-dev" }, "expose": [ "client/dist" diff --git a/docs/en/02_Customisation/Contributing.md b/docs/en/02_Customisation/Contributing.md index 4360238c3..c28927a7a 100644 --- a/docs/en/02_Customisation/Contributing.md +++ b/docs/en/02_Customisation/Contributing.md @@ -5,7 +5,7 @@ This module only moves forward as we each build the features we need. We love pu ### Here is a quick list of ways you can contribute: * __Test the latest code__. Find out what branch is currently being worked on (usually 'master'). Install it and try it out. - * __Code new features and bug fixes__. Submit github pull requests. Don't forget to write PHPUnit tests that ensure your code runs. All pull requests are automatically tested [via TravisCI](https://travis-ci.org/burnbright/silverstripe-shop/pull_requests). + * __Code new features and bug fixes__. Submit github pull requests. Don't forget to write PHPUnit tests that ensure your code runs. * __Submit issues and ideas__. These can be bugs, or ideas. Be descriptive and detailed. Its better to discuss and design ideas before writing code. Please first check the [list of existing issues](https://github.com/burnbright/silverstripe-shop/issues) to make sure an identical one doesn't exist already. * __Write documentation__. Both the developer and user documentation can have pieces missing. Documentation is stored in the repository under `/shop/docs`, and `/shop/docs_user`. Documentation gets displayed at http://docs.ss-shop.org * __Provide translations__. This will allow people speaking other languages to use the shop module: https://www.transifex.com/silvershop/silverstripe-shop/ diff --git a/docs/en/02_Customisation/Testing.md b/docs/en/02_Customisation/Testing.md index 56b16a24a..4adb2259d 100644 --- a/docs/en/02_Customisation/Testing.md +++ b/docs/en/02_Customisation/Testing.md @@ -4,15 +4,13 @@ Testing is highly important for maintaining a quality product. We insist that the shop module contains a suite of unit tests that are updated with any changes to the code. Sub-Modules should also have their own test suites. See the [framework testing documentation](http://docs.silverstripe.org/en/developer_guides/testing/) for setup information etc. -See also: [https://phpunit.de/manual/3.7/en/](https://phpunit.de/manual/3.7/en/) +See also: [https://docs.phpunit.de/en/9.6/](https://docs.phpunit.de/en/9.6/) To run all shop tests visit `yoursite/dev/tests/module/shop`. If you intend on doing lots of development, it might be a good idea to run tests from the command line. **Note:** Be aware that your website's configuration may affect your test results. The tests should set configuration correctly, but sometimes configuration options get missed. -Every change to this module is [tested using the Travis Continuous Integration service](https://travis-ci.org/burnbright/silverstripe-shop). - -Current status: [![Build Status](https://travis-ci.org/silvershop/silvershop-core.svg?branch=master)](http://travis-ci.org/silvershop/silvershop-core) +Every change to this module is [![tested using a Continuous Integration service](https://github.com/silvershop/silvershop-core/actions/workflows/ci.yml/badge.svg)](https://github.com/silvershop/silvershop-core/actions/workflows/ci.yml). ### Writing Tests @@ -23,4 +21,4 @@ The products created by the shop.yml file are all in draft form (unpublished). Y As features/sites are being developed, they should be tested. In a nutshell, be sure to test the following main functionality: * Adding/removing items from cart - * Placing an order. Follow the process end-to-end. \ No newline at end of file + * Placing an order. Follow the process end-to-end. diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 6aa4983a5..685a2a218 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -2,6 +2,9 @@ CodeSniffer ruleset for SilverStripe coding conventions. + src + tests + @@ -18,17 +21,23 @@ - + + + + /thirdparty/* + + - */Fixtures/* + */SSTemplateParser.php$ + */_fakewebroot/* + */fixtures/* - diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 149c0c41f..f1ac20968 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,14 +1,16 @@ - + + + + + src/ + + + tests/php/ + + + - tests/php + tests/php - - - - src/ - - tests/php/ - - - + diff --git a/src/Admin/OrdersAdmin.php b/src/Admin/OrdersAdmin.php index 3ec253f4b..4f7e4de6c 100644 --- a/src/Admin/OrdersAdmin.php +++ b/src/Admin/OrdersAdmin.php @@ -31,7 +31,7 @@ class OrdersAdmin extends ModelAdmin OrderStatusLog::class ]; - private static $model_importers = array(); + private static $model_importers = []; /** * Restrict list to non-hidden statuses @@ -42,7 +42,7 @@ public function getList() if ($this->modelClass == Order::class) { // Exclude hidden statuses - $list = $list->exclude('Status', Order::config()->hidden_status); + $list = $list->exclude('Status', Order::config()->hidden_status); $this->extend('updateList', $list); } diff --git a/src/Admin/ProductBulkLoader.php b/src/Admin/ProductBulkLoader.php index 1f7fd06e1..024913de3 100644 --- a/src/Admin/ProductBulkLoader.php +++ b/src/Admin/ProductBulkLoader.php @@ -145,7 +145,7 @@ public function processRecord($record, $columnMap, &$results, $preview = false) } // set image, based on filename - public function imageByFilename(&$obj, $val, $record) + public function imageByFilename(&$obj, $val) { $filename = trim(strtolower(Convert::raw2sql($val))); $filenamedashes = str_replace(' ', '-', $filename); @@ -165,7 +165,7 @@ public function imageByFilename(&$obj, $val, $record) } // find product group parent (ie Cateogry) - public function setParent(&$obj, $val, $record) + public function setParent(&$obj, $val) { $title = strtolower(Convert::raw2sql($val)); if ($title) { @@ -281,7 +281,7 @@ public function variationRow(&$obj, $val, $record) $variation->ProductID = $obj->ID; //link to product $variation->write(); } - $varcols = array( + $varcols = [ '->processVariation', '->processVariation1', '->processVariation2', @@ -289,7 +289,7 @@ public function variationRow(&$obj, $val, $record) '->processVariation4', '->processVariation5', '->processVariation6', - ); + ]; foreach ($varcols as $col) { if (isset($record[$col])) { $parts = explode(':', $record[$col]); diff --git a/src/Cart/OrderTotalCalculator.php b/src/Cart/OrderTotalCalculator.php index 60ae1f198..633c1b093 100644 --- a/src/Cart/OrderTotalCalculator.php +++ b/src/Cart/OrderTotalCalculator.php @@ -35,7 +35,7 @@ class OrderTotalCalculator */ protected $order; - function __construct(Order $order) + public function __construct(Order $order) { $this->order = $order; } @@ -45,19 +45,19 @@ function __construct(Order $order) * @throws Exception * @throws \Psr\Container\NotFoundExceptionInterface */ - function calculate() + public function calculate() { $runningtotal = $this->order->SubTotal(); $sort = 1; $existingmodifiers = $this->order->Modifiers(); - + $modifierclasses = Order::config()->modifiers; //check if modifiers are even in use if (!is_array($modifierclasses) || empty($modifierclasses)) { return $runningtotal; } - + $modifierclasses = array_unique($modifierclasses); if (DB::get_conn()->supportsTransactions()) { diff --git a/src/Cart/ShoppingCart.php b/src/Cart/ShoppingCart.php index cc6d92ffc..35f4333b8 100644 --- a/src/Cart/ShoppingCart.php +++ b/src/Cart/ShoppingCart.php @@ -368,7 +368,7 @@ private function findOrMakeItem(Buyable $buyable, $quantity = 1, $filter = []) * * @return OrderItem the item requested or null */ - public function get(Buyable $buyable, $customfilter = array()) + public function get(Buyable $buyable, $customfilter = []) { $order = $this->current(); if (!$buyable || !$order) { @@ -377,9 +377,9 @@ public function get(Buyable $buyable, $customfilter = array()) $buyable = $this->getCorrectBuyable($buyable); - $filter = array( + $filter = [ 'OrderID' => $order->ID, - ); + ]; $itemclass = Config::inst()->get(get_class($buyable), 'order_item'); $relationship = Config::inst()->get($itemclass, 'buyable_relationship'); diff --git a/src/Cart/ShoppingCartController.php b/src/Cart/ShoppingCartController.php index 1a40155c3..cd5f2f143 100644 --- a/src/Cart/ShoppingCartController.php +++ b/src/Cart/ShoppingCartController.php @@ -69,22 +69,22 @@ class ShoppingCartController extends Controller 'debug', ]; - public static function add_item_link(Buyable $buyable, $parameters = array()) + public static function add_item_link(Buyable $buyable, $parameters = []) { return self::build_url('add', $buyable, $parameters); } - public static function remove_item_link(Buyable $buyable, $parameters = array()) + public static function remove_item_link(Buyable $buyable, $parameters = []) { return self::build_url('remove', $buyable, $parameters); } - public static function remove_all_item_link(Buyable $buyable, $parameters = array()) + public static function remove_all_item_link(Buyable $buyable, $parameters = []) { return self::build_url('removeall', $buyable, $parameters); } - public static function set_quantity_item_link(Buyable $buyable, $parameters = array()) + public static function set_quantity_item_link(Buyable $buyable, $parameters = []) { return self::build_url('setquantity', $buyable, $parameters); } @@ -191,7 +191,7 @@ protected function buyableFromRequest() * * @param HTTPRequest $request * - * @return HTTPResponse + * @return string|HTTPResponse * @throws \SilverStripe\Control\HTTPResponse_Exception */ public function add($request) @@ -216,7 +216,7 @@ public function add($request) * * @param HTTPRequest $request * - * @return HTTPResponse + * @return string|HTTPResponse * @throws \SilverStripe\Control\HTTPResponse_Exception */ public function remove($request) @@ -235,7 +235,7 @@ public function remove($request) * * @param HTTPRequest $request * - * @return HTTPResponse + * @return string|HTTPResponse * @throws \SilverStripe\Control\HTTPResponse_Exception */ public function removeall($request) @@ -254,7 +254,7 @@ public function removeall($request) * * @param HTTPRequest $request * - * @return HTTPResponse + * @return string|HTTPResponse * @throws \SilverStripe\Control\HTTPResponse_Exception */ public function setquantity($request) @@ -275,7 +275,7 @@ public function setquantity($request) * * @param HTTPRequest $request * - * @return HTTPResponse + * @return string|HTTPResponse */ public function clear($request) { diff --git a/src/Checkout/CheckoutComponentConfig.php b/src/Checkout/CheckoutComponentConfig.php index e91b0f51b..bd8e56ccf 100644 --- a/src/Checkout/CheckoutComponentConfig.php +++ b/src/Checkout/CheckoutComponentConfig.php @@ -80,7 +80,7 @@ public function getComponents() /** * Returns the first available component with the given class or interface. * - * @param String ClassName + * @param string $type ClassName * * @return CheckoutComponent */ @@ -135,7 +135,7 @@ public function getFormFields() public function getRequiredFields() { - $required = array(); + $required = []; foreach ($this->getComponents() as $component) { $required = array_merge($required, $component->getRequiredFields($this->order)); } @@ -186,7 +186,7 @@ public function validateData($data) */ public function getData() { - $data = array(); + $data = []; foreach ($this->getComponents() as $component) { $orderdata = $component->getData($this->order); @@ -220,7 +220,7 @@ protected function dependantData($component, $data) if (!$this->namespaced) { //no need to try and get un-namespaced dependant data return $data; } - $dependantdata = array(); + $dependantdata = []; foreach ($component->dependsOn() as $dependanttype) { $dependant = null; foreach ($this->components as $check) { diff --git a/src/Checkout/CheckoutFieldFactory.php b/src/Checkout/CheckoutFieldFactory.php index 30d8479f0..fc970f95d 100644 --- a/src/Checkout/CheckoutFieldFactory.php +++ b/src/Checkout/CheckoutFieldFactory.php @@ -40,7 +40,7 @@ private function __construct() { } - public function getContactFields($subset = array()) + public function getContactFields($subset = []) { return $this->getSubset( FieldList::create( @@ -52,7 +52,7 @@ public function getContactFields($subset = array()) ); } - public function getAddressFields($type = "shipping", $subset = array()) + public function getAddressFields($type = "shipping", $subset = []) { $address = singleton(Address::class); $fields = $address->getFormFields($type); @@ -82,7 +82,7 @@ public function getPasswordFields() 'SilverShop\Checkout\CheckoutField.MemberLoginInfo', 'If you are already a member please log in', '', - array('LoginUrl' => $loginlink) + ['LoginUrl' => $loginlink] ) . '

' ), @@ -138,7 +138,7 @@ public function getTermsConditionsField() 'SilverShop\Checkout\Checkout.TermsAndConditionsLink', 'I agree to the terms and conditions stated on the {TermsPageTitle} page', '', - array('TermsPageLink' => $termsPage->Link(), 'TermsPageTitle' => $termsPage->Title) + ['TermsPageLink' => $termsPage->Link(), 'TermsPageTitle' => $termsPage->Title] ) ); } @@ -155,7 +155,7 @@ public function getTermsConditionsField() * * @return FieldList subset of form fields */ - private function getSubset(FieldList $fields, $subset = array()) + private function getSubset(FieldList $fields, $subset = []) { if (empty($subset)) { return $fields; diff --git a/src/Checkout/Component/Address.php b/src/Checkout/Component/Address.php index 5b9bb643b..6aef73705 100644 --- a/src/Checkout/Component/Address.php +++ b/src/Checkout/Component/Address.php @@ -65,7 +65,7 @@ public function getData(Order $order) if (!$order->{$this->addresstype . 'AddressID'}) { $data = array_merge( ShopUserInfo::singleton()->getLocation(), - $member ? $member->{'Default' . $this->addresstype . 'Address'}()->toMap() : array(), + $member ? $member->{'Default' . $this->addresstype . 'Address'}()->toMap() : [], [$this->addresstype . 'AddressID' => $order->{$this->addresstype . 'AddressID'}] ); } diff --git a/src/Checkout/Component/AddressBook.php b/src/Checkout/Component/AddressBook.php index de6340332..90b76b5ab 100644 --- a/src/Checkout/Component/AddressBook.php +++ b/src/Checkout/Component/AddressBook.php @@ -19,6 +19,7 @@ */ abstract class AddressBook extends Address implements i18nEntityProvider { + private static $jquery_file = 'https://code.jquery.com/jquery-3.7.0.min.js'; /** * The composite field tag to use * @@ -34,9 +35,13 @@ public function getFormFields(Order $order) $fields = parent::getFormFields($order); if ($existingaddressfields = $this->getExistingAddressFields()) { - Requirements::javascript('silverstripe/admin:thirdparty/jquery/jquery.js'); - Requirements::javascript('silvershop/core:client/dist/javascript/CheckoutPage.js'); - + if ($jquery = $this->config()->get('jquery_file')) { + Requirements::javascript($jquery); + Requirements::javascript('silvershop/core:client/dist/javascript/CheckoutPage.js'); + } else { + Requirements::javascript('silvershop/core:client/dist/javascript/CheckoutPage.nojquery.js'); + } + // add the fields for a new address after the dropdown field $existingaddressfields->merge($fields); // group under a composite field (invisible by default) so we @@ -128,7 +133,7 @@ public function validateData(Order $order, array $data) $errorMessage = _t( 'SilverShop\Forms.FIELDISREQUIRED', '{name} is required', - array('name' => $fieldLabel) + ['name' => $fieldLabel] ); $result->addError($errorMessage, $fieldName); @@ -180,6 +185,6 @@ public function provideI18nEntities() ]; } - return array(); + return []; } } diff --git a/src/Checkout/Component/CheckoutComponent.php b/src/Checkout/Component/CheckoutComponent.php index 860c334ed..7d3ecfc82 100644 --- a/src/Checkout/Component/CheckoutComponent.php +++ b/src/Checkout/Component/CheckoutComponent.php @@ -4,6 +4,7 @@ use SilverShop\Model\Order; use SilverShop\ShopTools; +use SilverStripe\Core\Config\Configurable; use SilverStripe\Core\Injector\Injectable; use SilverStripe\Forms\FieldList; use SilverStripe\ORM\ValidationException; @@ -22,6 +23,7 @@ abstract class CheckoutComponent { use Injectable; + use Configurable; protected $requiredfields = []; diff --git a/src/Checkout/Component/CheckoutComponentNamespaced.php b/src/Checkout/Component/CheckoutComponentNamespaced.php index 5efdae36e..6d18de3fe 100644 --- a/src/Checkout/Component/CheckoutComponentNamespaced.php +++ b/src/Checkout/Component/CheckoutComponentNamespaced.php @@ -58,7 +58,7 @@ public function setData(Order $order, array $data) public function getRequiredFields(Order $order) { $fields = $this->proxy->getRequiredFields($order); - $namespaced = array(); + $namespaced = []; foreach ($fields as $field) { $namespaced[] = $this->namespaceFieldName($field); } @@ -84,7 +84,7 @@ public function providesPaymentData() public function namespaceData(array $data) { - $newdata = array(); + $newdata = []; foreach ($data as $key => $value) { $newdata[$this->namespaceFieldName($key)] = $value; } @@ -93,7 +93,7 @@ public function namespaceData(array $data) public function unnamespaceData(array $data) { - $newdata = array(); + $newdata = []; foreach ($data as $key => $value) { if (strpos($key, $this->name()) === 0) { $newdata[$this->unnamespaceFieldName($key)] = $value; diff --git a/src/Checkout/Component/CustomerDetails.php b/src/Checkout/Component/CustomerDetails.php index f3d67c372..168bc46b8 100644 --- a/src/Checkout/Component/CustomerDetails.php +++ b/src/Checkout/Component/CustomerDetails.php @@ -48,7 +48,7 @@ public function getData(Order $order) 'Email' => $member->Email, ]; } - return array(); + return []; } public function setData(Order $order, array $data) diff --git a/src/Checkout/Component/Membership.php b/src/Checkout/Component/Membership.php index 16045fc81..83ffb9e20 100644 --- a/src/Checkout/Component/Membership.php +++ b/src/Checkout/Component/Membership.php @@ -70,12 +70,12 @@ public function getFormFields(Order $order, Form $form = null) public function getRequiredFields(Order $order) { if (Security::getCurrentUser() || !Checkout::membership_required()) { - return array(); + return []; } - return array( + return [ Member::config()->unique_identifier_field, 'Password', - ); + ]; } public function getPasswordField() @@ -108,7 +108,7 @@ public function validateData(Order $order, array $data) 'SilverShop\Checkout\Checkout.MemberExists', 'A member already exists with the {Field} {Identifier}', '', - array('Field' => $fieldLabel, 'Identifier' => $idval) + ['Field' => $fieldLabel, 'Identifier' => $idval] ), $idfield ); @@ -127,7 +127,7 @@ public function validateData(Order $order, array $data) public function getData(Order $order) { - $data = array(); + $data = []; if ($member = Security::getCurrentUser()) { $idf = Member::config()->unique_identifier_field; diff --git a/src/Checkout/Component/OnsitePayment.php b/src/Checkout/Component/OnsitePayment.php index 78f82c714..c57f9b6e4 100644 --- a/src/Checkout/Component/OnsitePayment.php +++ b/src/Checkout/Component/OnsitePayment.php @@ -53,7 +53,7 @@ public function validateData(Order $order, array $data) public function getData(Order $order) { - $data = array(); + $data = []; $gateway = Checkout::get($order)->getSelectedPaymentMethod(); //provide valid dummy credit card data if ($gateway === 'Dummy') { diff --git a/src/Checkout/Component/Payment.php b/src/Checkout/Component/Payment.php index 8f427fa1c..cda3d1d39 100644 --- a/src/Checkout/Component/Payment.php +++ b/src/Checkout/Component/Payment.php @@ -42,7 +42,7 @@ public function getRequiredFields(Order $order) return []; } - return array('PaymentMethod'); + return ['PaymentMethod']; } public function validateData(Order $order, array $data) @@ -64,9 +64,9 @@ public function validateData(Order $order, array $data) public function getData(Order $order) { - return array( + return [ 'PaymentMethod' => Checkout::get($order)->getSelectedPaymentMethod(), - ); + ]; } public function setData(Order $order, array $data) diff --git a/src/Checkout/OrderEmailNotifier.php b/src/Checkout/OrderEmailNotifier.php index 34ef1dbd6..cb019617d 100644 --- a/src/Checkout/OrderEmailNotifier.php +++ b/src/Checkout/OrderEmailNotifier.php @@ -120,7 +120,7 @@ public function sendConfirmation() 'SilverShop\ShopEmail.ConfirmationSubject', 'Order #{OrderNo} confirmation', '', - array('OrderNo' => $this->order->Reference) + ['OrderNo' => $this->order->Reference] ); return $this->sendEmail( 'SilverShop/Model/Order_ConfirmationEmail', @@ -140,7 +140,7 @@ public function sendAdminNotification() 'SilverShop\ShopEmail.AdminNotificationSubject', 'Order #{OrderNo} notification', '', - array('OrderNo' => $this->order->Reference) + ['OrderNo' => $this->order->Reference] ); $email = $this->buildEmail('SilverShop/Model/Order_AdminNotificationEmail', $subject) @@ -163,7 +163,7 @@ public function sendReceipt() 'SilverShop\ShopEmail.ReceiptSubject', 'Order #{OrderNo} receipt', '', - array('OrderNo' => $this->order->Reference) + ['OrderNo' => $this->order->Reference] ); return $this->sendEmail( diff --git a/src/Checkout/OrderProcessor.php b/src/Checkout/OrderProcessor.php index 6f330830c..2b177493f 100644 --- a/src/Checkout/OrderProcessor.php +++ b/src/Checkout/OrderProcessor.php @@ -85,7 +85,7 @@ public function getReturnUrl() * @return ServiceResponse|null * @throws \SilverStripe\Omnipay\Exception\InvalidConfigurationException */ - public function makePayment($gateway, $gatewaydata = array(), $successUrl = null, $cancelUrl = null) + public function makePayment($gateway, $gatewaydata = [], $successUrl = null, $cancelUrl = null) { //create payment $payment = $this->createPayment($gateway); @@ -147,19 +147,19 @@ protected function getGatewayData($customData) $billing = $this->order->getBillingAddress(); $numPayments = Payment::get() - ->filter(array('OrderID' => $this->order->ID)) + ->filter(['OrderID' => $this->order->ID]) ->count() - 1; $transactionId = $this->order->Reference . ($numPayments > 0 ? "-$numPayments" : ''); return array_merge( $customData, - array( + [ 'transactionId' => $transactionId, 'firstName' => $this->order->FirstName, 'lastName' => $this->order->Surname, 'email' => $this->order->Email, - 'company' => $this->order->Company, + 'company' => $billing->Company, 'billingAddress1' => $billing->Address, 'billingAddress2' => $billing->AddressLine2, 'billingCity' => $billing->City, @@ -174,7 +174,7 @@ protected function getGatewayData($customData) 'shippingState' => $shipping->State, 'shippingCountry' => $shipping->Country, 'shippingPhone' => $shipping->Phone, - ) + ] ); } @@ -189,7 +189,7 @@ public function createPayment($gateway) __CLASS__ . ".InvalidGateway", "`{gateway}` isn't a valid payment gateway.", 'gateway is the name of the payment gateway', - array('gateway' => $gateway) + ['gateway' => $gateway] ) ); return false; @@ -216,7 +216,6 @@ public function createPayment($gateway) public function completePayment() { if (!$this->order->IsPaid()) { - $this->order->extend('onPayment'); //a payment has been made //place the order, if not already placed if ($this->canPlace($this->order)) { @@ -232,7 +231,7 @@ public function completePayment() || ($this->order->GrandTotal() == 0 && Order::config()->allow_zero_order_total) ) { //set order as paid - $this->order->Status = 'Paid'; + $this->order->setField('Status', 'Paid'); $this->order->write(); } } @@ -288,13 +287,13 @@ public function placeOrder() //update status if ($this->order->TotalOutstanding(false)) { - $this->order->Status = 'Unpaid'; + $this->order->setField('Status', 'Unpaid'); } else { - $this->order->Status = 'Paid'; + $this->order->setField('Status', 'Paid'); } if (!$this->order->Placed) { - $this->order->Placed = DBDatetime::now()->Rfc2822(); //record placed order datetime + $this->order->setField('Placed', DBDatetime::now()->Rfc2822()); //record placed order datetime if ($request = Controller::curr()->getRequest()) { $this->order->IPAddress = $request->getIP(); //record client IP } diff --git a/src/Checkout/Step/Address.php b/src/Checkout/Step/Address.php index eeef1f7d2..3007993ea 100644 --- a/src/Checkout/Step/Address.php +++ b/src/Checkout/Step/Address.php @@ -13,14 +13,14 @@ class Address extends CheckoutStep { - private static $allowed_actions = array( + private static $allowed_actions = [ 'shippingaddress', 'ShippingAddressForm', 'setshippingaddress', 'billingaddress', 'BillingAddressForm', 'setbillingaddress', - ); + ]; public function shippingconfig() { @@ -85,7 +85,7 @@ public function billingconfig() public function billingaddress() { - return array('OrderForm' => $this->BillingAddressForm()); + return ['OrderForm' => $this->BillingAddressForm()]; } public function BillingAddressForm() diff --git a/src/Checkout/Step/AddressBook.php b/src/Checkout/Step/AddressBook.php index 7ff50ca5a..cdbe8f0a8 100644 --- a/src/Checkout/Step/AddressBook.php +++ b/src/Checkout/Step/AddressBook.php @@ -9,14 +9,14 @@ class AddressBook extends Address { - private static $allowed_actions = array( + private static $allowed_actions = [ 'shippingaddress', 'ShippingAddressForm', 'setshippingaddress', 'billingaddress', 'BillingAddressForm', 'setbillingaddress', - ); + ]; public function shippingconfig() { diff --git a/src/Checkout/Step/PaymentMethod.php b/src/Checkout/Step/PaymentMethod.php index 74a28bfa5..70951383a 100644 --- a/src/Checkout/Step/PaymentMethod.php +++ b/src/Checkout/Step/PaymentMethod.php @@ -32,9 +32,9 @@ public function paymentmethod() if (count($gateways) == 1) { return $this->owner->redirect($this->NextStepLink()); } - return array( + return [ 'OrderForm' => $this->PaymentMethodForm(), - ); + ]; } public function PaymentMethodForm() diff --git a/src/Checkout/Step/Summary.php b/src/Checkout/Step/Summary.php index c1c37632c..ef47a8d0f 100644 --- a/src/Checkout/Step/Summary.php +++ b/src/Checkout/Step/Summary.php @@ -18,9 +18,9 @@ class Summary extends CheckoutStep public function summary() { $form = $this->ConfirmationForm(); - return array( + return [ 'OrderForm' => $form, - ); + ]; } public function ConfirmationForm() diff --git a/src/Extension/LocationFormPageExtension.php b/src/Extension/LocationFormPageExtension.php index f5f0c2c71..2e6ae14ac 100644 --- a/src/Extension/LocationFormPageExtension.php +++ b/src/Extension/LocationFormPageExtension.php @@ -7,9 +7,9 @@ class LocationFormPageExtension extends Extension { - private static $allowed_actions = array( + private static $allowed_actions = [ 'SetLocationForm', - ); + ]; public function SetLocationForm() { diff --git a/src/Extension/OrderManipulationExtension.php b/src/Extension/OrderManipulationExtension.php index 360c843bc..05012b6ab 100644 --- a/src/Extension/OrderManipulationExtension.php +++ b/src/Extension/OrderManipulationExtension.php @@ -22,10 +22,10 @@ */ class OrderManipulationExtension extends Extension { - private static $allowed_actions = array( + private static $allowed_actions = [ 'ActionsForm', 'order', - ); + ]; private static $sessname = 'OrderManipulation.historicalorders'; @@ -36,7 +36,7 @@ public static function add_session_order(Order $order) { $history = self::get_session_order_ids(); if (!is_array($history)) { - $history = array(); + $history = []; } $history[$order->ID] = $order->ID; ShopTools::getSession()->set(self::$sessname, $history); @@ -83,9 +83,9 @@ public function orderfromid() */ public function allorders() { - $filters = array( + $filters = [ 'ID' => -1 //ensures no results are returned - ); + ]; if ($sessids = self::get_session_order_ids()) { $filters['ID'] = $sessids; } @@ -129,10 +129,10 @@ public function order(HTTPRequest $request) return $this->owner->httpError(404, 'Order could not be found'); } - return array( + return [ 'Order' => $order, 'Form' => $this->ActionsForm() //see OrderManipulation extension - ); + ]; } /** diff --git a/src/Extension/ProductVariationsExtension.php b/src/Extension/ProductVariationsExtension.php index d52caecc7..3a663b64a 100644 --- a/src/Extension/ProductVariationsExtension.php +++ b/src/Extension/ProductVariationsExtension.php @@ -89,12 +89,12 @@ public function PriceRange() } $prices = $variations->map('ID', 'SellingPrice')->toArray(); - $pricedata = array( + $pricedata = [ 'HasRange' => false, 'Max' => ShopCurrency::create(), 'Min' => ShopCurrency::create(), 'Average' => ShopCurrency::create(), - ); + ]; $count = count($prices); $sum = array_sum($prices); $maxprice = max($prices); diff --git a/src/Extension/SteppedCheckoutExtension.php b/src/Extension/SteppedCheckoutExtension.php index 11e356aa0..8bd99d4c6 100644 --- a/src/Extension/SteppedCheckoutExtension.php +++ b/src/Extension/SteppedCheckoutExtension.php @@ -125,7 +125,7 @@ public function index() if (CheckoutPage::config()->first_step) { return $this->owner->{CheckoutPage::config()->first_step}(); } - return array(); + return []; } /** diff --git a/src/Forms/AddProductForm.php b/src/Forms/AddProductForm.php index bb81fbbcc..e050615c7 100644 --- a/src/Forms/AddProductForm.php +++ b/src/Forms/AddProductForm.php @@ -37,7 +37,7 @@ class AddProductForm extends Form * * @var array */ - protected $saveablefields = array(); + protected $saveablefields = []; public function __construct($controller, $name = "AddProductForm") { @@ -115,7 +115,7 @@ protected function getFormFields($controller = null) $fields = FieldList::create(); if ($this->maxquantity) { - $values = array(); + $values = []; $count = 1; while ($count <= $this->maxquantity) { diff --git a/src/Forms/CartEditField.php b/src/Forms/CartEditField.php index 09126976e..2301445f0 100644 --- a/src/Forms/CartEditField.php +++ b/src/Forms/CartEditField.php @@ -85,12 +85,12 @@ public function setEditableItemsCallback(Closure $callback) * * @param array $properties */ - public function Field($properties = array()) + public function Field($properties = []) { $editables = $this->editableItems(); - $customcartdata = array( + $customcartdata = [ 'Items' => $editables, - ); + ]; // NOTE: this was originally incorrect - passing just $editables and $customcartdata // which broke modules like Display_Logic. $this->extend('onBeforeRender', $this, $editables, $customcartdata); @@ -98,7 +98,7 @@ public function Field($properties = array()) return SSViewer::execute_template( $this->template, $this->cart->customise($customcartdata), - array('Editable' => true) + ['Editable' => true] ); } @@ -145,11 +145,11 @@ protected function editableItems() $remove = CheckboxField::create($name . '[Remove]', _t('SilverShop\Generic.Remove', 'Remove')); $editables->push( $item->customise( - array( + [ 'QuantityField' => $quantity, 'VariationField' => $variationfield, 'RemoveField' => $remove, - ) + ] ) ); } diff --git a/src/Forms/CartForm.php b/src/Forms/CartForm.php index 3a9a4103c..d6392d17d 100644 --- a/src/Forms/CartForm.php +++ b/src/Forms/CartForm.php @@ -97,7 +97,7 @@ public function updatecart($data, $form) __CLASS__ . '.REMOVED_ITEMS', 'Removed {count} items.', 'count is the amount that was removed', - array('count' => $removecount) + ['count' => $removecount] ); } if ($updatecount) { @@ -105,7 +105,7 @@ public function updatecart($data, $form) __CLASS__ . '.UPDATED_ITEMS', 'Updated {count} items.', 'count is the amount that was updated', - array('count' => $updatecount) + ['count' => $updatecount] ); } if (count($messages)) { diff --git a/src/Forms/DropdownShopQuantityField.php b/src/Forms/DropdownShopQuantityField.php index f595a1141..0415de085 100644 --- a/src/Forms/DropdownShopQuantityField.php +++ b/src/Forms/DropdownShopQuantityField.php @@ -23,7 +23,7 @@ class DropdownShopQuantityField extends ShopQuantityField public function Field() { - $qtyArray = array(); + $qtyArray = []; for ($r = 1; $r <= $this->config()->max; $r++) { $qtyArray[$r] = $r; } diff --git a/src/Forms/OrderActionsForm.php b/src/Forms/OrderActionsForm.php index 5e5434fed..fce67860d 100644 --- a/src/Forms/OrderActionsForm.php +++ b/src/Forms/OrderActionsForm.php @@ -198,7 +198,7 @@ public function docancel($data, $form) if (self::config()->allow_cancelling && $this->order->canCancel() ) { - $this->order->Status = 'MemberCancelled'; + $this->order->setField('Status', 'MemberCancelled'); $this->order->write(); if (self::config()->email_notification) { @@ -225,9 +225,9 @@ public function docancel($data, $form) */ protected function getCCFields(array $gateways) { - $fieldFactory = new GatewayFieldsFactory(null, array('Card')); - $onsiteGateways = array(); - $allRequired = array(); + $fieldFactory = new GatewayFieldsFactory(null, ['Card']); + $onsiteGateways = []; + $allRequired = []; foreach ($gateways as $gateway => $title) { if (!GatewayInfo::isOffsite($gateway)) { $required = GatewayInfo::requiredFields($gateway); diff --git a/src/Forms/VariationForm.php b/src/Forms/VariationForm.php index 7d9d10890..c3079aae7 100644 --- a/src/Forms/VariationForm.php +++ b/src/Forms/VariationForm.php @@ -55,7 +55,6 @@ public function addtocart($data, $form) // if we are in just doing a validation step then check if ($this->getRequest()->requestVar('ValidateVariant')) { $message = ''; - $success = false; try { $success = $variation->canPurchase(null, $data['Quantity']); @@ -156,7 +155,7 @@ protected function getFormFields($controller = null) foreach ($query->execute()->column('ID') as $variationID) { $query2->setSelect('SilverShop_AttributeValueID') ->setFrom('SilverShop_Variation_AttributeValues') - ->setWhere(array('SilverShop_VariationID' => $variationID)); + ->setWhere(['SilverShop_VariationID' => $variationID]); $vararray[$variationID] = $query2->execute()->keyedColumn(); } diff --git a/src/Model/Address.php b/src/Model/Address.php index 70275ba6f..976ffbdce 100644 --- a/src/Model/Address.php +++ b/src/Model/Address.php @@ -218,7 +218,7 @@ public function getName() */ public function toString($separator = ', ') { - $fields = array( + $fields = [ $this->Company, $this->getName(), $this->Address, @@ -227,7 +227,7 @@ public function toString($separator = ', ') $this->State, $this->PostalCode, $this->Country - ); + ]; $this->extend('updateToString', $fields); return implode($separator, array_filter($fields)); } diff --git a/src/Model/Modifiers/Shipping/Simple.php b/src/Model/Modifiers/Shipping/Simple.php index 64a1a4d79..cda9a7eaf 100644 --- a/src/Model/Modifiers/Shipping/Simple.php +++ b/src/Model/Modifiers/Shipping/Simple.php @@ -22,7 +22,7 @@ class Simple extends Base * @config * @var array */ - private static $charges_by_country = array(); + private static $charges_by_country = []; public function value($subtotal = null) { diff --git a/src/Model/Order.php b/src/Model/Order.php index adda79991..e157da4b6 100644 --- a/src/Model/Order.php +++ b/src/Model/Order.php @@ -294,7 +294,7 @@ class Order extends DataObject public static function get_order_status_options() { - $values = array(); + $values = []; foreach (singleton(Order::class)->dbObject('Status')->enumValues(false) as $value) { $values[$value] = _t(__CLASS__ . '.STATUS_' . strtoupper($value), $value); } @@ -309,12 +309,12 @@ public function getCMSFields() $fields = FieldList::create(TabSet::create('Root', Tab::create('Main'))); $fs = '
'; $fe = '
'; - $parts = array( + $parts = [ 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); } @@ -626,7 +626,7 @@ public function canEdit($member = null) * * @return boolean */ - public function canCreate($member = null, $context = array()) + public function canCreate($member = null, $context = []) { $extended = $this->extendedCan(__FUNCTION__, $member, $context); if ($extended !== null) { @@ -668,7 +668,7 @@ 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))); + return implode(' ', array_filter([$firstname, $surname])); } public function getTitle() @@ -838,7 +838,7 @@ protected function statusTransition($fromStatus, $toStatus) $this->extend('onStatusChange', $fromStatus, $toStatus); if ($toStatus == 'Paid' && !$this->Paid) { - $this->Paid = DBDatetime::now()->Rfc2822(); + $this->setField('Paid', DBDatetime::now()->Rfc2822()); foreach ($this->Items() as $item) { $item->onPayment(); } @@ -847,7 +847,7 @@ protected function statusTransition($fromStatus, $toStatus) if (!$this->ReceiptSent) { OrderEmailNotifier::create($this)->sendReceipt(); - $this->ReceiptSent = DBDatetime::now()->Rfc2822(); + $this->setField('ReceiptSent', DBDatetime::now()->Rfc2822()); } } @@ -947,10 +947,10 @@ public function provideI18nEntities() // collect all the payment status values foreach ($this->dbObject('Status')->enumValues() as $value) { $key = strtoupper($value); - $entities[__CLASS__ . ".STATUS_$key"] = array( + $entities[__CLASS__ . ".STATUS_$key"] = [ $value, "Translation of the order status '$value'", - ); + ]; } return $entities; diff --git a/src/Model/OrderAttribute.php b/src/Model/OrderAttribute.php index 8e97b5a1f..e9c59fa7a 100644 --- a/src/Model/OrderAttribute.php +++ b/src/Model/OrderAttribute.php @@ -36,7 +36,7 @@ class OrderAttribute extends DataObject private static $table_name = 'SilverShop_OrderAttribute'; - public function canCreate($member = null, $context = array()) + public function canCreate($member = null, $context = []) { return false; } diff --git a/src/Model/OrderItem.php b/src/Model/OrderItem.php index e6015a133..b820223eb 100644 --- a/src/Model/OrderItem.php +++ b/src/Model/OrderItem.php @@ -49,7 +49,7 @@ class OrderItem extends OrderAttribute 'Total' => 'Total Price', ]; - private static $required_fields = array(); + private static $required_fields = []; /** * The ORM relationship to the buyable item @@ -131,7 +131,7 @@ public function Total() */ protected function calculatetotal() { - $total = $this->UnitPrice() * $this->Quantity; + $total = (float)$this->UnitPrice() * (int)$this->Quantity; $this->extend('updateTotal', $total); $this->CalculatedTotal = $total; return $total; @@ -155,7 +155,7 @@ public function uniquedata() $unique[$field] = $this->$field; } } - $this->extend('updateuniquedata',$unique); + $this->extend('updateuniquedata', $unique); return $unique; } diff --git a/src/Model/OrderStatusLog.php b/src/Model/OrderStatusLog.php index f4517897d..f96f5cef7 100644 --- a/src/Model/OrderStatusLog.php +++ b/src/Model/OrderStatusLog.php @@ -168,13 +168,13 @@ protected function updateWithLastInfo() ->first(); if ($latestLog) { - $this->DispatchedBy = $latestLog->DispatchedBy; - $this->DispatchedOn = $latestLog->DispatchedOn; - $this->DispatchTicket = $latestLog->DispatchTicket; - $this->PaymentCode = $latestLog->PaymentCode; - $this->PaymentOK = $latestLog->PaymentOK; - $this->SentToCustomer = $latestLog->SentToCustomer; - $this->VisibleToCustomer = $latestLog->VisibleToCustomer; + $this->setField('DispatchedBy', $latestLog->DispatchedBy); + $this->setField('DispatchedOn', $latestLog->DispatchedOn); + $this->setField('DispatchTicket', $latestLog->DispatchTicket); + $this->setField('PaymentCode', $latestLog->PaymentCode); + $this->setField('PaymentOK', $latestLog->PaymentOK); + $this->setField('SentToCustomer', $latestLog->SentToCustomer); + $this->setField('VisibleToCustomer', $latestLog->VisibleToCustomer); } } } diff --git a/src/Model/Variation/Variation.php b/src/Model/Variation/Variation.php index d06028ee7..6ac081b38 100755 --- a/src/Model/Variation/Variation.php +++ b/src/Model/Variation/Variation.php @@ -248,7 +248,7 @@ public function getTitle() { $values = $this->AttributeValues(); if ($values->exists()) { - $labelvalues = array(); + $labelvalues = []; foreach ($values as $value) { if (self::config()->title_has_label) { $labelvalues[] = $value->Type()->Label . self::config()->title_separator . $value->Value; @@ -266,7 +266,7 @@ public function getTitle() public function getCategoryIDs() { - return $this->Product() ? $this->Product()->getCategoryIDs() : array(); + return $this->Product() ? $this->Product()->getCategoryIDs() : []; } public function getCategories() @@ -302,7 +302,7 @@ public function IsInCart() */ public function Item() { - $filter = array(); + $filter = []; $this->extend('updateItemFilter', $filter); $item = ShoppingCart::singleton()->get($this, $filter); if (!$item) { @@ -323,13 +323,14 @@ public function addLink() * * @param $action string * - * @return string + * @return string|false */ - public function Link($action = null) { + public function Link($action = null) + { return ($this->ProductID) ? $this->Product()->Link($action) : false; } - public function createItem($quantity = 1, $filter = array()) + public function createItem($quantity = 1, $filter = []) { $orderitem = self::config()->order_item; $item = new $orderitem(); diff --git a/src/ORM/FieldType/I18nDatetime.php b/src/ORM/FieldType/I18nDatetime.php index 6c2dd6763..2b40bd71c 100644 --- a/src/ORM/FieldType/I18nDatetime.php +++ b/src/ORM/FieldType/I18nDatetime.php @@ -18,7 +18,7 @@ class I18nDatetime extends DBDatetime public function Nice() { if ($this->value) { - return strftime(_t('SilverShop\Generic.DateTimeFormatNice', '%m/%d/%G %I:%M%p'), $this->getTimestamp()); + return date_format(date_create($this->getTimestamp()), _t('SilverShop\Generic.DateTimeFormatNice', '%m/%d/%G %I:%M%p')); } } @@ -31,7 +31,7 @@ public function Nice() public function NiceDate() { if ($this->value) { - return strftime(_t('SilverShop\Generic.DateFormatNice', '%m/%d/%G'), $this->getTimestamp()); + return date_format(date_create($this->getTimestamp()), _t('SilverShop\Generic.DateFormatNice', '%m/%d/%G')); } } diff --git a/src/ORM/Filters/MultiFieldPartialMatchFilter.php b/src/ORM/Filters/MultiFieldPartialMatchFilter.php index 1ad8ccc9c..1d3270c0c 100644 --- a/src/ORM/Filters/MultiFieldPartialMatchFilter.php +++ b/src/ORM/Filters/MultiFieldPartialMatchFilter.php @@ -51,7 +51,7 @@ public function setModifiers(array $modifiers) { $modifiers = array_map('strtolower', $modifiers); - if (($extras = array_diff($modifiers, ['not', 'nocase', 'case', 'splitwords'])) != array()) { + if (($extras = array_diff($modifiers, ['not', 'nocase', 'case', 'splitwords'])) != []) { throw new InvalidArgumentException( get_class($this) . ' does not accept ' . implode(', ', $extras) . ' as modifiers' ); @@ -77,7 +77,7 @@ function ($v) { */ public function setSubfilters(array $fieldNames) { - $this->subfilters = array(); + $this->subfilters = []; if (count($fieldNames) > 0) { foreach ($fieldNames as $name) { $this->subfilters[] = new PartialMatchFilter($name, $this->value, $this->subfilterModifiers); diff --git a/src/Page/AccountPage.php b/src/Page/AccountPage.php index 6021d23b4..ea6b8819e 100644 --- a/src/Page/AccountPage.php +++ b/src/Page/AccountPage.php @@ -18,7 +18,7 @@ class AccountPage extends Page private static $table_name = 'SilverShop_AccountPage'; - public function canCreate($member = null, $context = array()) + public function canCreate($member = null, $context = []) { return !self::get()->exists(); } diff --git a/src/Page/AccountPageController.php b/src/Page/AccountPageController.php index 262d885cf..57f3b5db9 100644 --- a/src/Page/AccountPageController.php +++ b/src/Page/AccountPageController.php @@ -50,7 +50,7 @@ public function init() $this->member = Security::getCurrentUser(); if (!$this->member) { - $messages = array( + $messages = [ 'default' => _t( 'SilverShop\Page\AccountPage.Login', 'You\'ll need to login before you can access the account page. @@ -61,7 +61,7 @@ public function init() 'SilverShop\Page\AccountPage.LoginAgain', 'You have been logged out. If you would like to log in again, please do so below.' ), - ); + ]; Security::permissionFailure($this, $messages); } } @@ -81,10 +81,10 @@ public function getMember() public function addressbook() { - return array( + return [ 'DefaultAddressForm' => $this->DefaultAddressForm(), 'CreateAddressForm' => $this->CreateAddressForm(), - ); + ]; } public function DefaultAddressForm() @@ -171,7 +171,7 @@ public function saveaddress($data, $form) public function editprofile() { - return array(); + return []; } /** diff --git a/src/Page/CheckoutPage.php b/src/Page/CheckoutPage.php index bbf449b7e..22f93452e 100644 --- a/src/Page/CheckoutPage.php +++ b/src/Page/CheckoutPage.php @@ -21,9 +21,9 @@ */ class CheckoutPage extends Page { - private static $db = array( + private static $db = [ 'PurchaseComplete' => 'HTMLText', - ); + ]; private static $icon = 'silvershop/core: client/dist/images/icons/money.gif'; @@ -57,7 +57,7 @@ public function getCMSFields() function (FieldList $fields) { $fields->addFieldsToTab( 'Root.Main', - array( + [ HtmlEditorField::create( 'PurchaseComplete', $this->fieldLabel('PurchaseComplete'), @@ -69,7 +69,7 @@ function (FieldList $fields) { "This message is included in reciept email, after the customer submits the checkout" ) ), - ), + ], 'Metadata' ); } diff --git a/src/Page/CheckoutPageController.php b/src/Page/CheckoutPageController.php index 958e5d5ee..f98d2a09f 100644 --- a/src/Page/CheckoutPageController.php +++ b/src/Page/CheckoutPageController.php @@ -36,11 +36,11 @@ class CheckoutPageController extends PageController { private static $url_segment = 'checkout'; - private static $allowed_actions = array( + private static $allowed_actions = [ 'OrderForm', 'payment', 'PaymentForm', - ); + ]; public function Title() { @@ -90,10 +90,10 @@ public function payment() return $this->redirect($this->Link()); } - return array( + return [ 'Title' => 'Make Payment', 'OrderForm' => $this->PaymentForm(), - ); + ]; } public function PaymentForm() diff --git a/src/Page/Product.php b/src/Page/Product.php index 5085bc761..42b624708 100644 --- a/src/Page/Product.php +++ b/src/Page/Product.php @@ -284,7 +284,7 @@ private function getCategoryOptionsNoParent() */ public function getCategoryIDs() { - $ids = array(); + $ids = []; //ancestors foreach ($this->getAncestors() as $ancestor) { $ids[$ancestor->ID] = $ancestor->ID; @@ -371,7 +371,7 @@ public function IsInCart() */ public function Item() { - $filter = array(); + $filter = []; $this->extend('updateItemFilter', $filter); $item = ShoppingCart::singleton()->get($this, $filter); if (!$item) { @@ -467,7 +467,7 @@ public function Image() /** * Link to add this product to cart. * - * @return string link + * @return string|false link */ public function addLink() { @@ -477,7 +477,7 @@ public function addLink() /** * Link to remove one of this product from cart. * - * @return string link + * @return string|false link */ public function removeLink() { @@ -487,7 +487,7 @@ public function removeLink() /** * Link to remove all of this product from cart. * - * @return string link + * @return string|false link */ public function removeallLink() { diff --git a/src/Page/ProductCategory.php b/src/Page/ProductCategory.php index 860d5ec56..1c2f8e215 100644 --- a/src/Page/ProductCategory.php +++ b/src/Page/ProductCategory.php @@ -51,7 +51,7 @@ class ProductCategory extends Page implements i18nEntityProvider public function ProductsShowable($recursive = true) { // Figure out the categories to check - $groupids = array($this->ID); + $groupids = [$this->ID]; if (!empty($recursive) && self::config()->include_child_groups) { $groupids += $this->AllChildCategoryIDs(); } @@ -105,7 +105,7 @@ public function AllChildCategoryIDs() */ public function ChildCategories($recursive = false) { - $ids = array($this->ID); + $ids = [$this->ID]; if ($recursive) { $ids += $this->AllChildCategoryIDs(); } @@ -150,10 +150,10 @@ public function provideI18nEntities() // add the sort option keys foreach ($this->config()->sort_options as $key => $value) { - $entities[__CLASS__ . '.' . $key] = array( + $entities[__CLASS__ . '.' . $key] = [ $key, "Sort by the '$value' field", - ); + ]; } return $entities; diff --git a/src/Page/ProductCategoryController.php b/src/Page/ProductCategoryController.php index b10858906..9b713c01a 100644 --- a/src/Page/ProductCategoryController.php +++ b/src/Page/ProductCategoryController.php @@ -54,7 +54,7 @@ public function NonFeaturedProducts($recursive = true) */ public function getSorter() { - $options = array(); + $options = []; foreach (ProductCategory::config()->sort_options as $k => $v) { // make the label translatable $k = _t(ProductCategory::class . '.' . $k, $k); diff --git a/src/Reports/AbandonedCartReport.php b/src/Reports/AbandonedCartReport.php index 035b80382..b39361657 100644 --- a/src/Reports/AbandonedCartReport.php +++ b/src/Reports/AbandonedCartReport.php @@ -26,11 +26,11 @@ class AbandonedCartReport extends ShopPeriodReport public function columns() { $period = isset($_GET['filters']['Grouping']) ? $_GET['filters']['Grouping'] : 'Month'; - return array( + return [ 'FilterPeriod' => $period, 'Count' => 'Count', 'TotalValue' => 'Total Value', - ); + ]; } public function query($params) diff --git a/src/Reports/ProductReport.php b/src/Reports/ProductReport.php index a429b3149..70584364d 100644 --- a/src/Reports/ProductReport.php +++ b/src/Reports/ProductReport.php @@ -20,15 +20,15 @@ class ProductReport extends ShopPeriodReport public function columns() { - return array( - 'Title' => array( + return [ + 'Title' => [ 'title' => 'Title', 'formatting' => '$Title', - ), + ], 'BasePrice' => 'Price', 'Quantity' => 'Quantity', 'Sales' => 'Sales', - ); + ]; } @@ -65,7 +65,6 @@ public function query($params) $query->setFrom('"' . $table . '"'); $whereClue = '1'; - $filterperiod = $this->periodfield; if ($start && $end) { $whereClue = sprintf( 'DATE("o"."Placed") BETWEEN DATE(\'%s\') AND DATE(\'%s\')', @@ -117,7 +116,9 @@ public function query($params) )', $completedStatus, $whereClue - ), 'Quantity') + ), + 'Quantity' + ) ->selectField( sprintf( '( @@ -139,7 +140,9 @@ public function query($params) )', $completedStatus, $whereClue - ), 'Sales') + ), + 'Sales' + ) ; $query->addInnerJoin('SiteTree', '"SilverShop_Product"."ID" = "SiteTree"."ID"'); diff --git a/src/Reports/ShopSalesReport.php b/src/Reports/ShopSalesReport.php index e3617cb9a..eb40c4686 100644 --- a/src/Reports/ShopSalesReport.php +++ b/src/Reports/ShopSalesReport.php @@ -28,11 +28,11 @@ class ShopSalesReport extends ShopPeriodReport public function columns() { $period = isset($_GET['filters']['Grouping']) ? $_GET['filters']['Grouping'] : 'Month'; - return array( + return [ 'FilterPeriod' => $period, 'Count' => 'Order Count', 'Sales' => 'Total Sales', - ); + ]; } public function query($params) diff --git a/src/Reports/TaxReport.php b/src/Reports/TaxReport.php index 7fd3b66c3..605de284c 100644 --- a/src/Reports/TaxReport.php +++ b/src/Reports/TaxReport.php @@ -26,12 +26,12 @@ class TaxReport extends ShopPeriodReport public function columns() { $period = isset($_GET['filters']['Grouping']) ? $_GET['filters']['Grouping'] : 'Month'; - return array( + return [ 'FilterPeriod' => $period, 'Count' => 'Order Count', 'Sales' => 'Total Sales', 'Tax' => 'Total Tax', - ); + ]; } public function query($params) diff --git a/src/Tasks/CalculateProductPopularity.php b/src/Tasks/CalculateProductPopularity.php index 42b03733f..3dcddb110 100644 --- a/src/Tasks/CalculateProductPopularity.php +++ b/src/Tasks/CalculateProductPopularity.php @@ -30,7 +30,7 @@ public function run($request) */ public function viasql() { - foreach (array('_Live', '') as $stage) { + foreach (['_Live', ''] as $stage) { $sql = <<ID . ';' ); //make an array of all combos - $alreadyAdded = array(); + $alreadyAdded = []; $alreadyAdded[-1] = -1; if ($allCombos) { foreach ($allCombos as $combo) { diff --git a/src/Tasks/PopulateShopTask.php b/src/Tasks/PopulateShopTask.php index 82aba8731..bc7682ff8 100644 --- a/src/Tasks/PopulateShopTask.php +++ b/src/Tasks/PopulateShopTask.php @@ -44,7 +44,7 @@ public function run($request) $shoppage = ProductCategory::get()->filter('URLSegment', 'shop')->first(); $parentid = $shoppage->ID; - $categoriestopublish = array( + $categoriestopublish = [ 'products', 'electronics', 'apparel', @@ -60,7 +60,7 @@ public function run($request) 'kitchen', 'bedroom', 'stationery', - ); + ]; foreach ($categoriestopublish as $categoryname) { $factory->get(ProductCategory::class, $categoryname)->publishSingle(); } @@ -89,7 +89,7 @@ public function run($request) } //cart page - if (!$page = CartPage::get()->first()) { + if (!CartPage::get()->first()) { $fixture = YamlFixture::create($fixtureDir . '/pages/Cart.yml'); $fixture->writeInto($factory); $page = $factory->get(CartPage::class, 'cart'); @@ -100,7 +100,7 @@ public function run($request) } //checkout page - if (!$page = CheckoutPage::get()->first()) { + if (!CheckoutPage::get()->first()) { $fixture = YamlFixture::create($fixtureDir . '/pages/Checkout.yml'); $fixture->writeInto($factory); $page = $factory->get(CheckoutPage::class, 'checkout'); @@ -122,7 +122,7 @@ public function run($request) } //terms page - if (!$termsPage = Page::get()->filter('URLSegment', 'terms-and-conditions')->first()) { + if (!Page::get()->filter('URLSegment', 'terms-and-conditions')->first()) { $fixture = YamlFixture::create($fixtureDir . '/pages/TermsConditions.yml'); $fixture->writeInto($factory); $page = $factory->get('Page', 'termsconditions'); diff --git a/src/Tasks/ShopEmailPreviewTask.php b/src/Tasks/ShopEmailPreviewTask.php index 97486b5c3..366fbbae4 100644 --- a/src/Tasks/ShopEmailPreviewTask.php +++ b/src/Tasks/ShopEmailPreviewTask.php @@ -26,11 +26,11 @@ class ShopEmailPreviewTask extends BuildTask protected $description = 'Previews shop emails'; - protected $previewableEmails = array( + protected $previewableEmails = [ 'Confirmation', 'Receipt', 'AdminNotification' - ); + ]; /** * @param HTTPRequest $request diff --git a/src/Tasks/ShopMigrationTask.php b/src/Tasks/ShopMigrationTask.php index 51e64b652..30dcb65a8 100644 --- a/src/Tasks/ShopMigrationTask.php +++ b/src/Tasks/ShopMigrationTask.php @@ -99,7 +99,7 @@ public function migrateProductImages() public function migrateMemberFields($order) { if ($member = $order->Member()) { - $fieldstocopy = array( + $fieldstocopy = [ 'FirstName', 'Surname', 'Email', @@ -110,7 +110,7 @@ public function migrateMemberFields($order) 'HomePhone', 'MobilePhone', 'Notes', - ); + ]; foreach ($fieldstocopy as $field) { if (!$order->$field) { $order->$field = $member->$field; diff --git a/tests/php/Cart/ShoppingCartControllerTest.php b/tests/php/Cart/ShoppingCartControllerTest.php index f52c7c6e2..628a35f56 100644 --- a/tests/php/Cart/ShoppingCartControllerTest.php +++ b/tests/php/Cart/ShoppingCartControllerTest.php @@ -62,7 +62,7 @@ class ShoppingCartControllerTest extends FunctionalTest protected $cart; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -120,7 +120,7 @@ public function testAddToCart() // set item quantiy $this->get( - ShoppingCartController::set_quantity_item_link($this->mp3player, array('quantity' => 5)) + ShoppingCartController::set_quantity_item_link($this->mp3player, ['quantity' => 5]) ); //add item via url $items = ShoppingCart::curr()->Items(); $mp3playeritem = @@ -161,7 +161,7 @@ public function testRemoveFromCart() { // add items via url - $this->get(ShoppingCartController::set_quantity_item_link($this->mp3player, array('quantity' => 5))); + $this->get(ShoppingCartController::set_quantity_item_link($this->mp3player, ['quantity' => 5])); $this->assertTrue($this->cart->get($this->mp3player) !== false, "mp3player item now exists in cart"); $this->get(ShoppingCartController::add_item_link($this->socks)); $this->assertTrue($this->cart->get($this->socks) !== false, "socks item now exists in cart"); @@ -196,7 +196,7 @@ public function testSecurityToken() $productId = $this->mp3player->ID; // link should contain the security-token $link = ShoppingCartController::add_item_link($this->mp3player); - $this->assertRegExp('{^shoppingcart/add/SilverShop-Page-Product/' . $productId . '\?SecurityID=[a-f0-9]+$}', $link); + $this->assertMatchesRegularExpression('{^shoppingcart/add/SilverShop-Page-Product/' . $productId . '\?SecurityID=[a-f0-9]+$}', $link); // should redirect back to the shop $response = $this->get($link); diff --git a/tests/php/Cart/ShoppingCartTest.php b/tests/php/Cart/ShoppingCartTest.php index 48c1d9064..c282707b3 100644 --- a/tests/php/Cart/ShoppingCartTest.php +++ b/tests/php/Cart/ShoppingCartTest.php @@ -29,7 +29,7 @@ class ShoppingCartTest extends SapphireTest */ protected $cart; - public function setUp() + public function setUp(): void { parent::setUp(); ShopTest::setConfiguration(); //reset config diff --git a/tests/php/Checkout/CheckoutTest.php b/tests/php/Checkout/CheckoutTest.php index 9052e5d1a..f2ba708e2 100644 --- a/tests/php/Checkout/CheckoutTest.php +++ b/tests/php/Checkout/CheckoutTest.php @@ -16,12 +16,12 @@ class CheckoutTest extends SapphireTest { - protected static $fixture_file = array( + protected static $fixture_file = [ __DIR__ . '/../Fixtures/Pages.yml', __DIR__ . '/../Fixtures/Orders.yml', __DIR__ . '/../Fixtures/Addresses.yml', __DIR__ . '/../Fixtures/ShopMembers.yml', - ); + ]; /** * @var ShoppingCart @@ -48,7 +48,7 @@ class CheckoutTest extends SapphireTest */ protected $memberFactory; - public function setUp() + public function setUp(): void { parent::setUp(); ShopTest::setConfiguration(); @@ -104,14 +104,14 @@ public function testCanBecomeMember() //check can proceeed with/without order //check member exists $result = $this->memberFactory->create( - array( + [ 'FirstName' => 'Jane', 'Surname' => 'Smith', 'Email' => 'jane@example.com', 'Password' => 'janesmith2012', - ) + ] ); - $this->assertTrue(($result instanceof Member), $this->checkout->getMessage()); + $this->assertTrue(($result instanceof Member), $this->checkout->getMessage() || ''); } public function testMustBecomeOrBeMember() @@ -120,12 +120,12 @@ public function testMustBecomeOrBeMember() CheckoutConfig::config()->membership_required = true; $member = $this->memberFactory->create( - array( + [ 'FirstName' => 'Susan', 'Surname' => 'Jackson', 'Email' => 'susan@example.com', 'Password' => 'jaleho3htgll', - ) + ] ); $this->assertTrue($this->checkout->validateMember($member)); @@ -141,12 +141,12 @@ public function testNoMemberships() $this->expectException(ValidationException::class); $member = $this->memberFactory->create( - array( + [ 'FirstName' => 'Susan', 'Surname' => 'Jackson', 'Email' => 'susan@example.com', 'Password' => 'jaleho3htgll', - ) + ] ); } @@ -158,16 +158,18 @@ public function testMembersOnly() { CheckoutConfig::config()->member_creation_enabled = false; CheckoutConfig::config()->membership_required = true; + + $this->expectException(ValidationException::class); + $this->expectExceptionMessage('Creating new memberships is not allowed'); + $result = $this->memberFactory->create( - array( + [ 'FirstName' => 'Some', 'Surname' => 'Body', 'Email' => 'somebody@example.com', 'Password' => 'pass1234', - ) + ] ); - - $this->fail("Exception was expected here"); } /** @@ -176,14 +178,15 @@ public function testMembersOnly() */ public function testMemberWithoutPassword() { + $this->expectException(ValidationException::class); + $this->expectExceptionMessage('A password is required'); $result = $this->memberFactory->create( - array( + [ 'FirstName' => 'Jim', 'Surname' => 'Smith', 'Email' => 'jim@example.com', - ) + ] ); - $this->fail("Exception was expected here"); } /** @@ -192,15 +195,16 @@ public function testMemberWithoutPassword() */ public function testMemberAlreadyExists() { + $this->expectException(ValidationException::class); + $this->expectExceptionMessage('A member already exists with the Email jeremy@example.com'); $result = $this->memberFactory->create( - array( + [ 'FirstName' => 'Jeremy', 'Surname' => 'Peremy', 'Email' => 'jeremy@example.com', 'Password' => 'jeremyperemy', - ) + ] ); - $this->fail("Exception was expected here"); } /** @@ -209,13 +213,14 @@ public function testMemberAlreadyExists() */ public function testMemberMissingIdentifier() { + $this->expectException(ValidationException::class); + $this->expectExceptionMessage('Required field not found: Email'); $result = $this->memberFactory->create( - array( + [ 'FirstName' => 'John', 'Surname' => 'Doe', 'Password' => 'johndoe1234', - ) + ] ); - $this->fail("Exception was expected here"); } } diff --git a/tests/php/Checkout/Component/AddressBookCheckoutComponentTest.php b/tests/php/Checkout/Component/AddressBookCheckoutComponentTest.php index b50bc3000..9e63b6e69 100644 --- a/tests/php/Checkout/Component/AddressBookCheckoutComponentTest.php +++ b/tests/php/Checkout/Component/AddressBookCheckoutComponentTest.php @@ -18,10 +18,10 @@ class AddressBookCheckoutComponentTest extends SapphireTest // Component namespace const COMPONENT_NS = 'SilverShop-Checkout-Component-AddressBookBilling'; - protected static $fixture_file = array( + protected static $fixture_file = [ '../../Fixtures/Orders.yml', '../../Fixtures/ShopMembers.yml', - ); + ]; /** * @var Order $cart @@ -48,7 +48,7 @@ class AddressBookCheckoutComponentTest extends SapphireTest */ protected $config; - protected $fixtureNewAddress = array( + protected $fixtureNewAddress = [ self::COMPONENT_NS . '_BillingAddressID' => 'newaddress', self::COMPONENT_NS . '_Country' => 'US', self::COMPONENT_NS . '_Address' => '123 Test St', @@ -57,9 +57,9 @@ class AddressBookCheckoutComponentTest extends SapphireTest self::COMPONENT_NS . '_State' => 'AR', self::COMPONENT_NS . '_PostalCode' => '72761', self::COMPONENT_NS . '_Phone' => '11231231234', - ); + ]; - public function setUp() + public function setUp(): void { ShopTest::setConfiguration(); CheckoutConfig::config()->membership_required = false; @@ -98,9 +98,9 @@ public function testUseExistingAddress() Security::setCurrentUser($this->member); $this->assertTrue( $this->config->validateData( - array( + [ self::COMPONENT_NS . '_BillingAddressID' => $this->address1->ID, - ) + ] ) ); } @@ -110,9 +110,9 @@ public function testShouldRejectExistingIfNotLoggedIn() $this->expectException(ValidationException::class); $this->assertTrue( $this->config->validateData( - array( + [ self::COMPONENT_NS . '_BillingAddressID' => $this->address1->ID, - ) + ] ) ); } @@ -126,9 +126,9 @@ public function testShouldRejectExistingIfNotOwnedByMember() $this->assertTrue( $this->config->validateData( - array( + [ self::COMPONENT_NS . '_BillingAddressID' => $this->address1->ID, - ) + ] ) ); } @@ -137,9 +137,9 @@ public function testShouldNotCreateBlankAddresses() { $beforeCount = Address::get()->count(); $this->config->setData( - array( + [ self::COMPONENT_NS . '_BillingAddressID' => $this->address1->ID, - ) + ] ); $this->assertEquals($this->cart->BillingAddressID, $this->address1->ID); diff --git a/tests/php/Checkout/Component/CheckoutComponentTest.php b/tests/php/Checkout/Component/CheckoutComponentTest.php index b575026cf..f9422541a 100644 --- a/tests/php/Checkout/Component/CheckoutComponentTest.php +++ b/tests/php/Checkout/Component/CheckoutComponentTest.php @@ -20,12 +20,12 @@ class CheckoutComponentTest extends SapphireTest { - protected static $fixture_file = array( + protected static $fixture_file = [ __DIR__ . '/../../Fixtures/Orders.yml', __DIR__ . '/../../Fixtures/Addresses.yml', __DIR__ . '/../../Fixtures/shop.yml', __DIR__ . '/../../Fixtures/ShopMembers.yml', - ); + ]; /** * @var Order @@ -47,7 +47,7 @@ class CheckoutComponentTest extends SapphireTest */ protected $addressNoCountry; - public function setUp() + public function setUp(): void { parent::setUp(); ShopTest::setConfiguration(); @@ -70,11 +70,11 @@ public function testSinglePageConfig() $customerdetailscomponent = $config->getComponentByType(CustomerDetails::class); $customerdetailscomponent->setData( $order, - array( + [ "FirstName" => "Ed", "Surname" => "Hillary", "Email" => "ed@example.com", - ) + ] ); $shippingaddresscomponent = $config->getComponentByType(ShippingAddress::class); @@ -86,25 +86,25 @@ public function testSinglePageConfig() $paymentcomponent = $config->getComponentByType(Payment::class); $paymentcomponent->setData( $order, - array( + [ "PaymentMethod" => "Dummy", - ) + ] ); $notescomponent = $config->getComponentByType(Notes::class); $notescomponent->setData( $order, - array( + [ "Notes" => "Please bring coffee with goods", - ) + ] ); $termscomponent = $config->getComponentByType(Terms::class); $termscomponent->setData( $order, - array( + [ "ReadTermsAndConditions" => true, - ) + ] ); $components = $config->getComponents(); @@ -114,75 +114,75 @@ public function testSinglePageConfig() $components, "Components must only be of type '$class'" ); - $this->assertContains(CustomerDetails::class, print_r($components, true)); - $this->assertContains(ShippingAddress::class, print_r($components, true)); - $this->assertContains(BillingAddress::class, print_r($components, true)); - $this->assertContains(Payment::class, print_r($components, true)); - $this->assertContains(Notes::class, print_r($components, true)); - $this->assertContains(Terms::class, print_r($components, true)); + $this->assertStringContainsString(CustomerDetails::class, print_r($components, true)); + $this->assertStringContainsString(ShippingAddress::class, print_r($components, true)); + $this->assertStringContainsString(BillingAddress::class, print_r($components, true)); + $this->assertStringContainsString(Payment::class, print_r($components, true)); + $this->assertStringContainsString(Notes::class, print_r($components, true)); + $this->assertStringContainsString(Terms::class, print_r($components, true)); $fields = $config->getFormFields(); $ns = 'SilverShop-Checkout-Component'; - $this->assertContains( + $this->assertStringContainsString( "$ns-CustomerDetails_FirstName", print_r($fields, true), "Form Fields should contain a $ns-CustomerDetails_FirstName field" ); - $this->assertContains( + $this->assertStringContainsString( "$ns-CustomerDetails_Surname", print_r($fields, true), "Form Fields should contain a $ns-CustomerDetails_Surname field" ); - $this->assertContains( + $this->assertStringContainsString( "$ns-CustomerDetails_Email", print_r($fields, true), "Form Fields should contain a $ns-CustomerDetails_Email field" ); - $this->assertContains( + $this->assertStringContainsString( "$ns-ShippingAddress_Country", print_r($fields, true), "Form Fields should contain a $ns-ShippingAddress_Country field" ); - $this->assertContains( + $this->assertStringContainsString( "$ns-ShippingAddress_Address", print_r($fields, true), "Form Fields should contain a $ns-ShippingAddress_Address field" ); - $this->assertContains( + $this->assertStringContainsString( "$ns-ShippingAddress_City", print_r($fields, true), "Form Fields should contain a $ns-ShippingAddress_City field" ); - $this->assertContains( + $this->assertStringContainsString( "$ns-ShippingAddress_State", print_r($fields, true), "Form Fields should contain a $ns-ShippingAddress_State field" ); - $this->assertContains( + $this->assertStringContainsString( "$ns-BillingAddress_Country", print_r($fields, true), "Form Fields should contain a $ns-BillingAddress_Country field" ); - $this->assertContains( + $this->assertStringContainsString( "$ns-BillingAddress_Address", print_r($fields, true), "Form Fields should contain a $ns-BillingAddress_Address field" ); - $this->assertContains( + $this->assertStringContainsString( "$ns-BillingAddress_City", print_r($fields, true), "Form Fields should contain a $ns-BillingAddress_City field" ); - $this->assertContains( + $this->assertStringContainsString( "$ns-BillingAddress_State", print_r($fields, true), "Form Fields should contain a $ns-BillingAddress_State field" ); - $this->assertNotContains("rubbish", print_r($fields, true), "Form Field should not include 'rubbish'"); + $this->assertStringNotContainsString("rubbish", print_r($fields, true), "Form Field should not include 'rubbish'"); $required = $config->getRequiredFields(); - $requiredfields = array( + $requiredfields = [ "$ns-CustomerDetails_FirstName", "$ns-CustomerDetails_Surname", "$ns-CustomerDetails_Email", @@ -194,7 +194,7 @@ public function testSinglePageConfig() "$ns-BillingAddress_State", "$ns-BillingAddress_City", "$ns-BillingAddress_Address", - ); + ]; $this->assertSame( $requiredfields, $required, @@ -257,11 +257,11 @@ public function testSinglePageConfigForSingleCountrySiteWithReadonlyFieldsForCou $customerdetailscomponent = $config->getComponentByType(CustomerDetails::class); $customerdetailscomponent->setData( $order, - array( + [ "FirstName" => "John", "Surname" => "Walker", "Email" => "jw@example.com", - ) + ] ); $shippingaddresscomponent = $config->getComponentByType(ShippingAddress::class); @@ -273,22 +273,22 @@ public function testSinglePageConfigForSingleCountrySiteWithReadonlyFieldsForCou $paymentcomponent = $config->getComponentByType(Payment::class); $paymentcomponent->setData( $order, - array( + [ "PaymentMethod" => "Dummy", - ) + ] ); $fields = $config->getFormFields(); $ns = 'SilverShop-Checkout-Component'; - $shippingaddressfield = $fields->fieldByName("$ns-ShippingAddress_Country_readonly"); - $billingaddressfield = $fields->fieldByName("$ns-BillingAddress_Country_readonly"); + $shippingaddressfield = $fields->dataFieldByName("$ns-ShippingAddress_Country_readonly"); + $billingaddressfield = $fields->dataFieldByName("$ns-BillingAddress_Country_readonly"); - $this->assertContains( + $this->assertStringContainsString( "New Zealand", $shippingaddressfield->Value(), "The value of the Shipping Country readonly field is 'New Zealand'" ); - $this->assertContains( + $this->assertStringContainsString( "New Zealand", $billingaddressfield->Value(), "The value of the Billing Country readonly field is 'New Zealand'" @@ -297,7 +297,7 @@ public function testSinglePageConfigForSingleCountrySiteWithReadonlyFieldsForCou $this->assertTrue($shippingaddressfield->isReadonly(), "The Billing Address Country field is readonly"); $required = $config->getRequiredFields(); - $requiredfieldswithCountryAbsent = array( + $requiredfieldswithCountryAbsent = [ "$ns-CustomerDetails_FirstName", "$ns-CustomerDetails_Surname", "$ns-CustomerDetails_Email", @@ -307,7 +307,7 @@ public function testSinglePageConfigForSingleCountrySiteWithReadonlyFieldsForCou "$ns-BillingAddress_State", "$ns-BillingAddress_City", "$ns-BillingAddress_Address", - ); + ]; $this->assertSame( $requiredfieldswithCountryAbsent, $required, diff --git a/tests/php/Checkout/NestedCheckoutTest.php b/tests/php/Checkout/NestedCheckoutTest.php index 47ce8a474..a35380804 100644 --- a/tests/php/Checkout/NestedCheckoutTest.php +++ b/tests/php/Checkout/NestedCheckoutTest.php @@ -10,7 +10,7 @@ class NestedCheckoutTest extends SapphireTest { public static $fixture_file = __DIR__ . '/../Fixtures/pages/NestedCheckout.yml'; - public function setUp() + public function setUp(): void { parent::setUp(); } diff --git a/tests/php/Checkout/OrderEmailNotifierTest.php b/tests/php/Checkout/OrderEmailNotifierTest.php index b144cb4ef..7138ca5c2 100644 --- a/tests/php/Checkout/OrderEmailNotifierTest.php +++ b/tests/php/Checkout/OrderEmailNotifierTest.php @@ -26,7 +26,7 @@ class OrderEmailNotifierTest extends SapphireTest */ protected $notifier; - public function setUp() + public function setUp(): void { parent::setUp(); Config::modify()->set(Email::class, 'admin_email', 'shop-admin@example.com'); diff --git a/tests/php/Checkout/OrderProcessorTest.php b/tests/php/Checkout/OrderProcessorTest.php index 55c384f7c..691fab39c 100644 --- a/tests/php/Checkout/OrderProcessorTest.php +++ b/tests/php/Checkout/OrderProcessorTest.php @@ -30,6 +30,7 @@ class OrderProcessorTest extends SapphireTest protected static $fixture_file = __DIR__ . '/../Fixtures/shop.yml'; protected static $disable_theme = true; protected static $use_draft_site = true; + protected $usesTransactions = false; protected $processor; protected static $extra_dataobjects = [ @@ -61,7 +62,7 @@ class OrderProcessorTest extends SapphireTest */ protected $shoppingcart; - public function setUp() + public function setUp(): void { parent::setUp(); ShoppingCart::singleton()->clear(); @@ -102,7 +103,7 @@ public function testPlaceOrder() 'FirstName' => 'James', 'Surname' => 'Brown', 'Email' => 'james@example.com', - 'Password' => 'jbrown', + 'Password' => '23u90oijlJKsa', ] ); $this->assertTrue((bool)$member); @@ -192,16 +193,16 @@ public function testPlaceFailure() $cart->calculate(); $this->assertListContains( - array( - array('ClassName' => OrderProcessorTest_CustomOrderItem::class) - ), + [ + ['ClassName' => OrderProcessorTest_CustomOrderItem::class] + ], $cart->Items() ); $versions = OrderItem::get()->filter('OrderID', $cart->ID)->column('ProductVersion'); // The Product_OrderItem should not reference a product version while the order is not placed - $this->assertEquals(array(0), $versions); + $this->assertEquals([0], $versions); $this->assertTrue($cart->has_extension(OrderProcessorTest_PlaceFailExtension::class)); @@ -236,7 +237,7 @@ public function testPlaceFailure() $versions = OrderItem::get()->filter('OrderID', $cart->ID)->column('ProductVersion'); // The Product_OrderItem should still not reference a product if the rollback worked - $this->assertEquals(array(0), $versions); + $this->assertEquals([0], $versions); $this->assertEquals( 0, @@ -368,7 +369,7 @@ public function testPlaceOrderMarksAsPaidWithNoOutstandingAmount() 'SilverShop\ShopEmail.ReceiptSubject', 'Order #{OrderNo} receipt', '', - array('OrderNo' => $order->Reference) + ['OrderNo' => $order->Reference] ); // Ensure receipt was sent $this->assertEmailSent('receipt@example.com', 'shopadmin@example.com', $subject); @@ -391,14 +392,14 @@ protected function placeOrder( $confirmpassword = null, $member = null ) { - $data = array( + $data = [ 'FirstName' => $firstname, 'Surname' => $surname, 'Email' => $email, 'Address' => $address1, 'City' => $city, 'State' => $state, - ); + ]; if ($address2) { $data['AddressLine2'] = $address2; } diff --git a/tests/php/Checkout/OrderProcessorTest_CustomOrderItem.php b/tests/php/Checkout/OrderProcessorTest_CustomOrderItem.php index 9e3a013a8..c19335742 100644 --- a/tests/php/Checkout/OrderProcessorTest_CustomOrderItem.php +++ b/tests/php/Checkout/OrderProcessorTest_CustomOrderItem.php @@ -8,9 +8,9 @@ // Class that writes order-item data to the DB upon placement class OrderProcessorTest_CustomOrderItem extends OrderItem implements TestOnly { - private static $db = array( + private static $db = [ 'IsPlaced' => 'Boolean' - ); + ]; private static $table_name = 'SilverShop_Test_CustomOrderItem'; diff --git a/tests/php/Checkout/ShopPaymentTest.php b/tests/php/Checkout/ShopPaymentTest.php index f134131e5..5b2a9010e 100644 --- a/tests/php/Checkout/ShopPaymentTest.php +++ b/tests/php/Checkout/ShopPaymentTest.php @@ -2,8 +2,7 @@ namespace SilverShop\Tests\Checkout; -use Guzzle\Http\Client; -use Guzzle\Plugin\Mock\MockPlugin; +use GuzzleHttp\Psr7\Message; use SilverShop\Cart\ShoppingCart; use SilverShop\Checkout\OrderProcessor; use SilverShop\Model\Order; @@ -16,28 +15,23 @@ use SilverStripe\Dev\FunctionalTest; use SilverStripe\Dev\TestSession; use SilverStripe\Omnipay\Model\Payment; -use SilverStripe\Omnipay\Service\PaymentService; use SilverStripe\Omnipay\Tests\Service\TestGatewayFactory; -use Symfony\Component\HttpFoundation\Request; class ShopPaymentTest extends FunctionalTest { - protected static $fixture_file = array( + protected static $fixture_file = [ __DIR__ . '/../Fixtures/Pages.yml', __DIR__ . '/../Fixtures/shop.yml', - ); + ]; public static $disable_theme = true; protected $autoFollowRedirection = false; - public function setUp() + /** @var \GuzzleHttp\Handler\MockHandler */ + protected $mockHandler = null; + + public function setUp(): void { parent::setUp(); - - /* - DataObject::reset(); - ClassLoader::inst()->init(false, true); - Debug::dump(ClassInfo::subclassesFor(OrderItem::class)); - */ ShoppingCart::singleton()->clear(); ShopTest::setConfiguration(); @@ -69,16 +63,25 @@ public function setUp() $this->objFromFixture(CartPage::class, "cart")->publishSingle(); } + /** + * @doesNotPerformAssertions + */ public function testManualPayment() { $this->markTestIncomplete("Process a manual payment"); } + /** + * @doesNotPerformAssertions + */ public function testOnsitePayment() { $this->markTestIncomplete("Process an onsite payment"); } + /** + * @doesNotPerformAssertions + */ public function testOffsitePayment() { $this->markTestIncomplete("Process an off-site payment"); @@ -92,23 +95,23 @@ public function testOffsitePaymentWithGatewayCallback() ->current(); //collect checkout details $cart->update( - array( + [ 'FirstName' => 'Foo', 'Surname' => 'Bar', 'Email' => 'foo@example.com', - ) + ] ); $cart->write(); //pay for order with external gateway $processor = OrderProcessor::create($cart); $this->setMockHttpResponse('paymentexpress/tests/Mock/PxPayPurchaseSuccess.txt'); - $response = $processor->makePayment("PaymentExpress_PxPay", array()); + $response = $processor->makePayment("PaymentExpress_PxPay", []); //gateway responds (in a different session) $oldsession = $this->mainSession; $this->mainSession = new TestSession(); ShoppingCart::singleton()->clear(); $this->setMockHttpResponse('paymentexpress/tests/Mock/PxPayCompletePurchaseSuccess.txt'); - $this->getHttpRequest()->query->replace(array('result' => 'abc123')); + $this->getHttpRequest()->query->replace(['result' => 'abc123']); $identifier = $response->getPayment()->Identifier; //bring back client session @@ -122,8 +125,6 @@ public function testOffsitePaymentWithGatewayCallback() $this->assertTrue($order->isPaid(), "order is paid"); $this->assertNull($this->mainSession->session()->get("shoppingcartid"), "cart session id should be removed"); $this->assertNotEquals(404, $response->getStatusCode(), "We shouldn't get page not found"); - - $this->markTestIncomplete("Should assert other things"); } protected $payment; @@ -133,7 +134,15 @@ public function testOffsitePaymentWithGatewayCallback() protected function getHttpClient() { if (null === $this->httpClient) { - $this->httpClient = new Client(); + if ($this->mockHandler === null) { + $this->mockHandler = new \GuzzleHttp\Handler\MockHandler(); + } + + $guzzle = new \GuzzleHttp\Client([ + 'handler' => $this->mockHandler, + ]); + + $this->httpClient = new \Omnipay\Common\Http\Client(new \Http\Adapter\Guzzle7\Client($guzzle)); } return $this->httpClient; @@ -142,7 +151,7 @@ protected function getHttpClient() protected function getHttpRequest() { if (null === $this->httpRequest) { - $this->httpRequest = new Request(); + $this->httpRequest = new \Symfony\Component\HttpFoundation\Request; } return $this->httpRequest; @@ -150,14 +159,18 @@ protected function getHttpRequest() protected function setMockHttpResponse($paths) { + if ($this->mockHandler === null) { + throw new \Exception('HTTP client not initialised before adding mock response.'); + } + $testspath = BASE_PATH . '/vendor/omnipay'; - $mock = new MockPlugin(null, true); - $this->getHttpClient()->getEventDispatcher()->removeSubscriber($mock); + foreach ((array)$paths as $path) { - $mock->addResponse($testspath . '/' . $path); + $this->mockHandler->append( + Message::parseResponse(file_get_contents("{$testspath}/{$path}")) + ); } - $this->getHttpClient()->getEventDispatcher()->addSubscriber($mock); - return $mock; + return $this->mockHandler; } } diff --git a/tests/php/Extension/MemberExtensionTest.php b/tests/php/Extension/MemberExtensionTest.php index 955dd59e9..95d317835 100644 --- a/tests/php/Extension/MemberExtensionTest.php +++ b/tests/php/Extension/MemberExtensionTest.php @@ -15,10 +15,10 @@ */ class MemberExtensionTest extends SapphireTest { - public static $fixture_file = array( + public static $fixture_file = [ __DIR__ . '/../Fixtures/ShopMembers.yml', __DIR__ . '/../Fixtures/shop.yml', - ); + ]; public function testGetByIdentifier() { @@ -29,6 +29,9 @@ public function testGetByIdentifier() $this->assertEquals('Jeremy', $member->FirstName); } + /** + * @doesNotPerformAssertions + */ public function testCMSFields() { singleton(Member::class)->getCMSFields(); diff --git a/tests/php/Extension/ProductImageExtensionTest.php b/tests/php/Extension/ProductImageExtensionTest.php index 5ccd78b8c..c92eb69b1 100644 --- a/tests/php/Extension/ProductImageExtensionTest.php +++ b/tests/php/Extension/ProductImageExtensionTest.php @@ -40,7 +40,7 @@ class ProductImageExtensionTest extends SapphireTest */ protected $siteConfig; - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/php/Extension/SteppedCheckoutExtensionTest.php b/tests/php/Extension/SteppedCheckoutExtensionTest.php index ac9d00b6a..a6745fc70 100644 --- a/tests/php/Extension/SteppedCheckoutExtensionTest.php +++ b/tests/php/Extension/SteppedCheckoutExtensionTest.php @@ -53,7 +53,7 @@ class SteppedCheckoutExtensionTest extends FunctionalTest */ protected $cart; - public function setUp() + public function setUp(): void { parent::setUp(); $this->logInWithPermission('ADMIN'); @@ -122,19 +122,19 @@ public function testMembershipStep() $this->checkout->handleRequest($this->buildTestRequest('checkout/createaccount')); */ $form = $this->checkout->MembershipForm(); - $data = array(); + $data = []; $form->loadDataFrom($data); - $data = array( + $data = [ 'FirstName' => 'Michael', 'Surname' => 'Black', 'Email' => 'mb@example.com', - 'Password' => array( + 'Password' => [ '_Password' => 'pass1234', '_ConfirmPassword' => 'pass1234', - ), + ], 'action_docreateaccount' => 'Create New Account', - ); + ]; $response = $this->post('/checkout/CreateAccountForm', $data); //redirect to next step $member = MemberExtension::get_by_identifier("mb@example.com"); @@ -148,12 +148,12 @@ public function testContactDetails() $user = $this->objFromFixture(Member::class, "joebloggs"); Security::setCurrentUser($user); $this->checkout->handleRequest($this->buildTestRequest('contactdetails')); - $data = array( + $data = [ 'FirstName' => 'Pauline', 'Surname' => 'Richardson', 'Email' => 'p.richardson@example.com', 'action_setcontactdetails' => 1, - ); + ]; $response = $this->post('/checkout/ContactDetailsForm', $data); $this->markTestIncomplete('check order has been updated'); @@ -164,14 +164,14 @@ public function testShippingAddress() $user = $this->objFromFixture(Member::class, "joebloggs"); Security::setCurrentUser($user); $this->checkout->handleRequest($this->buildTestRequest('shippingaddress')); - $data = array( + $data = [ 'Address' => '2b Baba place', 'AddressLine2' => 'Level 2', 'City' => 'Newton', 'State' => 'Wellington', 'Country' => 'NZ', 'action_setaddress' => 1, - ); + ]; $response = $this->post('/checkout/AddressForm', $data); $this->markTestIncomplete('assertions!'); @@ -182,14 +182,14 @@ public function testBillingAddress() $user = $this->objFromFixture(Member::class, "joebloggs"); Security::setCurrentUser($user); $this->checkout->handleRequest($this->buildTestRequest('billingaddress')); - $data = array( + $data = [ 'Address' => '3 Art Cresent', 'AddressLine2' => '', 'City' => 'Walkworth', 'State' => 'New Caliphoneya', 'Country' => 'ZA', 'action_setbillingaddress' => 1, - ); + ]; $response = $this->post('/checkout/AddressForm', $data); $this->markTestIncomplete('assertions!'); @@ -197,10 +197,10 @@ public function testBillingAddress() public function testPaymentMethod() { - $data = array( + $data = [ 'PaymentMethod' => 'Dummy', 'action_setpaymentmethod' => 1, - ); + ]; $response = $this->post('/checkout/PaymentMethodForm', $data); $this->assertEquals('Dummy', Checkout::get($this->cart)->getSelectedPaymentMethod()); } @@ -212,10 +212,10 @@ public function testSummary() * @var PaymentForm $form */ $form = $this->checkout->ConfirmationForm(); - $data = array( + $data = [ 'Notes' => 'Leave it around the back', 'ReadTermsAndConditions' => 1, - ); + ]; $member = $this->objFromFixture(Member::class, "joebloggs"); Security::setCurrentUser($member); @@ -231,7 +231,7 @@ public function testSummary() //redirect to make payment $this->assertEquals(302, $response->getStatusCode()); - $this->assertContains( + $this->assertStringContainsString( '/checkout/payment', $response->getHeader('location') ); diff --git a/tests/php/Extension/ViewableCartExtensionTest.php b/tests/php/Extension/ViewableCartExtensionTest.php index 830a87253..2d2f81b0e 100644 --- a/tests/php/Extension/ViewableCartExtensionTest.php +++ b/tests/php/Extension/ViewableCartExtensionTest.php @@ -15,7 +15,7 @@ class ViewableCartExtensionTest extends FunctionalTest public static $fixture_file = __DIR__ . '/../Fixtures/shop.yml'; public static $disable_theme = true; - function setUp() + public function setUp(): void { parent::setUp(); ShoppingCart::singleton()->clear(); diff --git a/tests/php/Fixtures/shop.yml b/tests/php/Fixtures/shop.yml index c0992af6c..1fb1cc979 100644 --- a/tests/php/Fixtures/shop.yml +++ b/tests/php/Fixtures/shop.yml @@ -114,6 +114,7 @@ SilverShop\Model\Order: Name: Cart Total: 8 unpaid: + Email: hi@there.net Status: Unpaid Created: '2012-11-21 15:23:32' Placed: '2012-11-21 15:33:02' diff --git a/tests/php/Forms/AddProductFormTest.php b/tests/php/Forms/AddProductFormTest.php index 50e7a843e..fa47b6ae7 100644 --- a/tests/php/Forms/AddProductFormTest.php +++ b/tests/php/Forms/AddProductFormTest.php @@ -20,9 +20,9 @@ public function testForm() $this->markTestIncomplete("test can't go over max quantity"); - $data = array( + $data = [ 'Quantity' => 4, - ); + ]; $form->addtocart($data, $form); $this->markTestIncomplete('check quantity'); diff --git a/tests/php/Forms/CheckoutFormTest.php b/tests/php/Forms/CheckoutFormTest.php index 540d33943..745181ea0 100644 --- a/tests/php/Forms/CheckoutFormTest.php +++ b/tests/php/Forms/CheckoutFormTest.php @@ -37,7 +37,7 @@ class CheckoutFormTest extends FunctionalTest */ protected $checkoutcontroller; - public function setUp() + public function setUp(): void { parent::setUp(); ShoppingCart::singleton()->clear(); @@ -63,7 +63,7 @@ public function testCheckoutForm() $config = new SinglePageCheckoutComponentConfig($order); $form = new CheckoutForm($this->checkoutcontroller, "OrderForm", $config); $ns = 'SilverShop-Checkout-Component-'; - $data = array( + $data = [ "{$ns}CustomerDetails_FirstName" => "Jane", "{$ns}CustomerDetails_Surname" => "Smith", "{$ns}CustomerDetails_Email" => "janesmith@example.com", @@ -84,7 +84,7 @@ public function testCheckoutForm() "{$ns}Payment_PaymentMethod" => "Dummy", "{$ns}Notes_Notes" => "Leave it around the back", "{$ns}Terms_ReadTermsAndConditions" => "1", - ); + ]; $form->loadDataFrom($data, true); $valid = $form->validationResult()->isValid(); $errors = $form->getValidator()->getErrors(); @@ -116,7 +116,7 @@ public function testCheckoutFormForSingleCountrySiteWithReadonlyFieldsForCountry $form = new CheckoutForm($this->checkoutcontroller, "OrderForm", $config); $ns = 'SilverShop-Checkout-Component-'; // no country fields due to readonly field - $dataCountryAbsent = array( + $dataCountryAbsent = [ "{$ns}CustomerDetails_FirstName" => "Jane", "{$ns}CustomerDetails_Surname" => "Smith", "{$ns}CustomerDetails_Email" => "janesmith@example.com", @@ -135,17 +135,17 @@ public function testCheckoutFormForSingleCountrySiteWithReadonlyFieldsForCountry "{$ns}Payment_PaymentMethod" => "Dummy", "{$ns}Notes_Notes" => "Leave it around the back", "{$ns}Terms_ReadTermsAndConditions" => "1", - ); + ]; $form->loadDataFrom($dataCountryAbsent, true); $valid = $form->validationResult()->isValid(); $errors = $form->getValidator()->getErrors(); $this->assertTrue($valid, print_r($errors, true)); $this->assertTrue( - $form->Fields()->fieldByName("{$ns}ShippingAddress_Country_readonly")->isReadonly(), + $form->Fields()->dataFieldByName("{$ns}ShippingAddress_Country_readonly")->isReadonly(), "Shipping Address Country field is readonly" ); $this->assertTrue( - $form->Fields()->fieldByName("{$ns}BillingAddress_Country_readonly")->isReadonly(), + $form->Fields()->dataFieldByName("{$ns}BillingAddress_Country_readonly")->isReadonly(), "Billing Address Country field is readonly" ); $form->checkoutSubmit($dataCountryAbsent, $form); diff --git a/tests/php/Forms/OrderActionsFormTest.php b/tests/php/Forms/OrderActionsFormTest.php index 5ef4e4048..4f68b83f1 100644 --- a/tests/php/Forms/OrderActionsFormTest.php +++ b/tests/php/Forms/OrderActionsFormTest.php @@ -20,10 +20,10 @@ class OrderActionsFormTest extends FunctionalTest { - protected static $fixture_file = array( + protected static $fixture_file = [ __DIR__ . '/../Fixtures/Pages.yml', __DIR__ . '/../Fixtures/shop.yml', - ); + ]; // This seems to be required, because we query the OrderItem table and thus this gets included… // TODO: Remove once we figure out how to circumvent that… @@ -34,7 +34,7 @@ class OrderActionsFormTest extends FunctionalTest protected $order; protected $checkoutPage; - public function setUp() + public function setUp(): void { parent::setUp(); ShopTest::setConfiguration(); @@ -60,7 +60,7 @@ public function setUp() public function testOffsitePayment() { - Config::modify()->set(GatewayInfo::class, 'Dummy', array('is_offsite' => true)); + Config::modify()->set(GatewayInfo::class, 'Dummy', ['is_offsite' => true]); $stubGateway = $this->buildPaymentGatewayStub(true, 'test-' . $this->order->ID, true); Injector::inst()->registerService($this->stubGatewayFactory($stubGateway), 'Omnipay\Common\GatewayFactory'); @@ -68,11 +68,11 @@ public function testOffsitePayment() $response = Director::test( $ctrl->Link('ActionsForm'), - array( + [ 'action_dopayment' => true, 'OrderID' => $this->order->ID, 'PaymentMethod' => 'Dummy' - ), + ], $this->session() ); @@ -93,7 +93,7 @@ public function testOnsitePayment() $response = Director::test( $ctrl->Link('ActionsForm'), - array( + [ 'action_dopayment' => true, 'OrderID' => $this->order->ID, 'PaymentMethod' => 'Dummy', @@ -103,7 +103,7 @@ public function testOnsitePayment() 'expiryMonth' => 10, 'expiryYear' => date('Y') + 1, 'cvv' => 123 - ), + ], $this->session() ); @@ -125,13 +125,13 @@ public function testValidation() ); $validator->setForm($form); $validator->php( - array( + [ 'OrderID' => $this->order->ID, 'PaymentMethod' => 'Dummy', 'type' => 'visa', 'name' => 'Tester Mc. Testerson', 'number' => '4242424242424242' - ) + ] ); $requiredCount = 0; @@ -192,7 +192,7 @@ protected function buildPaymentGatewayStub( // Build the gateway $stubGateway = $this->getMockBuilder('Omnipay\Common\AbstractGateway') - ->setMethods(array('purchase', 'supportsCompletePurchase', 'getName')) + ->setMethods(['purchase', 'supportsCompletePurchase', 'getName']) ->getMock(); $stubGateway->expects($this->any()) diff --git a/tests/php/Model/Modifiers/FlatTaxModifierTest.php b/tests/php/Model/Modifiers/FlatTaxModifierTest.php index 8bc73d961..7c619693a 100644 --- a/tests/php/Model/Modifiers/FlatTaxModifierTest.php +++ b/tests/php/Model/Modifiers/FlatTaxModifierTest.php @@ -35,7 +35,7 @@ class FlatTaxModifierTest extends FunctionalTest */ protected $cart; - public function setUp() + public function setUp(): void { parent::setUp(); ShoppingCart::singleton()->clear(); diff --git a/tests/php/Model/Modifiers/GlobalTaxModifierTest.php b/tests/php/Model/Modifiers/GlobalTaxModifierTest.php index 0c6f56c11..14fc799bf 100644 --- a/tests/php/Model/Modifiers/GlobalTaxModifierTest.php +++ b/tests/php/Model/Modifiers/GlobalTaxModifierTest.php @@ -9,7 +9,7 @@ class GlobalTaxModifierTest extends SapphireTest { - public function setUp() + public function setUp(): void { parent::setUp(); @@ -23,8 +23,8 @@ public function setUp() GlobalTax::class, 'country_rates', [ - 'NZ' => array('rate' => 0.15, 'name' => 'GST', 'exclusive' => false), - 'UK' => array('rate' => 0.175, 'name' => 'VAT', 'exclusive' => true), + 'NZ' => ['rate' => 0.15, 'name' => 'GST', 'exclusive' => false], + 'UK' => ['rate' => 0.175, 'name' => 'VAT', 'exclusive' => true], ] ); } diff --git a/tests/php/Model/Modifiers/OrderModifierTest.php b/tests/php/Model/Modifiers/OrderModifierTest.php index a993801ac..06ed51ae8 100644 --- a/tests/php/Model/Modifiers/OrderModifierTest.php +++ b/tests/php/Model/Modifiers/OrderModifierTest.php @@ -21,6 +21,7 @@ class OrderModifierTest extends FunctionalTest { public static $fixture_file = __DIR__ . '/../../Fixtures/shop.yml'; public static $disable_theme = true; + protected $usesTransactions = false; protected static $use_draft_site = true; /** @@ -38,7 +39,7 @@ class OrderModifierTest extends FunctionalTest OrderModifierTest_TestModifier::class ]; - public function setUp() + public function setUp(): void { parent::setUp(); ShopTest::setConfiguration(); @@ -97,12 +98,12 @@ public function testModifierFailure() // 408 from items + 10 from modifier + 25% from tax $this->assertEquals('522.5', $order->Total); - $amounts = array(); + $amounts = []; foreach ($order->Modifiers()->sort('Sort') as $modifier) { $amounts[] = (string)$modifier->Amount; } - $this->assertEquals(array('10', '104.5'), $amounts); + $this->assertEquals(['10', '104.5'], $amounts); OrderModifierTest_TestModifier::$value = 42; @@ -118,16 +119,12 @@ public function testModifierFailure() // Order Total should not have changed $this->assertEquals('522.5', $order->Total); - $amounts = array(); + $amounts = []; foreach ($order->Modifiers()->sort('Sort') as $modifier) { $amounts[] = (string)$modifier->Amount; } - $this->assertEquals( - array('10', '104.5'), - $amounts, - 'Modifiers aren\'t allowed to change upon failure' - ); + $this->assertEquals(['10', '104.5'], $amounts); } public function createOrder() diff --git a/tests/php/Model/Modifiers/SimpleShippingModifierTest.php b/tests/php/Model/Modifiers/SimpleShippingModifierTest.php index 2c50214fb..6d13a7fd4 100644 --- a/tests/php/Model/Modifiers/SimpleShippingModifierTest.php +++ b/tests/php/Model/Modifiers/SimpleShippingModifierTest.php @@ -12,7 +12,7 @@ */ class SimpleShippingModifierTest extends SapphireTest { - public function setUp() + public function setUp(): void { parent::setUp(); Config::modify() diff --git a/tests/php/Model/OrderStatusLogTest.php b/tests/php/Model/OrderStatusLogTest.php index 7956c62a0..44c25f18a 100644 --- a/tests/php/Model/OrderStatusLogTest.php +++ b/tests/php/Model/OrderStatusLogTest.php @@ -20,17 +20,17 @@ */ class OrderStatusLogTest extends SapphireTest { - protected static $fixture_file = array( + protected static $fixture_file = [ __DIR__ . '/../Fixtures/Orders.yml', __DIR__ . '/../Fixtures/ShopMembers.yml', __DIR__ . '/../Fixtures/Pages.yml' - ); + ]; - public function setUp() + public function setUp(): void { parent::setUp(); ShopTest::setConfiguration(); - Config::modify()->set(Order::class, 'log_status', array('Processing', 'Sent', 'AdminCancelled', 'MemberCancelled')); + Config::modify()->set(Order::class, 'log_status', ['Processing', 'Sent', 'AdminCancelled', 'MemberCancelled']); } public function testOrderStatusLogItemsWithMember() @@ -56,7 +56,7 @@ public function testOrderStatusLogItemsWithMember() ); $processor = OrderProcessor::create($order); - $response = $processor->makePayment("Manual", array()); + $processor->makePayment("Manual", []); $order->Status = "Paid"; $order->write(); @@ -81,12 +81,12 @@ public function testOrderStatusLogItemsWithMember() "Log conatins an Order" ); - $this->assertContains( + $this->assertStringContainsString( "Processing", $log_order_status_processing->Note, "Processing note is recorded" ); - $this->assertContains( + $this->assertStringContainsString( 'changed to "Processing"', $log_order_status_processing->Title, 'Processing title is recorded' @@ -114,12 +114,12 @@ public function testOrderStatusLogItemsWithMember() $order->ID, "Log conatins an Order" ); - $this->assertContains( + $this->assertStringContainsString( "sent", $log_order_status_sent->Note, "Sent note is recorded" ); - $this->assertContains( + $this->assertStringContainsString( 'changed to "Sent"', $log_order_status_sent->Title, "Sent title is recorded" @@ -157,12 +157,12 @@ public function testOrderStatusLogItemsWithMember() $order->ID, "Log conatins an Order" ); - $this->assertContains( + $this->assertStringContainsString( "cancelled", $log_order_status_admin_cancelled->Note, "Admin Cancelled note is recorded" ); - $this->assertContains( + $this->assertStringContainsString( 'changed to "Cancelled by admin"', $log_order_status_admin_cancelled->Title, "Admin Cancelled title is recorded" @@ -195,7 +195,7 @@ public function testOrderStatusLogItemsWithMember() $log_order_status_member_cancelled->Note, "Member Cancelled note is recorded" ); - $this->assertContains( + $this->assertStringContainsString( ' changed to "Cancelled by member"', $log_order_status_member_cancelled->Title, "Member Cancelled title is recorded" @@ -280,7 +280,7 @@ public function testOrderPlacedByGuest() ); $processor_guest = OrderProcessor::create($order); - $response = $processor_guest->makePayment("Manual", array()); + $processor_guest->makePayment("Manual", []); $order->Status = "Paid"; $order->write(); @@ -305,12 +305,12 @@ public function testOrderPlacedByGuest() "Log conatins an Order" ); - $this->assertContains( + $this->assertStringContainsString( "Processing", $log_order_status_processing->Note, "Processing note is recorded" ); - $this->assertContains( + $this->assertStringContainsString( ' changed to "Processing"', $log_order_status_processing->Title, "Processing title is recorded" diff --git a/tests/php/Model/OrderTest.php b/tests/php/Model/OrderTest.php index cf20e0679..591befbba 100644 --- a/tests/php/Model/OrderTest.php +++ b/tests/php/Model/OrderTest.php @@ -49,7 +49,7 @@ class OrderTest extends SapphireTest protected $beachball; - public function setUp() + public function setUp(): void { parent::setUp(); ShopTest::setConfiguration(); @@ -62,7 +62,7 @@ public function setUp() $this->beachball->publishSingle(); } - public function tearDown() + public function tearDown(): void { parent::tearDown(); unset($this->mp3player); @@ -95,10 +95,10 @@ public function testOrderItems() $items = $order->Items(); $this->assertNotNull($items); $this->assertListEquals( - array( - array('ProductID' => $this->mp3player->ID, 'Quantity' => 2, 'CalculatedTotal' => 400), - array('ProductID' => $this->socks->ID, 'Quantity' => 1, 'CalculatedTotal' => 8), - ), + [ + ['ProductID' => $this->mp3player->ID, 'Quantity' => 2, 'CalculatedTotal' => 400], + ['ProductID' => $this->socks->ID, 'Quantity' => 1, 'CalculatedTotal' => 8], + ], $items ); $this->assertEquals(3, $items->Quantity(), "Quantity is 3"); @@ -119,11 +119,11 @@ public function testRounding() { //create an order with unrounded total $order = new Order( - array( + [ 'Total' => 123.257323, //NOTE: setTotal isn't called here, so un-rounded data *could* get in to the object 'Status' => 'Unpaid', - ) + ] ); $order->Total = 123.257323; //setTotal IS called here $this->assertEquals(123.26, $order->Total(), "Check total rounds appropriately"); @@ -156,10 +156,10 @@ public function testPlacedOrderImmutability() ); $this->assertNotNull($items); $this->assertListEquals( - array( - array('ProductID' => $this->mp3player->ID, 'Quantity' => 2, 'CalculatedTotal' => 400), - array('ProductID' => $this->socks->ID, 'Quantity' => 1, 'CalculatedTotal' => 8), - ), + [ + ['ProductID' => $this->mp3player->ID, 'Quantity' => 2, 'CalculatedTotal' => 400], + ['ProductID' => $this->socks->ID, 'Quantity' => 1, 'CalculatedTotal' => 8], + ], $items ); @@ -298,12 +298,13 @@ public function testStatusChange() $orderId = $order->write(); $order->Status = 'Unpaid'; + $order->Email = 'hi@there.net'; $order->write(); $this->assertEquals( - array( - array('Cart' => 'Unpaid') - ), + [ + ['Cart' => 'Unpaid'] + ], OrderTest_TestStatusChangeExtension::$stack ); @@ -314,9 +315,9 @@ public function testStatusChange() $order->write(); $this->assertEquals( - array( - array('Unpaid' => 'Paid') - ), + [ + ['Unpaid' => 'Paid'] + ], OrderTest_TestStatusChangeExtension::$stack ); diff --git a/tests/php/Model/OrderTest_TestStatusChangeExtension.php b/tests/php/Model/OrderTest_TestStatusChangeExtension.php index 13dd8dd5e..abe718867 100644 --- a/tests/php/Model/OrderTest_TestStatusChangeExtension.php +++ b/tests/php/Model/OrderTest_TestStatusChangeExtension.php @@ -7,17 +7,17 @@ class OrderTest_TestStatusChangeExtension extends DataExtension implements TestOnly { - public static $stack = array(); + public static $stack = []; public static function reset() { - self::$stack = array(); + self::$stack = []; } public function onStatusChange($fromStatus, $toStatus) { - self::$stack[] = array( + self::$stack[] = [ $fromStatus => $toStatus - ); + ]; } } diff --git a/tests/php/Model/Product/CustomProduct.php b/tests/php/Model/Product/CustomProduct.php index c6d91fb39..bd1c9b7d4 100644 --- a/tests/php/Model/Product/CustomProduct.php +++ b/tests/php/Model/Product/CustomProduct.php @@ -12,15 +12,15 @@ */ class CustomProduct extends DataObject implements Buyable, TestOnly { - private static $db = array( + private static $db = [ 'Title' => 'Varchar', 'Price' => 'Currency', - ); + ]; private static $order_item = CustomProduct_OrderItem::class; private static $table_name = 'SilverShop_Test_CustomProduct'; - public function createItem($quantity = 1, $filter = array()) + public function createItem($quantity = 1, $filter = []) { $itemclass = self::config()->order_item; $item = new $itemclass(); diff --git a/tests/php/Model/Product/CustomProductTest.php b/tests/php/Model/Product/CustomProductTest.php index 9fcb9e050..44df59223 100644 --- a/tests/php/Model/Product/CustomProductTest.php +++ b/tests/php/Model/Product/CustomProductTest.php @@ -18,7 +18,7 @@ class CustomProductTest extends FunctionalTest CustomProduct_OrderItem::class, ]; - public function setUp() + public function setUp(): void { parent::setUp(); // clear session @@ -37,7 +37,7 @@ public function testCustomProduct() $cart = ShoppingCart::singleton(); - $options1 = array('Color' => 'Green', 'Size' => 5, 'Premium' => true); + $options1 = ['Color' => 'Green', 'Size' => 5, 'Premium' => true]; $this->assertTrue((bool)$cart->add($thing, 1, $options1), "add to customisation 1 to cart"); $item = $cart->get($thing, $options1); @@ -53,13 +53,13 @@ public function testCustomProduct() $this->assertFalse((bool)$cart->get($thing), "try to get a non-customised product"); - $options2 = array('Color' => 'Blue', 'Size' => 6, 'Premium' => false); + $options2 = ['Color' => 'Blue', 'Size' => 6, 'Premium' => false]; $this->assertTrue((bool)$cart->add($thing, 5, $options2), "add customisation 2 to cart"); $item = $cart->get($thing, $options2); $this->assertTrue((bool)$item, "item with customisation 2 exists"); $this->assertEquals(5, $item->Quantity); - $options3 = array('Color' => 'Blue'); + $options3 = ['Color' => 'Blue']; $this->assertTrue((bool)$cart->add($thing, 1, $options3), "add a sub-variant of customisation 2"); $item = $cart->get($thing, $options3); @@ -79,7 +79,7 @@ public function testCustomProduct() $cart->clear(); //set quantity - $options4 = array('Size' => 12, 'Color' => 'Blue', 'Premium' => false); + $options4 = ['Size' => 12, 'Color' => 'Blue', 'Premium' => false]; $resp = $cart->setQuantity($thing, 5, $options4); $item = $cart->get($thing, $options4); diff --git a/tests/php/Model/Product/CustomProduct_OrderItem.php b/tests/php/Model/Product/CustomProduct_OrderItem.php index 8c9e3e0a5..750568ce1 100644 --- a/tests/php/Model/Product/CustomProduct_OrderItem.php +++ b/tests/php/Model/Product/CustomProduct_OrderItem.php @@ -8,26 +8,26 @@ class CustomProduct_OrderItem extends OrderItem implements TestOnly { - private static $db = array( + private static $db = [ 'Color' => "Enum('Red,Green,Blue','Red')", 'Size' => 'Int', 'Premium' => 'Boolean', - ); - private static $defaults = array( + ]; + private static $defaults = [ 'Color' => 'Red', 'Premium' => false, - ); - private static $has_one = array( + ]; + private static $has_one = [ 'CustomProduct' => CustomProduct::class, 'Recipient' => Member::class, - ); + ]; private static $buyable_relationship = "CustomProduct"; - private static $required_fields = array( + private static $required_fields = [ 'Color', 'Size', 'Premium', 'Recipient', - ); + ]; private static $table_name = 'SilverShop_Test_CustomProduct_OrderItem'; public function UnitPrice() diff --git a/tests/php/Model/Product/ProductOrderItemTest.php b/tests/php/Model/Product/ProductOrderItemTest.php index 17cca3b8c..d95efb32a 100644 --- a/tests/php/Model/Product/ProductOrderItemTest.php +++ b/tests/php/Model/Product/ProductOrderItemTest.php @@ -17,7 +17,7 @@ class ProductOrderItemTest extends FunctionalTest { public static $fixture_file = __DIR__ . '/../../Fixtures/shop.yml'; public static $disable_theme = true; - public static $orig = array(); + public static $orig = []; /** * @var Product @@ -42,7 +42,7 @@ class ProductOrderItemTest extends FunctionalTest /** * Create and publish some products. */ - public function setUp() + public function setUp(): void { parent::setUp(); ShoppingCart::singleton()->clear(); diff --git a/tests/php/Model/Variation/VariationTest.php b/tests/php/Model/Variation/VariationTest.php index 349dcd971..de051a924 100644 --- a/tests/php/Model/Variation/VariationTest.php +++ b/tests/php/Model/Variation/VariationTest.php @@ -39,7 +39,7 @@ class VariationTest extends SapphireTest */ protected $redlarge; - public function setUp() + public function setUp(): void { parent::setUp(); ShoppingCart::singleton()->clear(); @@ -73,12 +73,12 @@ public function testGetVariation() { $colorred = $this->objFromFixture(AttributeValue::class, "color_red"); $sizelarge = $this->objFromFixture(AttributeValue::class, "size_large"); - $attributes = array($colorred->ID, $sizelarge->ID); + $attributes = [$colorred->ID, $sizelarge->ID]; $variation = $this->ball->getVariationByAttributes($attributes); $this->assertInstanceOf(Variation::class, $variation, "Variation exists"); $this->assertEquals(22, $variation->sellingPrice(), "Variation price is $22 (price of ball"); - $attributes = array($colorred->ID, 999); + $attributes = [$colorred->ID, 999]; $variation = $this->ball->getVariationByAttributes($attributes); $this->assertNull($variation, "Variation does not exist"); } @@ -86,21 +86,21 @@ public function testGetVariation() public function testGenerateVariations() { $color = $this->objFromFixture(AttributeType::class, "color"); - $values = array('Black', 'Blue'); //Note: black doesn't exist in the yaml + $values = ['Black', 'Blue']; //Note: black doesn't exist in the yaml $this->mp3player->generateVariationsFromAttributes($color, $values); $capacity = $this->objFromFixture(AttributeType::class, "capacity"); - $values = array("120GB", "300GB"); //Note: 300GB doesn't exist in the yaml + $values = ["120GB", "300GB"]; //Note: 300GB doesn't exist in the yaml $this->mp3player->generateVariationsFromAttributes($capacity, $values); $variations = $this->mp3player->Variations(); $this->assertEquals($variations->Count(), 4, "four variations created"); $titles = $variations->map('ID', 'Title')->toArray(); - $this->assertContains('Color:Black, Capacity:120GB', $titles); - $this->assertContains('Color:Black, Capacity:300GB', $titles); - $this->assertContains('Color:Blue, Capacity:120GB', $titles); - $this->assertContains('Color:Blue, Capacity:300GB', $titles); + $this->assertStringContainsString('Color:Black, Capacity:120GB', $titles[5]); + $this->assertStringContainsString('Color:Black, Capacity:300GB', $titles[6]); + $this->assertStringContainsString('Color:Blue, Capacity:120GB', $titles[7]); + $this->assertStringContainsString('Color:Blue, Capacity:300GB', $titles[8]); } public function testPriceRange() diff --git a/tests/php/Model/Variation/VariationVersionTest.php b/tests/php/Model/Variation/VariationVersionTest.php index 07a4147df..2228c26db 100644 --- a/tests/php/Model/Variation/VariationVersionTest.php +++ b/tests/php/Model/Variation/VariationVersionTest.php @@ -36,7 +36,7 @@ class VariationVersionTest extends SapphireTest */ protected $redlarge; - public function setUp() + public function setUp(): void { parent::setUp(); $this->ball = $this->objFromFixture(Product::class, "ball"); @@ -47,7 +47,7 @@ public function setUp() public function testVariationsPersistOnUnpublish() { $color = $this->objFromFixture(AttributeType::class, "color"); - $values = array('Black', 'Blue'); + $values = ['Black', 'Blue']; $this->mp3player->generateVariationsFromAttributes($color, $values); $this->mp3player->publishSingle(); diff --git a/tests/php/ORM/Filters/MatchObjectFilterTest.php b/tests/php/ORM/Filters/MatchObjectFilterTest.php index 5c3b92c9d..e4bc32621 100644 --- a/tests/php/ORM/Filters/MatchObjectFilterTest.php +++ b/tests/php/ORM/Filters/MatchObjectFilterTest.php @@ -11,25 +11,25 @@ class MatchObjectFilterTest extends SapphireTest public function testRelationId() { // Tests that an ID is automatically added to any relation fields in the DataObject's has_one. - $filter = new MatchObjectFilter(OrderItem::class, array('ProductID' => 5), array('ProductID')); - $this->assertEquals($filter->getFilter(), array('"ProductID" = \'5\''), 'ID was added to filter'); + $filter = new MatchObjectFilter(OrderItem::class, ['ProductID' => 5], ['ProductID']); + $this->assertEquals($filter->getFilter(), ['"ProductID" = \'5\''], 'ID was added to filter'); } public function testMissingValues() { // Tests that missing values are included in the filter as IS NULL or = 0 // Missing value for a has_one relationship field. - $filter = new MatchObjectFilter(OrderItem::class, array(), array('ProductID')); + $filter = new MatchObjectFilter(OrderItem::class, [], ['ProductID']); $this->assertEquals( $filter->getFilter(), - array('"ProductID" IS NULL'), + ['"ProductID" IS NULL'], 'missing ID value became IS NULL' ); // Missing value for a db field. - $filter = new MatchObjectFilter(OrderItem::class, array(), array('ProductVersion')); + $filter = new MatchObjectFilter(OrderItem::class, [], ['ProductVersion']); $this->assertEquals( $filter->getFilter(), - array('"ProductVersion" IS NULL'), + ['"ProductVersion" IS NULL'], 'missing DB value became IS NULL' ); } diff --git a/tests/php/Page/AccountPageTest.php b/tests/php/Page/AccountPageTest.php index 9059760bb..79b4ee642 100644 --- a/tests/php/Page/AccountPageTest.php +++ b/tests/php/Page/AccountPageTest.php @@ -35,7 +35,7 @@ class AccountPageTest extends FunctionalTest */ protected $controller; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -63,10 +63,10 @@ public function testCanViewAccountPage() $this->submitForm( "MemberLoginForm_LoginForm", "action_doLogin", - array( + [ 'Email' => 'test@example.com', 'Password' => '23u90oijlJKsa', - ) + ] ); $page = $this->get("account/"); // try accessing the account page again @@ -118,7 +118,7 @@ public function testAddressBookWithDropdownFieldToSelectCountry() $this->assertEquals('addressbook', $page->getHeader('X-TestPageAction'), "Account addressbook should open"); // Create an address - $data = array( + $data = [ "Country" => "AU", "Address" => "Sydney Opera House", "AddressLine2" => "Bennelong Point", @@ -126,7 +126,7 @@ public function testAddressBookWithDropdownFieldToSelectCountry() "State" => "NSW", "PostalCode" => "2000", "Phone" => "1234 5678", - ); + ]; $this->submitForm("Form_CreateAddressForm", "action_saveaddress", $data); $this->assertEquals(200, $page->getStatusCode(), "a page should load"); @@ -164,24 +164,24 @@ public function testAddressBookWithReadonlyFieldForCountry() // Open the Address Book page to test form submission with a readonly field $page = $this->get("account/addressbook/"); // goto address book page $this->assertEquals(200, $page->getStatusCode(), "a page should load"); - $this->assertContains( + $this->assertStringContainsString( "Form_CreateAddressForm_Country_readonly", $page->getBody(), "The Country field is readonly" ); - $this->assertNotContains( + $this->assertStringNotContainsString( "", $page->getBody(), "Dropdown field is not shown" ); // Create an address - $data = array( + $data = [ "Address" => "234 Hereford Street", "City" => "Christchurch", "State" => "Canterbury", "PostalCode" => "8011", - ); + ]; $this->submitForm("Form_CreateAddressForm", "action_saveaddress", $data); $this->assertEquals(200, $page->getStatusCode(), "a page should load"); diff --git a/tests/php/Page/CheckoutPageTest.php b/tests/php/Page/CheckoutPageTest.php index 5753db5d8..bbabda319 100644 --- a/tests/php/Page/CheckoutPageTest.php +++ b/tests/php/Page/CheckoutPageTest.php @@ -11,15 +11,15 @@ class CheckoutPageTest extends FunctionalTest { - protected static $fixture_file = array( + protected static $fixture_file = [ __DIR__ . '/../Fixtures/Pages.yml', __DIR__ . '/../Fixtures/shop.yml', - ); + ]; protected static $disable_theme = true; protected static $use_draft_site = true; protected $controller; - public function setUp() + public function setUp(): void { parent::setUp(); ShopTest::setConfiguration(); @@ -34,20 +34,20 @@ public function testActionsForm() //make payment action $this->post( "/checkout/order/ActionsForm", - array( + [ 'OrderID' => $order->ID, 'PaymentMethod' => 'Dummy', 'action_dopayment' => 'submit', - ) + ] ); //cancel action $this->post( "/checkout/order/ActionsForm", - array( + [ 'OrderID' => $order->ID, 'action_docancel' => 'submit', - ) + ] ); $this->markTestIncomplete('Add some assertions'); diff --git a/tests/php/Page/ProductCategoryTest.php b/tests/php/Page/ProductCategoryTest.php index 4e6dbf1b5..35eb013a4 100644 --- a/tests/php/Page/ProductCategoryTest.php +++ b/tests/php/Page/ProductCategoryTest.php @@ -55,7 +55,7 @@ class ProductCategoryTest extends FunctionalTest */ protected $mp3player; - public function setUp() + public function setUp(): void { parent::setUp(); Config::modify()->set(ProductCategory::class, 'must_have_price', false); @@ -85,6 +85,9 @@ public function setUp() Versioned::set_stage('Live'); } + /** + * @doesNotPerformAssertions + */ public function testCanViewProductCategoryPage() { $products = $this->objFromFixture(ProductCategory::class, 'products'); @@ -96,12 +99,12 @@ public function testGetAllProducts() $products = $this->products->ProductsShowable(); $this->assertNotNull($products, "Products exist in category"); $this->assertListEquals( - array( - array('URLSegment' => 'socks'), - array('URLSegment' => 't-shirt'), - array('URLSegment' => 'hdtv'), - array('URLSegment' => 'beach-ball'), - ), + [ + ['URLSegment' => 'socks'], + ['URLSegment' => 't-shirt'], + ['URLSegment' => 'hdtv'], + ['URLSegment' => 'beach-ball'], + ], $products ); } @@ -110,9 +113,9 @@ public function testSecondaryMembership() { $products = $this->electronics->ProductsShowable(); $this->assertListEquals( - array( - array('URLSegment' => 'hdtv'), - ), + [ + ['URLSegment' => 'hdtv'], + ], $products, 'Should initially contain only direct membership products' ); @@ -122,10 +125,10 @@ public function testSecondaryMembership() $products = $this->electronics->ProductsShowable(); $this->assertListEquals( - array( - array('URLSegment' => 'hdtv'), - array('URLSegment' => 'socks'), - ), + [ + ['URLSegment' => 'hdtv'], + ['URLSegment' => 'socks'], + ], $products, 'After adding a category via many-many to socks, that should show up as well' ); @@ -139,11 +142,11 @@ public function testZeroPrice() $this->assertNotNull($products, "Products exist in category"); // hdtv not in the list, since it doesn't have a base-price set $this->assertListEquals( - array( - array('URLSegment' => 'socks'), - array('URLSegment' => 't-shirt'), - array('URLSegment' => 'beach-ball'), - ), + [ + ['URLSegment' => 'socks'], + ['URLSegment' => 't-shirt'], + ['URLSegment' => 'beach-ball'], + ], $products ); @@ -152,10 +155,10 @@ public function testZeroPrice() $products = $this->products->ProductsShowable(); $this->assertListEquals( - array( - array('URLSegment' => 't-shirt'), - array('URLSegment' => 'beach-ball'), - ), + [ + ['URLSegment' => 't-shirt'], + ['URLSegment' => 'beach-ball'], + ], $products ); } @@ -179,9 +182,9 @@ public function testZeroPriceWithVariations() $products = $this->electronics->ProductsShowable(); $this->assertListEquals( - array( - array('URLSegment' => 'hdtv') - ), + [ + ['URLSegment' => 'hdtv'] + ], $products, 'HDTV has a priced extension and should now show up in the list of products' ); diff --git a/tests/php/Page/ProductTest.php b/tests/php/Page/ProductTest.php index cd3c73135..13abb2ff8 100644 --- a/tests/php/Page/ProductTest.php +++ b/tests/php/Page/ProductTest.php @@ -48,7 +48,7 @@ class ProductTest extends FunctionalTest */ protected $pdfbrochure; - function setUp() + public function setUp(): void { parent::setUp(); ShoppingCart::singleton()->clear(); @@ -132,6 +132,9 @@ public function testDiscountRoundingError() Product::remove_extension('ProductTest_FractionalDiscountExtension'); } + /** + * @doesNotPerformAssertions + */ public function testCanViewProductPage() { $this->get(Director::makeRelative($this->tshirt->Link())); @@ -140,19 +143,19 @@ public function testCanViewProductPage() public function testCategories() { - $expectedids = array( + $expectedids = [ $this->objFromFixture(ProductCategory::class, "products")->ID, - ); + ]; $this->assertEquals( array_combine($expectedids, $expectedids), $this->beachball->getCategoryIDs() ); - $expectedids = array( + $expectedids = [ $this->objFromFixture(ProductCategory::class, "products")->ID, $this->objFromFixture(ProductCategory::class, "electronics")->ID, $this->objFromFixture(ProductCategory::class, "musicplayers")->ID, $this->objFromFixture(ProductCategory::class, "clearance")->ID, - ); + ]; $this->assertEquals( array_combine($expectedids, $expectedids), $this->mp3player->getCategoryIDs() diff --git a/tests/php/Reports/ShopReportTest.php b/tests/php/Reports/ShopReportTest.php index 637a1020f..a0d89abde 100644 --- a/tests/php/Reports/ShopReportTest.php +++ b/tests/php/Reports/ShopReportTest.php @@ -12,16 +12,16 @@ class ShopReportTest extends SapphireTest function testSalesReport() { $report = new ShopSalesReport(); - $records = $report->sourceRecords(array()); - $records = $report->sourceRecords(array('Grouping' => 'Year')); - $records = $report->sourceRecords(array('Grouping' => 'Month')); - $records = $report->sourceRecords(array('Grouping' => 'Week')); + $records = $report->sourceRecords([]); + $records = $report->sourceRecords(['Grouping' => 'Year']); + $records = $report->sourceRecords(['Grouping' => 'Month']); + $records = $report->sourceRecords(['Grouping' => 'Week']); $records = $report->sourceRecords( - array( + [ 'Grouping' => 'Day', 'StartPeriod' => 'May 1, 2010', 'EndPeriod' => 'May 16, 2111', - ) + ] ); $record = $records->first(); $this->assertEquals("02 October 2012 - Tuesday", $record->FilterPeriod); diff --git a/tests/php/ShopToolsTest.php b/tests/php/ShopToolsTest.php index 81caaf6b5..e9d63aa9a 100644 --- a/tests/php/ShopToolsTest.php +++ b/tests/php/ShopToolsTest.php @@ -7,7 +7,7 @@ class ShopToolsTest extends SapphireTest { - public function setUp() + public function setUp(): void { parent::setUp(); ShopTest::setConfiguration(); diff --git a/tests/php/Tasks/FakeCartCleanupTask.php b/tests/php/Tasks/FakeCartCleanupTask.php index a2bc8bc74..41755f6b5 100644 --- a/tests/php/Tasks/FakeCartCleanupTask.php +++ b/tests/php/Tasks/FakeCartCleanupTask.php @@ -7,7 +7,7 @@ class FakeCartCleanupTask extends CartCleanupTask implements TestOnly { - public $log = array(); + public $log = []; public function log($msg) { diff --git a/tests/php/test_config.php b/tests/php/test_config.php index 336987099..a9b41a9d4 100644 --- a/tests/php/test_config.php +++ b/tests/php/test_config.php @@ -30,7 +30,7 @@ $cfg = Config::modify(); -$cfg->set(Injector::class, DBDatetime::class, array("class" => I18nDatetime::class)); +$cfg->set(Injector::class, DBDatetime::class, ["class" => I18nDatetime::class]); //remove array configs (these get merged, rater than replaced) @@ -74,10 +74,10 @@ $cfg->set(ProductCategory::class, 'include_child_groups', true); $cfg->set(ProductCategory::class, 'page_length', 10); $cfg->set(ProductCategory::class, 'must_have_price', true); -$cfg->set(ProductCategory::class, 'sort_options', array('Title' => 'Alphabetical', 'Price' => 'Lowest Price')); +$cfg->set(ProductCategory::class, 'sort_options', ['Title' => 'Alphabetical', 'Price' => 'Lowest Price']); // cart, order -$cfg->set(Order::class, 'modifiers', array()); +$cfg->set(Order::class, 'modifiers', []); $cfg->set(Order::class, 'cancel_before_payment', true); $cfg->set(Order::class, 'cancel_before_processing', false); $cfg->set(Order::class, 'cancel_before_sending', false); @@ -92,13 +92,13 @@ $cfg->set( GlobalTax::class, 'country_rates', - array( - "NZ" => array("rate" => 0.15, "name" => "GST", "exclusive" => false), - ) + [ + "NZ" => ["rate" => 0.15, "name" => "GST", "exclusive" => false], + ] ); $cfg->set(Simple::class, 'default_charge', 10); -$cfg->set(Simple::class, 'charges_for_countries', array('US' => 10, 'NZ' => 5)); +$cfg->set(Simple::class, 'charges_for_countries', ['US' => 10, 'NZ' => 5]); // checkout $cfg->set(ShopConfigExtension::class, 'email_from', null);