Skip to content

Commit

Permalink
Merge pull request #29 from ThomasDaSilva/main
Browse files Browse the repository at this point in the history
Fix module Thelia 2.5 + CS Fixer
  • Loading branch information
zawaze committed May 31, 2024
2 parents e58d427 + eed8d20 commit 85cfea5
Show file tree
Hide file tree
Showing 11 changed files with 161 additions and 169 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/Config/config.json
105 changes: 51 additions & 54 deletions CmCIC.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@
namespace CmCIC;

use CmCIC\Model\Config;
use Exception;
use JsonException;
use Propel\Runtime\Connection\ConnectionInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Propel\Runtime\Exception\PropelException;
use RuntimeException;
use Symfony\Component\DependencyInjection\Loader\Configurator\ServicesConfigurator;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Routing\Router;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Translation\Translator;
use Thelia\Log\Tlog;
Expand All @@ -41,32 +43,30 @@

class CmCIC extends AbstractPaymentModule
{
const DOMAIN_NAME = "cmcic";
public const DOMAIN_NAME = "cmcic";

const JSON_CONFIG_PATH = "/Config/config.json";
public const JSON_CONFIG_PATH = "/Config/config.json";

const CMCIC_CGI2_RECEIPT = "version=2\ncdr=%s";
const CMCIC_CGI2_MACOK = "0";
const CMCIC_CGI2_MACNOTOK = "1\n";

protected $config;
public const CMCIC_CGI2_RECEIPT = "version=2\ncdr=%s";
public const CMCIC_CGI2_MACOK = "0";
public const CMCIC_CGI2_MACNOTOK = "1\n";

/**
*
* This method is call on Payment loop.
*
* If you return true, the payment method will de display
* If you return false, the payment method will not be display
* If you return false, the payment method will not be displayed
*
* @return boolean
*/
public function isValidPayment()
public function isValidPayment(): bool
{
$debug = $this->getConfigValue('debug', false);
$debug = self::getConfigValue('debug', false);

if ($debug) {
// Check allowed IPs when in test mode.
$testAllowedIps = $this->getConfigValue('allowed_ips', '');
$testAllowedIps = self::getConfigValue('allowed_ips', '');

$raw_ips = explode("\n", $testAllowedIps);

Expand All @@ -78,7 +78,7 @@ public function isValidPayment()

$client_ip = $this->getRequest()->getClientIp();

$valid = in_array($client_ip, $allowed_client_ips);
$valid = in_array($client_ip, $allowed_client_ips, true);
} else {
$valid = true;
}
Expand All @@ -92,28 +92,26 @@ public function isValidPayment()

/**
* @param ConnectionInterface|null $con
* @throws \Propel\Runtime\Exception\PropelException
* @throws \Exception
* @throws PropelException
* @throws Exception
*/
public function postActivation(ConnectionInterface $con = null): void
{
/* insert the images from image folder if first module activation */
$configFile = __DIR__ . self::JSON_CONFIG_PATH;
$configDistFile = __DIR__ . self::JSON_CONFIG_PATH . '.dist';

if (!file_exists($configFile)) {
if (!copy($configDistFile, $configFile)) {
throw new \Exception(
Translator::getInstance()->trans(
"Can't create file %file%. Please change the rights on the file and/or directory."
)
);
}
if (!file_exists($configFile) && !copy($configDistFile, $configFile)) {
throw new RuntimeException(
Translator::getInstance()->trans(
"Can't create file %file%. Please change the rights on the file and/or directory."
)
);
}

$module = $this->getModuleModel();

if (ModuleImageQuery::create()->filterByModule($module)->count() == 0) {
if (ModuleImageQuery::create()->filterByModule($module)->count() === 0) {
$this->deployImageFolder($module, sprintf('%s/images', __DIR__), $con);
}

Expand All @@ -136,34 +134,34 @@ public function update($currentVersion, $newVersion, ConnectionInterface $con =
try {
$fs->remove(__DIR__ . '/AdminIncludes');
$fs->remove(__DIR__ . 'I18n/AdminIncludes');
} catch (\Exception $ex) {
} catch (Exception $ex) {
Tlog::getInstance()->addWarning("Failed to delete CmCIC module AdminIncludes directory (" . __DIR__ . '/AdminIncludes): ' . $ex->getMessage());
}
}

/**
* @param Order $order
* @return Response|null
* @throws \Exception
* @throws Exception
*/
public function pay(Order $order)
public function pay(Order $order): ?Response
{
$c = Config::read(CmCIC::JSON_CONFIG_PATH);
$c = Config::read(self::JSON_CONFIG_PATH);
$currency = $order->getCurrency()->getCode();

$vars = array(
"version" => $c["CMCIC_VERSION"],
"TPE" => $c["CMCIC_TPE"],
"date" => date("d/m/Y:H:i:s"),
"montant" => (string)round($order->getTotalAmount(), 2) . $currency,
"montant" => round($order->getTotalAmount(), 2) . $currency,
"reference" => $this->harmonise($order->getId(), 'numeric', 12),
"url_retour_ok" => URL::getInstance()->absoluteUrl("/order/placed/".$order->getId()),
"url_retour_err" => URL::getInstance()->absoluteUrl("/cmcic/payfail/" . $order->getId()),
"lgue" => strtoupper($this->getRequest()->getSession()->getLang()->getCode()),
"lgue" => strtoupper($this->getRequest()->getSession()?->getLang()->getCode()),
"contexte_commande" => self::getCommandContext($order),
"societe" => $c["CMCIC_CODESOCIETE"],
"texte-libre" => "0",
"mail" => $this->getRequest()->getSession()->getCustomerUser()->getEmail(),
"mail" => $this->getRequest()->getSession()?->getCustomerUser()?->getEmail(),
"3dsdebrayable" => "0",
"ThreeDSecureChallenge" => "challenge_preferred",
);
Expand All @@ -183,7 +181,7 @@ public function pay(Order $order)
);
}

protected function harmonise($value, $type, $len)
protected function harmonise($value, $type, $len): string
{
switch ($type) {
case 'numeric':
Expand All @@ -209,37 +207,36 @@ protected function harmonise($value, $type, $len)
return $value;
}

public static function getUsableKey($key)
public static function getUsableKey($key): string
{
$hexStrKey = substr($key, 0, 38);
$hexFinal = "" . substr($key, 38, 2) . "00";
$hexFinal = substr($key, 38, 2) . "00";

$cca0 = ord($hexFinal);

if ($cca0 > 70 && $cca0 < 97) {
$hexStrKey .= chr($cca0 - 23) . substr($hexFinal, 1, 1);
$hexStrKey .= chr($cca0 - 23) . $hexFinal[1];
} elseif ($hexFinal[1] === "M") {
$hexStrKey .= $hexFinal[0] . "0";
} else {
if (substr($hexFinal, 1, 1) == "M") {
$hexStrKey .= substr($hexFinal, 0, 1) . "0";
} else {
$hexStrKey .= substr($hexFinal, 0, 2);
}
$hexStrKey .= substr($hexFinal, 0, 2);
}

return pack("H*", $hexStrKey);
}

public static function computeHmac($sData, $key)
public static function computeHmac($sData, $key): string
{
return strtolower(hash_hmac("sha1", $sData, $key));
}

/**
* @param Order $order
* @return string
* @throws \Propel\Runtime\Exception\PropelException
* @throws PropelException
* @throws JsonException
*/
public static function getCommandContext(Order $order)
public static function getCommandContext(Order $order): string
{

$orderAddressId = $order->getInvoiceOrderAddressId();
Expand All @@ -254,17 +251,17 @@ public static function getCommandContext(Order $order)
$commandContext = array("billing" => $billing,
"shipping" => $shipping);

$json = json_encode($commandContext);
$json = json_encode($commandContext, JSON_THROW_ON_ERROR);
$utf8 = utf8_encode($json);
return base64_encode($utf8);
}

/**
* @param OrderAddress $orderAddress
* @return array
* @throws \Propel\Runtime\Exception\PropelException
* @throws PropelException
*/
public static function orderAddressForCbPayment(OrderAddress $orderAddress)
public static function orderAddressForCbPayment(OrderAddress $orderAddress): array
{
$address = array(
"name" => substr($orderAddress->getFirstname() . " " . $orderAddress->getLastname() . " " . $orderAddress->getCompany(), 0, 45),
Expand All @@ -289,8 +286,8 @@ public static function orderAddressForCbPayment(OrderAddress $orderAddress)
}

/*
We should not pass a phone number. This number is optionnal, but if it is provided, it should match the
documented regexp : (^[0-9]{2,20}$), which is not always the case, an may prevent payment !!
We should not pass a phone number. This number is essential, but if it is provided, it should match the
documented regexp : (^[0-9]{2,20}$), which is not always the case, a may prevent payment !!
if (substr($orderAddress->getPhone(),0,1) == "+") {
$address["phone"] = $orderAddress->getPhone();
Expand All @@ -309,13 +306,13 @@ public static function orderAddressForCbPayment(OrderAddress $orderAddress)
* @param $vars
* @return string
*/
public static function getHashable($vars)
public static function getHashable($vars): string
{
// Sort by keys according to ASCII order
ksort($vars);

// Formats the values in the following way : Nom_champ=Valeur_champ
array_walk($vars, function (&$value, $key) {
// Formats the values in the following way: Nom_champ=Valeur_champ
array_walk($vars, static function (&$value, $key) {
$value = "$key=$value";
});

Expand All @@ -330,7 +327,7 @@ public static function configureServices(ServicesConfigurator $servicesConfigura
{
$servicesConfigurator->load(self::getModuleCode() . '\\', __DIR__)
->exclude([THELIA_MODULE_DIR . ucfirst(self::getModuleCode()) . '/I18n/*'])
->autowire(true)
->autoconfigure(true);
->autowire()
->autoconfigure();
}
}
6 changes: 0 additions & 6 deletions Config/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,4 @@
<loop name="cmcic.check.rights" class="CmCIC\Loop\CheckRightsLoop" />
</loops>

<hooks>
<hook id="cmcic.back.hook" class="CmCIC\Hook\HookManager">
<tag name="hook.event_listener" event="module.configuration" type="back" method="onModuleConfigure" />
</hook>
</hooks>

</config>
2 changes: 1 addition & 1 deletion Config/module.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<language>fr_FR</language>
<language>en_US</language>
</languages>
<version>2.0.3</version>
<version>2.0.4</version>
<authors>
<author>
<name>Thelia</name>
Expand Down
21 changes: 0 additions & 21 deletions Config/routing.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,4 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

<route id="cmcic.payfail" path="/cmcic/payfail/{order_id}" methods="get">
<default key="_controller">CmCIC\Controller\CmcicPayResponse::payfail</default>
<requirement key="order_id">\d+</requirement>
</route>

<route id="cmcic.payfail.with.message" path="/cmcic/payfail/{order_id}/{message}" methods="get">
<default key="_controller">CmCIC\Controller\CmcicPayResponse::payfail</default>
<requirement key="order_id">\d+</requirement>
</route>

<route id="cmcic.receive" path="/cmcic/validation" methods="post">
<default key="_controller">CmCIC\Controller\CmcicPayResponse::receiveResponse</default>
</route>

<route id="cmcic.saveconfig" path="/admin/module/cmcic/saveconfig" methods="post">
<default key="_controller">CmCIC\Controller\CmcicSaveConfig::save</default>
</route>

<route id="cmcic.download.log" path="/admin/module/cmcic/log">
<default key="_controller">CmCIC\Controller\CmcicSaveConfig::downloadLog</default>
</route>
</routes>
Loading

0 comments on commit 85cfea5

Please sign in to comment.