Skip to content

Commit

Permalink
Merge pull request #46 from FosterCommerce/developcraft4
Browse files Browse the repository at this point in the history
Craft 4/Commerce 4 version
  • Loading branch information
peteeveleigh authored Aug 5, 2022
2 parents 8b3bee5 + e296efa commit c2c6a50
Show file tree
Hide file tree
Showing 7 changed files with 159 additions and 76 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## 2.0.1 - 2022-07-19

### Added

- Support for Craft 4/Commerce 4. Note that development for Craft 3 has stopped at 1.3.7.

## 1.3.7 - 2021-12-01

### Fixed
Expand Down
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"description": "A Craft CMS plugin for integrating Craft Commerce with ShipStation",
"homepage": "https://github.com/fostercommerce/shipstation-connect",
"type": "craft-plugin",
"version": "1.3.7",
"version": "2.0.1",
"keywords": ["craft","plugin","shipstation"],
"license": "proprietary",
"support": {
Expand All @@ -23,8 +23,8 @@
}
},
"require": {
"craftcms/cms": "^3.0",
"craftcms/commerce": "^2.0|^3.0"
"craftcms/cms": "^4.0",
"craftcms/commerce": "^4.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^2.13"
Expand Down
98 changes: 80 additions & 18 deletions src/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,42 @@
use Craft;
use craft\events\RegisterUrlRulesEvent;
use craft\web\UrlManager;
use craft\web\Application;
use craft\services\UserPermissions;
use craft\events\RegisterUserPermissionsEvent;
use craft\base\Model;
use yii\base\Event;
use yii\base\Exception;
use fostercommerce\shipstationconnect\web\twig\filters\IsFieldTypeFilter;

class Plugin extends \craft\base\Plugin
{
public $hasCpSettings = true;
public $hasCpSection = true;
public $schemaVersion = '1.0.1';

public function init()
/**
* @var bool $hasCpSettings
*/
public bool $hasCpSettings = true;

/**
* @var bool $hasCpSection
*/
public bool $hasCpSection = true;

/**
* @var string $schemaVersion
*/
public string $schemaVersion = '1.0.1';


/**
* init.
*
* @author Unknown
* @since v0.0.1
* @version v1.0.0 Monday, May 23rd, 2022.
* @access public
* @return void
*/
public function init(): void
{
parent::init();

Expand All @@ -25,6 +48,28 @@ public function init()
]);

Craft::$app->view->registerTwigExtension(new IsFieldTypeFilter());

// Because Shipstation uses a querystring parameter of 'action' in their requests.
// This interferes with Craft's routing system.
// So we intercept the request and rename that parameter to ssaction IF the request is for one of this plugin's controllers
/*
Craft::$app->on(Application::EVENT_INIT, function() {
$request = Craft::$app->request;
if(!$request->isConsoleRequest){
if(in_array('actions', $request->getSegments()) && in_array('shipstationconnect', $request->getSegments())) {
if(array_key_exists('action', $request->getQueryParams())) {
// rename array key to match the action name
$params = $request->getQueryParams();
$params['ssaction'] = $params['action'];
unset($params['action']);
$request->setQueryParams($params);
}
};
}
});
*/

Event::on(
UrlManager::class,
Expand All @@ -34,36 +79,53 @@ function (RegisterUrlRulesEvent $event) {
$event->rules['shipstationconnect/settings/save'] = 'shipstationconnect/settings/save';
}
);


Event::on(
UrlManager::class,
UrlManager::EVENT_REGISTER_SITE_URL_RULES,
function (RegisterUrlRulesEvent $event) {
$event->rules['export'] = 'shipstationconnect/orders/export';
}
);


Event::on(UserPermissions::class, UserPermissions::EVENT_REGISTER_PERMISSIONS, function(RegisterUserPermissionsEvent $event) {
$event->permissions['ShipStation Connect'] = [
'shipstationconnect-processOrders' => ['label' => 'Process Orders'],
];
});
Event::on(
UserPermissions::class,
UserPermissions::EVENT_REGISTER_PERMISSIONS,
function(RegisterUserPermissionsEvent $event) {
$event->permissions[] = [
'heading' => 'ShipStation Connect',
'permissions' => [
'shipstationconnect-processOrders' => [
'label' => 'Process Orders'
],
]
];
}
);
}

protected function beforeInstall(): bool
protected function beforeInstall(): void
{
if (!Craft::$app->plugins->isPluginInstalled('commerce')) {
Craft::error(Craft::t(
'shipstationconnect',
'Failed to install. Craft Commerce is required.'
));
return false;
// return false;
}

if (!Craft::$app->plugins->isPluginEnabled('commerce')) {
Craft::error(Craft::t(
'shipstationconnect',
'Failed to install. Craft Commerce is required.'
));
return false;
// return false;
}

return true;
}

public function getCpNavItem()
public function getCpNavItem(): ?array
{
$item = parent::getCpNavItem();

Expand All @@ -75,12 +137,12 @@ public function getCpNavItem()
return $item;
}

protected function createSettingsModel()
protected function createSettingsModel(): ?Model
{
return new \fostercommerce\shipstationconnect\models\Settings();
}

public function settingsHtml()
public function settingsHtml(): ?string
{
return Craft::$app->getView()->renderTemplate('shipstationconnect/settings', [
'settings' => $this->getSettings()
Expand Down
44 changes: 24 additions & 20 deletions src/controllers/OrdersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@
use craft\commerce\elements\Order;
use craft\db\Query;
use craft\db\Table;
use craft\helpers\App;
use craft\web\Response;
use craft\models\MatrixBlockType;
use yii\web\HttpException;
use yii\base\ErrorException;
use yii\base\Event;
use yii\web\Response as YiiResponse;
use fostercommerce\shipstationconnect\Plugin;
use fostercommerce\shipstationconnect\events\FindOrderEvent;

Expand All @@ -23,12 +26,12 @@ class OrdersController extends Controller
// Disable CSRF validation for the entire controller
public $enableCsrfValidation = false;

protected $allowAnonymous = true;
protected array|int|bool $allowAnonymous = true;

/**
* @inheritDoc
*/
public function init()
public function init(): void
{
// Allow anonymous access only when this plugin is handling basic
// authentication, otherwise require auth so that Craft doesn't let
Expand All @@ -38,8 +41,9 @@ public function init()
if ($isUsingCraftAuth) {
$this->requirePermission('shipstationconnect-processOrders');
}

return parent::init();

parent::init();

}

/**
Expand All @@ -50,7 +54,7 @@ public function init()
* @param array $variables, containing key 'fulfillmentService'
* @throws HttpException for malformed requests
*/
public function actionProcess($store = null, $action = null)
public function actionProcess($store = null, $action = null): null|string|Response|YiiResponse|SimpleXMLElement
{
$request = Craft::$app->request;
try {
Expand All @@ -70,7 +74,7 @@ public function actionProcess($store = null, $action = null)
$this->logException('Error processing action {action}', ['action' => $action], $e);
return $this->asErrorJson($e->getMessage())->setStatusCode(500);
} catch (HttpException $e) {
$action = $action;

if ($action) {
$this->logException('Error processing action {action}', ['action' => $action], $e);
} else {
Expand All @@ -84,7 +88,7 @@ public function actionProcess($store = null, $action = null)
}
}

private function logException($msg, $params = [], $e = null)
private function logException($msg, $params = [], $e = null): void
{
Craft::error(
Craft::t('shipstationconnect', $msg, $params),
Expand All @@ -101,16 +105,16 @@ private function logException($msg, $params = [], $e = null)
*
* @return bool, true if successfully authenticated or false otherwise
*/
protected function authenticate()
protected function authenticate(): bool
{
$plugin = Plugin::getInstance();
if ($plugin->isAuthHandledByCraft()) {
return true;
}

$settings = $plugin->settings;
$expectedUsername = Craft::parseEnv($settings->shipstationUsername);
$expectedPassword = Craft::parseEnv($settings->shipstationPassword);
$expectedUsername = App::parseEnv($settings->shipstationUsername);
$expectedPassword = App::parseEnv($settings->shipstationPassword);

list($username, $password) = Craft::$app->getRequest()->getAuthCredentials();

Expand All @@ -122,7 +126,7 @@ protected function authenticate()
*
* @return SimpleXMLElement Orders XML
*/
protected function getOrders($store = null)
protected function getOrders($store = null): SimpleXMLElement
{
$query = Order::find();

Expand Down Expand Up @@ -160,7 +164,7 @@ protected function getOrders($store = null)
* @param ElementCriteriaModel, a REFERENCE to the criteria instance
* @return Int total number of pages
*/
protected function paginateOrders(&$query)
protected function paginateOrders(&$query): int
{
$pageSize = Plugin::getInstance()->settings->ordersPageSize;
if (!is_numeric($pageSize) || $pageSize < 1) {
Expand All @@ -185,7 +189,7 @@ protected function paginateOrders(&$query)
* @param String $field_name, the name of the field in GET params
* @return String|null the formatted date string
*/
protected function parseDate($field_name)
protected function parseDate($field_name): ?string
{
$request = Craft::$app->getRequest();
if ($date_raw = $request->getParam($field_name)) {
Expand All @@ -201,7 +205,7 @@ protected function parseDate($field_name)
return null;
}

private function getBlockTypeByHandle($fieldId, $handle)
private function getBlockTypeByHandle($fieldId, $handle): ?MatrixBlockType
{
$result = (new Query())
->select([
Expand Down Expand Up @@ -236,7 +240,7 @@ private function getBlockTypeByHandle($fieldId, $handle)
*
* @throws ErrorException if the order fails to save
*/
protected function postShipment()
protected function postShipment(): null|string|Response
{
$order = $this->orderFromParams();

Expand Down Expand Up @@ -296,7 +300,7 @@ protected function postShipment()
}
}

private function validateShippingInformation($info)
private function validateShippingInformation($info): bool
{
// Requires at least one value
foreach ($info as $key => $value) {
Expand All @@ -317,7 +321,7 @@ private function validateShippingInformation($info)
*
* @return array
*/
protected function getShippingInformationFromParams()
protected function getShippingInformationFromParams(): array
{
$request = Craft::$app->getRequest();
return [
Expand All @@ -334,9 +338,9 @@ protected function getShippingInformationFromParams()
* return to ShipStation as part of the getOrders() method above.
*
* @throws HttpException, 404 if not found, 406 if order number is invalid
* @return Commerce_Order
* @return Order
*/
protected function orderFromParams()
protected function orderFromParams(): Order
{
$request = Craft::$app->getRequest();
if ($orderNumber = $request->getParam('order_number')) {
Expand Down Expand Up @@ -365,7 +369,7 @@ protected function orderFromParams()
* @param SimpleXMLElement $xml
* @return null
*/
protected function returnXML(\SimpleXMLElement $xml)
protected function returnXML(\SimpleXMLElement $xml): void
{
header("Content-type: text/xml");
// Output it into a buffer, in case TasksService wants to close the connection prematurely
Expand Down
6 changes: 4 additions & 2 deletions src/controllers/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
use fostercommerce\shipstationconnect\Plugin;
use fostercommerce\shipstationconnect\models\Settings;

use yii\web\Response;

class SettingsController extends Controller
{

public function actionIndex()
public function actionIndex(): Response
{
$plugin = Plugin::getInstance();
return $this->renderTemplate("shipstationconnect/settings/index", [
Expand All @@ -19,7 +21,7 @@ public function actionIndex()
]);
}

public function actionSave()
public function actionSave(): Response
{
$this->requirePostRequest();
$postData = Craft::$app->getRequest()->getBodyParam('settings');
Expand Down
Loading

0 comments on commit c2c6a50

Please sign in to comment.