Initial import: Carteasy Shop (Dev-Stand)

This commit is contained in:
Thomas Bartelt
2026-04-20 01:03:43 +02:00
commit d504f8a05d
3845 changed files with 761050 additions and 0 deletions
+150
View File
@@ -0,0 +1,150 @@
<?php
/**
* JsonStorage
*
* PHP Version 5.3
*
* @category Payment
* @package KlarnaAPI
* @author MS Dev <ms.modules@klarna.com>
* @copyright 2012 Klarna AB (http://klarna.com)
* @license http://opensource.org/licenses/BSD-2-Clause BSD-2
* @link http://integration.klarna.com/
*/
/**
* Include the {@link PCStorage} interface.
*/
require_once 'storage.intf.php';
/**
* JSON storage class for KlarnaPClass
*
* This class is an JSON implementation of the PCStorage interface.
*
* @category Payment
* @package KlarnaAPI
* @author MS Dev <ms.modules@klarna.com>
* @copyright 2012 Klarna AB (http://klarna.com)
* @license http://opensource.org/licenses/BSD-2-Clause BSD-2
* @link http://integration.klarna.com/
*/
class JSONStorage extends PCStorage
{
/**
* return the name of the storage type
*
* @return string
*/
public function getName()
{
return "json";
}
/**
* Checks if the file is writeable, readable or if the directory is.
*
* @param string $jsonFile json file that holds the pclasses
*
* @throws error
* @return void
*/
protected function checkURI($jsonFile)
{
//If file doesn't exist, check the directory.
if (!file_exists($jsonFile)) {
$jsonFile = dirname($jsonFile);
}
if (!is_writable($jsonFile)) {
throw new Klarna_FileNotWritableException($jsonFile);
}
if (!is_readable($jsonFile)) {
throw new Klarna_FileNotReadableException($jsonFile);
}
}
/**
* Clear the pclasses
*
* @param string $uri uri to file to clear
*
* @throws KlarnaException
* @return void
*/
public function clear($uri)
{
$this->checkURI($uri);
unset($this->pclasses);
if (file_exists($uri)) {
unlink($uri);
}
}
/**
* Load pclasses from file
*
* @param string $uri uri to file to load
*
* @throws KlarnaException
* @return void
*/
public function load($uri)
{
$this->checkURI($uri);
if (!file_exists($uri)) {
//Do not fail, if file doesn't exist.
return;
}
$arr = json_decode(file_get_contents($uri), true);
if (count($arr) == 0) {
return;
}
foreach ($arr as $pclasses) {
if (count($pclasses) == 0) {
continue;
}
foreach ($pclasses as $pclass) {
$this->addPClass(new KlarnaPClass($pclass));
}
}
}
/**
* Save pclasses to file
*
* @param string $uri uri to file to save
*
* @throws KlarnaException
* @return void
*/
public function save($uri)
{
try {
$this->checkURI($uri);
$output = array();
foreach ($this->pclasses as $eid => $pclasses) {
foreach ($pclasses as $pclass) {
if (!isset($output[$eid])) {
$output[$eid] = array();
}
$output[$eid][] = $pclass->toArray();
}
}
if (count($this->pclasses) > 0) {
file_put_contents($uri, json_encode($output));
} else {
file_put_contents($uri, "");
}
} catch(Exception $e) {
throw new KlarnaException($e->getMessage());
}
}
}
+335
View File
@@ -0,0 +1,335 @@
<?php
/**
* MySQL Storage
*
* PHP Version 5.3
*
* @category Payment
* @package KlarnaAPI
* @author MS Dev <ms.modules@klarna.com>
* @copyright 2012 Klarna AB (http://klarna.com)
* @license http://opensource.org/licenses/BSD-2-Clause BSD-2
* @link http://integration.klarna.com/
*/
/**
* Include the {@link PCStorage} interface.
*/
require_once 'storage.intf.php';
/**
* MySQL storage class for KlarnaPClass
*
* This class is an MySQL implementation of the PCStorage interface.<br>
* Config field pcURI needs to match format:
* user:passwd@addr:port/dbName.dbTable<br>
* Port can be omitted.<br>
*
* <b>Acceptable characters</b>:<br>
* Username: [A-Za-z0-9_]<br>
* Password: [A-Za-z0-9_]<br>
* Address: [A-Za-z0-9_.]<br>
* Port: [0-9]<br>
* DB name: [A-Za-z0-9_]<br>
* DB table: [A-Za-z0-9_]<br>
*
* To allow for more special characters, and to avoid having<br>
* a regular expression that is too hard to understand, you can<br>
* use an associative array:<br>
* <code>
* array(
* "user" => "myuser",
* "passwd" => "mypass",
* "dsn" => "localhost",
* "db" => "mydatabase",
* "table" => "mytable"
* );
* </code>
*
* @category Payment
* @package KlarnaAPI
* @author MS Dev <ms.modules@klarna.com>
* @copyright 2012 Klarna AB (http://klarna.com)
* @license http://opensource.org/licenses/BSD-2-Clause BSD-2
* @link http://integration.klarna.com/
*/
class MySQLStorage extends PCStorage
{
/**
* Database name.
*
* @var string
*/
protected $dbName;
/**
* Database table.
*
* @var string
*/
protected $dbTable;
/**
* Database address.
*
* @var string
*/
protected $addr;
/**
* Database username.
*
* @var string
*/
protected $user;
/**
* Database password.
*
* @var string
*/
protected $passwd;
/**
* MySQL DB link resource.
*
* @var resource
*/
protected $link;
/**
* return the name of the storage type
*
* @return string
*/
public function getName()
{
return "mysql";
}
/**
* Connects to the DB and checks if DB and table exists.
*
* @throws KlarnaException
* @return void
*/
protected function connect()
{
$this->link = mysql_connect($this->addr, $this->user, $this->passwd);
if ($this->link === false) {
throw new Klarna_DatabaseException(
'Failed to connect to database! ('.mysql_error().')'
);
}
if (!mysql_query(
"CREATE DATABASE IF NOT EXISTS `{$this->dbName}`",
$this->link
)
) {
throw new Klarna_DatabaseException(
'Failed to create! ('.mysql_error().')'
);
}
$create = mysql_query(
"CREATE TABLE IF NOT EXISTS `{$this->dbName}`.`{$this->dbTable}` (
`eid` int(10) unsigned NOT NULL,
`id` int(10) unsigned NOT NULL,
`type` tinyint(4) NOT NULL,
`description` varchar(255) NOT NULL,
`months` int(11) NOT NULL,
`interestrate` decimal(11,2) NOT NULL,
`invoicefee` decimal(11,2) NOT NULL,
`startfee` decimal(11,2) NOT NULL,
`minamount` decimal(11,2) NOT NULL,
`country` int(11) NOT NULL,
`expire` int(11) NOT NULL,
KEY `id` (`id`)
)", $this->link
);
if (!$create) {
throw new Klarna_DatabaseException(
'Table not existing, failed to create! ('.mysql_error().')'
);
}
}
/**
* Splits the URI in format: user:passwd@addr/dbName.dbTable<br>
*
* To allow for more special characters, and to avoid having<br>
* a regular expression that is too hard to understand, you can<br>
* use an associative array:<br>
* <code>
* array(
* "user" => "myuser",
* "passwd" => "mypass",
* "dsn" => "localhost",
* "db" => "mydatabase",
* "table" => "mytable"
* );
* </code>
*
* @param string|array $uri Specified URI to database and table.
*
* @throws KlarnaException
* @return void
*/
protected function splitURI($uri)
{
if (is_array($uri)) {
$this->user = $uri['user'];
$this->passwd = $uri['passwd'];
$this->addr = $uri['dsn'];
$this->dbName = $uri['db'];
$this->dbTable = $uri['table'];
} else if (preg_match(
'/^([\w-]+):([\w-]+)@([\w\.-]+|[\w\.-]+:[\d]+)\/([\w-]+).([\w-]+)$/',
$uri,
$arr
) === 1
) {
/*
[0] => user:passwd@addr/dbName.dbTable
[1] => user
[2] => passwd
[3] => addr
[4] => dbName
[5] => dbTable
*/
if (count($arr) != 6) {
throw new Klarna_DatabaseException(
'URI is invalid! Missing field or invalid characters used!'
);
}
$this->user = $arr[1];
$this->passwd = $arr[2];
$this->addr = $arr[3];
$this->dbName = $arr[4];
$this->dbTable = $arr[5];
} else {
throw new Klarna_DatabaseException(
'URI to MySQL is not valid! ( user:passwd@addr/dbName.dbTable )'
);
}
}
/**
* Load pclasses
*
* @param string $uri pclass uri
*
* @throws KlarnaException
* @return void
*/
public function load($uri)
{
$this->splitURI($uri);
$this->connect();
$result = mysql_query(
"SELECT * FROM `{$this->dbName}`.`{$this->dbTable}`",
$this->link
);
if ($result === false) {
throw new Klarna_DatabaseException(
'SELECT query failed! ('.mysql_error().')'
);
}
while ($row = mysql_fetch_assoc($result)) {
$this->addPClass(new KlarnaPClass($row));
}
}
/**
* Save pclasses to database
*
* @param string $uri pclass uri
*
* @throws KlarnaException
* @return void
*/
public function save($uri)
{
$this->splitURI($uri);
$this->connect();
if (!is_array($this->pclasses) || count($this->pclasses) == 0) {
return;
}
foreach ($this->pclasses as $pclasses) {
foreach ($pclasses as $pclass) {
//Remove the pclass if it exists.
mysql_query(
"DELETE FROM `{$this->dbName}`.`{$this->dbTable}`
WHERE `id` = '{$pclass->getId()}'
AND `eid` = '{$pclass->getEid()}'"
);
//Insert it again.
$result = mysql_query(
"INSERT INTO `{$this->dbName}`.`{$this->dbTable}`
(`eid`,
`id`,
`type`,
`description`,
`months`,
`interestrate`,
`invoicefee`,
`startfee`,
`minamount`,
`country`,
`expire`
)
VALUES
('{$pclass->getEid()}',
'{$pclass->getId()}',
'{$pclass->getType()}',
'{$pclass->getDescription()}',
'{$pclass->getMonths()}',
'{$pclass->getInterestRate()}',
'{$pclass->getInvoiceFee()}',
'{$pclass->getStartFee()}',
'{$pclass->getMinAmount()}',
'{$pclass->getCountry()}',
'{$pclass->getExpire()}')", $this->link
);
if ($result === false) {
throw new Klarna_DatabaseException(
'INSERT INTO query failed! ('.mysql_error().')'
);
}
}
}
}
/**
* Clear the pclasses
*
* @param string $uri pclass uri
*
* @throws KlarnaException
* @return void
*/
public function clear($uri)
{
try {
$this->splitURI($uri);
unset($this->pclasses);
$this->connect();
mysql_query(
"DELETE FROM `{$this->dbName}`.`{$this->dbTable}`",
$this->link
);
} catch(Exception $e) {
throw new Klarna_DatabaseException(
$e->getMessage(), $e->getCode()
);
}
}
}
+473
View File
@@ -0,0 +1,473 @@
<?php
/**
* SQL Storage
*
* PHP Version 5.3
*
* @category Payment
* @package KlarnaAPI
* @author MS Dev <ms.modules@klarna.com>
* @copyright 2012 Klarna AB (http://klarna.com)
* @license http://opensource.org/licenses/BSD-2-Clause BSD-2
* @link http://integration.klarna.com/
*/
/**
* Include the {@link PCStorage} interface.
*/
require_once 'storage.intf.php';
/**
* SQL storage class for KlarnaPClass
*
* This class is an MySQL implementation of the PCStorage interface.<br>
* Config field pcURI needs to match format:
* user:passwd@addr:port/dbName.dbTable<br>
* Port can be omitted.<br>
*
* <b>Acceptable characters</b>:<br>
* Username: [A-Za-z0-9_]<br>
* Password: [A-Za-z0-9_]<br>
* Address: [A-Za-z0-9_.]<br>
* Port: [0-9]<br>
* DB name: [A-Za-z0-9_]<br>
* DB table: [A-Za-z0-9_]<br>
*
* To allow for more special characters, and to avoid having<br>
* a regular expression that is too hard to understand, you can<br>
* use an associative array:<br>
* <code>
* array(
* "user" => "myuser",
* "passwd" => "mypass",
* "dsn" => "localhost",
* "db" => "mydatabase",
* "table" => "mytable"
* );
* </code>
*
* @category Payment
* @package KlarnaAPI
* @author MS Dev <ms.modules@klarna.com>
* @copyright 2012 Klarna AB (http://klarna.com)
* @license http://opensource.org/licenses/BSD-2-Clause BSD-2
* @link http://integration.klarna.com/
*/
class SQLStorage extends PCStorage
{
/**
* Database name.
*
* @var string
*/
protected $dbName;
/**
* Database table.
*
* @var string
*/
protected $dbTable;
/**
* Database address.
*
* @var string
*/
protected $addr;
/**
* PDO DSN notation.
*
* @var string
*/
protected $dsn;
/**
* Database username.
*
* @var string
*/
protected $user;
/**
* Database password.
*
* @var string
*/
protected $passwd;
/**
* PDO DB link resource.
*
* @var PDO
*/
protected $pdo;
/**
* return the name of the storage type
*
* @return string
*/
public function getName()
{
return "sql";
}
/**
* Splits the URI for the following formats:<br>
* user:passwd@addr/dbName.dbTable (assumes MySQL)<br>
* user:password@pdo:dsn/dbName.dbTable<br>
*
* To allow for more special characters, and to avoid having<br>
* a regular expression that is too hard to understand, you can<br>
* use an associative array:<br>
* <code>
* array(
* "user" => "myuser",
* "passwd" => "mypass",
* "dsn" => "localhost",
* "db" => "mydatabase",
* "table" => "mytable"
* );
* </code>
*
* @param string|array $uri Specified URI to database and table.
*
* @throws KlarnaException
* @return void
*/
protected function splitURI($uri)
{
/* If you want to have some characters that would make the
regexp too complex, you can use an array as input instead. */
if (is_array($uri)) {
$this->user = $uri['user'];
$this->passwd = $uri['passwd'];
$this->dsn = $uri['dsn'];
$this->dbName = $uri['db'];
$this->dbTable = $uri['table'];
return array(
$uri,
$this->user,
$this->passwd,
$this->dsn,
$this->dbName,
$this->dbTable
);
}
$pdo_rex
= '/^([\w-]+):([\w-]+)@pdo:([\w.,:;\/ \\\t=\(\){}\*-]+)\/([\w-]+)'.
'.([\w-]+)$/';
$pcuri_rex
= '/^([\w-]+):([\w-]+)@([\w\.-]+|[\w\.-]+:[\d]+|[\w\.-]+:'.
'[\w\.\/-]+|:[\w\.\/-]+)\/([\w-]+).([\w-]+)$/';
$arr = null;
if (preg_match($pdo_rex, $uri, $arr) === 1) {
/*
* [0] => user:password@pdo:dsn/dbName.dbTable
* [1] => user
* [2] => passwd
* [3] => dsn
* [4] => dbName
* [5] => dbTable
*/
if (count($arr) != 6) {
throw new Klarna_DatabaseException(
'URI is invalid! Missing field or invalid characters used!'
);
}
$this->user = $arr[1];
$this->passwd = $arr[2];
$this->dsn = $arr[3];
$this->dbName = $arr[4];
$this->dbTable = $arr[5];
} else if (preg_match($pcuri_rex, $uri, $arr) === 1) {
//user:pass@127.0.0.1:3306/dbName.dbTable
//user:pass@localhost:/tmp/mysql.sock/dbName.dbTable
/*
* [0] => user:passwd@addr/dbName.dbTable
* [1] => user
* [2] => passwd
* [3] => addr
* [4] => dbName
* [5] => dbTable
*/
if (count($arr) != 6) {
throw new Klarna_DatabaseException(
'URI is invalid! Missing field or invalid characters used!'
);
}
$this->user = $arr[1];
$this->passwd = $arr[2];
$this->addr = $arr[3];
$this->port = 3306;
if (preg_match(
'/^([0-9.]+(:([0-9]+))?)$/', $this->addr, $tmp
) === 1
) {
if (isset($tmp[3])) {
$this->port = $tmp[3];
}
}
$this->dbName = $arr[4];
$this->dbTable = $arr[5];
$this->dsn = "mysql:host={$this->addr};port={$this->port};";
} else {
throw new Klarna_DatabaseException(
'URI to SQL is not valid! ( user:passwd@addr/dbName.dbTable )'
);
}
return $arr;
}
/**
* Grabs the PDO connection to the database, specified by the URI.
*
* @param string $uri pclass uri
*
* @return void
* @throws KlarnaException
*/
protected function getConnection($uri)
{
if ($this->pdo) {
return; //Already have a connection
}
$this->splitURI($uri);
try {
$this->pdo = new PDO($this->dsn, $this->user, $this->passwd);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
throw new Klarna_DatabaseException('Failed to connect to database!');
}
}
/**
* Initializes the DB, if the database or table is missing.
*
* @return void
* @throws KlarnaException
*/
protected function initDB()
{
try {
$this->pdo->exec("CREATE DATABASE `{$this->dbName}`");
} catch (PDOException $e) {
//SQLite does not support this...
//throw new KlarnaException(
// 'Database non-existant, failed to create it!'
//);
}
$sql = <<<SQL
CREATE TABLE IF NOT EXISTS `{$this->dbName}`.`{$this->dbTable}` (
`eid` int(10) NOT NULL,
`id` int(10) NOT NULL,
`type` int(4) NOT NULL,
`description` varchar(255) NOT NULL,
`months` int(11) NOT NULL,
`interestrate` decimal(11,2) NOT NULL,
`invoicefee` decimal(11,2) NOT NULL,
`startfee` decimal(11,2) NOT NULL,
`minamount` decimal(11,2) NOT NULL,
`country` int(11) NOT NULL,
`expire` int(11) NOT NULL
);
SQL;
try {
$this->pdo->exec($sql);
} catch (PDOException $e) {
throw new Klarna_DatabaseException(
'Table non-existant, failed to create it!'
);
}
}
/**
* Connects to the DB and checks if DB and table exists.
*
* @param string|array $uri pclass uri
*
* @throws KlarnaException
* @return void
*/
protected function connect($uri)
{
$this->getConnection($uri);
$this->initDB();
}
/**
* Loads the PClasses.
*
* @param string|array $uri pclass uri
*
* @return void
* @throws KlarnaException
*/
public function load($uri)
{
$this->connect($uri);
$this->loadPClasses();
}
/**
* Loads the PClasses.
*
* @return void
* @throws KlarnaException
*/
protected function loadPClasses()
{
try {
$sth = $this->pdo->prepare(
"SELECT * FROM `{$this->dbName}`.`{$this->dbTable}`",
array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)
);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) {
$this->addPClass(new KlarnaPClass($row));
}
$sth->closeCursor();
$sth = null;
} catch (PDOException $e) {
throw new Klarna_DatabaseException(
'Could not fetch PClasses from database!'
);
}
}
/**
* Saves the PClasses.
*
* @param string|array $uri pclass uri
*
* @return void
* @throws KlarnaException
*/
public function save($uri)
{
$this->connect($uri);
//Only attempt to savePClasses if there are any.
if (!is_array($this->pclasses)) {
return;
}
if (count($this->pclasses) == 0) {
return;
}
$this->savePClasses();
}
/**
* Saves the PClasses.
*
* @return void
* @throws KlarnaException
*/
protected function savePClasses()
{
//Insert PClass SQL statement.
$sql = <<<SQL
INSERT INTO `{$this->dbName}`.`{$this->dbTable}`
(`eid`, `id`, `type`, `description`, `months`, `interestrate`,
`invoicefee`, `startfee`, `minamount`, `country`, `expire`)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
SQL;
foreach ($this->pclasses as $pclasses) {
foreach ($pclasses as $pclass) {
try {
//Remove the pclass if it exists.
$sth = $this->pdo->prepare(
"DELETE FROM `{$this->dbName}`.`{$this->dbTable}`
WHERE `id` = ? AND `eid` = ?"
);
$sth->execute(
array(
$pclass->getId(), $pclass->getEid()
)
);
$sth->closeCursor();
$sth = null;
} catch(PDOException $e) {
//Fail silently, we don't care if the removal failed.
}
try {
//Attempt to insert the PClass into the DB.
$sth = $this->pdo->prepare($sql);
$sth->execute(
array(
$pclass->getEid(),
$pclass->getId(),
$pclass->getType(),
$pclass->getDescription(),
$pclass->getMonths(),
$pclass->getInterestRate(),
$pclass->getInvoiceFee(),
$pclass->getStartFee(),
$pclass->getMinAmount(),
$pclass->getCountry(),
$pclass->getExpire()
)
);
$sth->closeCursor();
$sth = null;
} catch(PDOException $e) {
throw new Klarna_DatabaseException(
'Failed to insert PClass into database!'
);
}
}
}
}
/**
* Drops the database table, to clear the PClasses.
*
* @param string|array $uri pclass uri
*
* @return void
* @throws KlarnaException
*/
public function clear($uri)
{
try {
$this->connect($uri);
unset($this->pclasses);
$this->clearTable();
} catch(Exception $e) {
throw new Klarna_DatabaseException(
$e->getMessage(), $e->getCode()
);
}
}
/**
* Drops the database table, to clear the PClasses.
*
* @return void
* @throws KlarnaException
*/
protected function clearTable()
{
try {
$this->pdo->exec("DELETE FROM `{$this->dbName}`.`{$this->dbTable}`");
} catch (PDOException $e) {
throw new Klarna_DatabaseException('Could not clear the database!');
}
}
}
+229
View File
@@ -0,0 +1,229 @@
<?php
/**
* PClass Storage Interface
*
* PHP Version 5.3
*
* @category Payment
* @package KlarnaAPI
* @author MS Dev <ms.modules@klarna.com>
* @copyright 2012 Klarna AB (http://klarna.com)
* @license http://opensource.org/licenses/BSD-2-Clause BSD-2
* @link http://integration.klarna.com/
*/
/**
* KlarnaPClass Storage interface
*
* This class provides an interface with which to save the PClasses easily.
*
* @category Payment
* @package KlarnaAPI
* @author MS Dev <ms.modules@klarna.com>
* @copyright 2012 Klarna AB (http://klarna.com)
* @license http://opensource.org/licenses/BSD-2-Clause BSD-2
* @link http://integration.klarna.com/
*/
abstract class PCStorage
{
/**
* An array of KlarnaPClasses.
*
* @var array
*/
protected $pclasses;
/**
* Thhe name of the implementation.
* The file should be <name>storage.class.php
*
* @return string
*/
abstract public function getName();
/**
* Adds a PClass to the storage.
*
* @param KlarnaPClass $pclass PClass object.
*
* @throws KlarnaException
* @return void
*/
public function addPClass($pclass)
{
if (! $pclass instanceof KlarnaPClass) {
throw new Klarna_InvalidTypeException('pclass', 'KlarnaPClass');
}
if (!isset($this->pclasses) || !is_array($this->pclasses)) {
$this->pclasses = array();
}
if ($pclass->getDescription() === null || $pclass->getType() === null) {
//Something went wrong, do not save these!
return;
}
if (!isset($this->pclasses[$pclass->getEid()])) {
$this->pclasses[$pclass->getEid()] = array();
}
$this->pclasses[$pclass->getEid()][$pclass->getId()] = $pclass;
}
/**
* Gets the PClass by ID.
*
* @param int $id PClass ID.
* @param int $eid Merchant ID.
* @param int $country {@link KlarnaCountry Country} constant.
*
* @throws KlarnaException
* @return KlarnaPClass
*/
public function getPClass($id, $eid, $country)
{
if (!is_int($id)) {
throw new InvalidArgumentException('Supplied ID is not an integer!');
}
if (!is_array($this->pclasses)) {
throw new Klarna_PClassException('No match for that eid!');
}
if (!isset($this->pclasses[$eid]) || !is_array($this->pclasses[$eid])) {
throw new Klarna_PClassException('No match for that eid!');
}
if (!isset($this->pclasses[$eid][$id])
|| !$this->pclasses[$eid][$id]->isValid()
) {
throw new Klarna_PClassException('No such pclass available!');
}
if ($this->pclasses[$eid][$id]->getCountry() !== $country) {
throw new Klarna_PClassException(
'You cannot use this pclass with set country!'
);
}
return $this->pclasses[$eid][$id];
}
/**
* Returns an array of KlarnaPClasses, keyed with pclass ID.
* If type is specified, only that type will be returned.
*
* <b>Types available</b>:<br>
* {@link KlarnaPClass::ACCOUNT}<br>
* {@link KlarnaPClass::CAMPAIGN}<br>
* {@link KlarnaPClass::SPECIAL}<br>
* {@link KlarnaPClass::DELAY}<br>
* {@link KlarnaPClass::MOBILE}<br>
*
* @param int $eid Merchant ID.
* @param int $country {@link KlarnaCountry Country} constant.
* @param int $type PClass type identifier.
*
* @throws KlarnaException
* @return array An array of {@link KlarnaPClass PClasses}.
*/
public function getPClasses($eid, $country, $type = null)
{
if (!is_int($country)) {
throw new Klarna_ArgumentNotSetException('country');
}
$tmp = false;
if (!is_array($this->pclasses)) {
return;
}
$tmp = array();
foreach ($this->pclasses as $eid => $pclasses) {
$tmp[$eid] = array();
foreach ($pclasses as $pclass) {
if (!$pclass->isValid()) {
continue; //Pclass invalid, skip it.
}
if ($pclass->getEid() === $eid
&& $pclass->getCountry() === $country
&& ($pclass->getType() === $type || $type === null)
) {
$tmp[$eid][$pclass->getId()] = $pclass;
}
}
}
return $tmp;
}
/**
* Returns a flattened array of all pclasses
*
* @return array
*/
public function getAllPClasses()
{
if (!is_array($this->pclasses)) {
return array();
}
return $this->_flatten(array_values($this->pclasses));
}
/**
* Flatten an array
*
* @param array $array array to flatten
*
* @return array
*/
private function _flatten($array)
{
if (!is_array($array)) {
// nothing to do if it's not an array
return array($array);
}
$result = array();
foreach ($array as $value) {
// explode the sub-array, and add the parts
$result = array_merge($result, $this->_flatten($value));
}
return $result;
}
/**
* Loads the PClasses and calls {@link self::addPClass()} to store them
* in runtime.
* URI can be location to a file, or a db prefixed table.
*
* @param string $uri URI to stored PClasses.
*
* @throws KlarnaException|Exception
* @return void
*/
abstract public function load($uri);
/**
* Takes the internal PClass array and stores it.
* URI can be location to a file, or a db prefixed table.
*
* @param string $uri URI to stored PClasses.
*
* @throws KlarnaException|Exception
* @return void
*/
abstract public function save($uri);
/**
* Removes the internally stored pclasses.
*
* @param string $uri URI to stored PClasses.
*
* @throws KlarnaException|Exception
* @return void
*/
abstract public function clear($uri);
}
+280
View File
@@ -0,0 +1,280 @@
<?php
/**
* XMLStorage
*
* PHP Version 5.3
*
* @category Payment
* @package KlarnaAPI
* @author MS Dev <ms.modules@klarna.com>
* @copyright 2012 Klarna AB (http://klarna.com)
* @license http://opensource.org/licenses/BSD-2-Clause BSD-2
* @link http://integration.klarna.com/
*/
/**
* Include the {@link PCStorage} interface.
*/
require_once 'storage.intf.php';
/**
* XML storage class for KlarnaPClass
*
* This class is an XML implementation of the PCStorage interface.
*
* @category Payment
* @package KlarnaAPI
* @author MS Dev <ms.modules@klarna.com>
* @copyright 2012 Klarna AB (http://klarna.com)
* @license http://opensource.org/licenses/BSD-2-Clause BSD-2
* @link http://integration.klarna.com/
*/
class XMLStorage extends PCStorage
{
/**
* The internal XML document.
*
* @var DOMDocument
*/
protected $dom;
/**
* XML version for the DOM document.
*
* @var string
*/
protected $version = '1.0';
/**
* Encoding for the DOM document.
*
* @var string
*/
protected $encoding = 'ISO-8859-1';
/**
* Class constructor
*/
public function __construct()
{
$this->dom = new DOMDocument($this->version, $this->encoding);
$this->dom->formatOutput = true;
$this->dom->preserveWhiteSpace = false;
}
/**
* return the name of the storage type
*
* @return string
*/
public function getName()
{
return "xml";
}
/**
* Checks if the file is writeable, readable or if the directory is.
*
* @param string $xmlFile URI to XML file.
*
* @throws KlarnaException
* @return void
*/
protected function checkURI($xmlFile)
{
//If file doesn't exist, check the directory.
if (!file_exists($xmlFile)) {
$xmlFile = dirname($xmlFile);
}
if (!is_writable($xmlFile)) {
throw new Klarna_FileNotWritableException($xmlFile);
}
if (!is_readable($xmlFile)) {
throw new Klarna_FileNotReadableException($xmlFile);
}
}
/**
* Load pclasses from file
*
* @param string $uri uri to file to load
*
* @throws KlarnaException
* @return void
*/
public function load($uri)
{
$this->checkURI($uri);
if (!file_exists($uri)) {
//Do not fail, if file doesn't exist.
return;
}
if (!@$this->dom->load($uri)) {
throw new Klarna_XMLParseException($uri);
}
$xpath = new DOMXpath($this->dom);
foreach ($xpath->query('/klarna/estore') as $estore) {
$eid = $estore->getAttribute('id');
foreach ($xpath->query('pclass', $estore) as $node) {
$pclass = new KlarnaPClass();
$pclass->setId(
$node->getAttribute('pid')
);
$pclass->setType(
$node->getAttribute('type')
);
$pclass->setEid($eid);
$pclass->setDescription(
$xpath->query('description', $node)->item(0)->textContent
);
$pclass->setMonths(
$xpath->query('months', $node)->item(0)->textContent
);
$pclass->setStartFee(
$xpath->query('startfee', $node)->item(0)->textContent
);
$pclass->setInvoiceFee(
$xpath->query('invoicefee', $node)->item(0)->textContent
);
$pclass->setInterestRate(
$xpath->query('interestrate', $node)->item(0)->textContent
);
$pclass->setMinAmount(
$xpath->query('minamount', $node)->item(0)->textContent
);
$pclass->setCountry(
$xpath->query('country', $node)->item(0)->textContent
);
$pclass->setExpire(
$xpath->query('expire', $node)->item(0)->textContent
);
$this->addPClass($pclass);
}
}
}
/**
* Creates DOMElement for all fields for specified PClass.
*
* @param KlarnaPClass $pclass pclass object
*
* @return array Array of DOMElements.
*/
protected function createFields($pclass)
{
$fields = array();
//This is to prevent HTMLEntities to be converted to the real character.
$fields[] = $this->dom->createElement('description');
end($fields)->appendChild(
$this->dom->createTextNode($pclass->getDescription())
);
$fields[] = $this->dom->createElement(
'months', $pclass->getMonths()
);
$fields[] = $this->dom->createElement(
'startfee', $pclass->getStartFee()
);
$fields[] = $this->dom->createElement(
'invoicefee', $pclass->getInvoiceFee()
);
$fields[] = $this->dom->createElement(
'interestrate', $pclass->getInterestRate()
);
$fields[] = $this->dom->createElement(
'minamount', $pclass->getMinAmount()
);
$fields[] = $this->dom->createElement(
'country', $pclass->getCountry()
);
$fields[] = $this->dom->createElement(
'expire', $pclass->getExpire()
);
return $fields;
}
/**
* Save pclasses to file
*
* @param string $uri uri to file to save
*
* @throws KlarnaException
* @return void
*/
public function save($uri)
{
$this->checkURI($uri);
//Reset DOMDocument.
if (!$this->dom->loadXML(
"<?xml version='$this->version' encoding='$this->encoding'?"
."><klarna/>"
)
) {
throw new Klarna_XMLParseException($uri);
}
ksort($this->pclasses, SORT_NUMERIC);
$xpath = new DOMXpath($this->dom);
foreach ($this->pclasses as $eid => $pclasses) {
$estore = $xpath->query('/klarna/estore[@id="'.$eid.'"]');
if ($estore === false || $estore->length === 0) {
//No estore with matching eid, create it.
$estore = $this->dom->createElement('estore');
$estore->setAttribute('id', $eid);
$this->dom->documentElement->appendChild($estore);
} else {
$estore = $estore->item(0);
}
foreach ($pclasses as $pclass) {
if ($eid != $pclass->getEid()) {
//This should never occur, failsafe.
continue;
}
$pnode = $this->dom->createElement('pclass');
foreach ($this->createFields($pclass) as $field) {
$pnode->appendChild($field);
}
$pnode->setAttribute('pid', $pclass->getId());
$pnode->setAttribute('type', $pclass->getType());
$estore->appendChild($pnode);
}
}
if (!$this->dom->save($uri)) {
throw new KlarnaException('Failed to save XML document!');
}
}
/**
* This uses unlink (delete) to clear the pclasses!
*
* @param string $uri uri to file to clear
*
* @throws KlarnaException
* @return void
*/
public function clear($uri)
{
$this->checkURI($uri);
unset($this->pclasses);
if (file_exists($uri)) {
unlink($uri);
}
}
}