You can also import backups from aCar free version. Use Help button below to read more.
';
- }
-
- public function getForm()
- {
- return new AcarForm();
- }
-}
\ No newline at end of file
diff --git a/lib/fuelioimporter/providers/drivvocard.class.php b/lib/fuelioimporter/providers/drivvocard.class.php
deleted file mode 100644
index 53fd34a..0000000
--- a/lib/fuelioimporter/providers/drivvocard.class.php
+++ /dev/null
@@ -1,40 +0,0 @@
-You can drop or upload Drivvo CSV export into this card and we will convert its data to Fuelio\'s format.
Export to CSV is possible in Pro version of the app. We are able to import basic fillups, expenses and service data.
-
See help for info about units. Default units are (0 - km) and (0 - liters)';
- }
-
- public function getForm()
- {
- return new DrivvoForm();
- }
-}
\ No newline at end of file
diff --git a/lib/fuelioimporter/providers/fuellogcard.class.php b/lib/fuelioimporter/providers/fuellogcard.class.php
deleted file mode 100644
index 7a9a2be..0000000
--- a/lib/fuelioimporter/providers/fuellogcard.class.php
+++ /dev/null
@@ -1,39 +0,0 @@
-You can drop or upload Fuel Log\'s CSV export into this card and we will convert its data to Fuelio\'s format.
Find export option in application menu, make sure you set correct fuel type in Fuelio\'s settings.
';
- }
-
- public function getForm()
- {
- return new FuelLogForm();
- }
-}
\ No newline at end of file
diff --git a/lib/fuelioimporter/providers/fuellogform.class.php b/lib/fuelioimporter/providers/fuellogform.class.php
deleted file mode 100644
index d5e4eff..0000000
--- a/lib/fuelioimporter/providers/fuellogform.class.php
+++ /dev/null
@@ -1,19 +0,0 @@
- 1, 'label' => 'Export vehicle #', 'value' => 1));
- }
-
- public function getName()
- {
- return 'fuellog';
- }
-}
\ No newline at end of file
diff --git a/lib/fuelioimporter/providers/motostatcard.class.php b/lib/fuelioimporter/providers/motostatcard.class.php
deleted file mode 100644
index 03419f8..0000000
--- a/lib/fuelioimporter/providers/motostatcard.class.php
+++ /dev/null
@@ -1,34 +0,0 @@
-You can upload your motostat.csv file here and we will convert it into Fuelio\'s CSV format. Just tap this card or drop file onto it.
To export your car data, open Motostat, select your car and click on "Export". Make sure to select both checkboxes!';
- }
-
- public function getForm()
- {
- return null;
- }
-}
\ No newline at end of file
diff --git a/psalm.xml b/psalm.xml
new file mode 100644
index 0000000..aad64c6
--- /dev/null
+++ b/psalm.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/lib/fuelioimporter/ibackupentry.class.php b/src/BackupEntryInterface.php
similarity index 62%
rename from lib/fuelioimporter/ibackupentry.class.php
rename to src/BackupEntryInterface.php
index 7b7b4d8..94e38fe 100644
--- a/lib/fuelioimporter/ibackupentry.class.php
+++ b/src/BackupEntryInterface.php
@@ -1,15 +1,16 @@
You can upload an .abp backup file from your aCar and we will convert it into Fuelio\'s CSV format. Just tap this card, or drop a file onto it.
You can also import backups from aCar free version. Use Help button below to read more.
';
+ }
+
+ public function getForm(): FormInterface
+ {
+ return new AcarForm();
+ }
+}
diff --git a/src/Card/DrivvoCardInterface.php b/src/Card/DrivvoCardInterface.php
new file mode 100644
index 0000000..d11ed40
--- /dev/null
+++ b/src/Card/DrivvoCardInterface.php
@@ -0,0 +1,42 @@
+You can drop or upload Drivvo CSV export into this card and we will convert its data to Fuelio\'s format.
Export to CSV is possible in Pro version of the app. We are able to import basic fillups, expenses and service data.
+
See help for info about units. Default units are (0 - km) and (0 - liters)';
+ }
+
+ public function getForm(): FormInterface
+ {
+ return new DrivvoForm();
+ }
+}
diff --git a/src/Card/FuellogCardInterface.php b/src/Card/FuellogCardInterface.php
new file mode 100644
index 0000000..58c0d56
--- /dev/null
+++ b/src/Card/FuellogCardInterface.php
@@ -0,0 +1,41 @@
+You can drop or upload Fuel Log\'s CSV export into this card and we will convert its data to Fuelio\'s format.
Find export option in application menu, make sure you set correct fuel type in Fuelio\'s settings.
';
+ }
+
+ public function getForm(): FormInterface
+ {
+ return new FuelLogForm();
+ }
+}
\ No newline at end of file
diff --git a/src/Card/MotostatCardInterface.php b/src/Card/MotostatCardInterface.php
new file mode 100644
index 0000000..277c0d8
--- /dev/null
+++ b/src/Card/MotostatCardInterface.php
@@ -0,0 +1,44 @@
+You can upload your motostat.csv file here and we will convert it into Fuelio\'s CSV format. Just tap this card or drop file onto it.
To export your car data, open Motostat, select your car and click on "Export". Make sure to select both checkboxes!';
+ }
+
+ public function getForm(): ?FormInterface
+ {
+ return null;
+ }
+}
diff --git a/lib/fuelioimporter/icard.class.php b/src/CardInterface.php
similarity index 54%
rename from lib/fuelioimporter/icard.class.php
rename to src/CardInterface.php
index 7b4366e..13ed828 100644
--- a/lib/fuelioimporter/icard.class.php
+++ b/src/CardInterface.php
@@ -1,48 +1,47 @@
Array of action menu entries
*/
- public function getActions();
+ public function getActions(): array;
/**
* Returns card menu items
* @return array Array of card menu entries
*/
- public function getMenu();
+ public function getMenu(): array;
/**
* Returns configuration form interface
- * @return IForm|null
*/
- public function getForm();
+ public function getForm(): ?FormInterface;
}
diff --git a/lib/fuelioimporter/converterprovider.class.php b/src/ConverterProvider.php
similarity index 53%
rename from lib/fuelioimporter/converterprovider.class.php
rename to src/ConverterProvider.php
index 169c1bb..231fb14 100644
--- a/lib/fuelioimporter/converterprovider.class.php
+++ b/src/ConverterProvider.php
@@ -1,9 +1,12 @@
Internal storage of found providers */
+ protected array $providers = [];
+ /** @var boolean $classes_loaded Flag for autodetecting available plugins */
+ protected bool $classes_loaded = false;
/**
* Interface implementation for iterating over available plugins
- * @return \ArrayIterator
+ * @return ArrayIterator
*/
- public function getIterator() {
- if (!$this->classes_loaded)
+ public function getIterator(): ArrayIterator
+ {
+ if (!$this->classes_loaded) {
$this->initialize();
+ }
- return new \ArrayIterator($this->providers);
+ return new ArrayIterator($this->providers);
}
/**
* Returns converter by its name
* @param string $name Converter name
- * @return \FuelioImporter\IConverter
- * @throws \FuelioImporter\ProviderNotExistsException
+ * @return ProviderInterface
+ * @throws ProviderNotExistsException
*/
- public function get($name)
+ public function get(string $name): ProviderInterface
{
- if (!$this->classes_loaded)
+ if (!$this->classes_loaded) {
$this->initialize();
- if (isset($this->providers[$name]))
+ }
+ if (isset($this->providers[$name])) {
return $this->providers[$name];
- throw new \FuelioImporter\ProviderNotExistsException();
+ }
+ throw new ProviderNotExistsException();
}
/**
@@ -50,26 +57,29 @@ public function get($name)
* This method reads all files in namespace FuelioImporter\Providers
* classes implementing IConverter interface
*/
- public function initialize() {
- $di = new DirectoryIterator(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'providers');
+ public function initialize(): void
+ {
+ $di = new DirectoryIterator(__DIR__ . DIRECTORY_SEPARATOR . 'Providers');
foreach ($di as $spl_file) {
- if ($spl_file->isFile() && !$spl_file->isDot() && $spl_file->isReadable() && stripos($spl_file->getBasename(), 'provider.class.php') !== false) {
-
+ if ($spl_file->isFile() && !$spl_file->isDot() && $spl_file->isReadable() && strpos($spl_file->getBasename(), 'Provider.php') !== false) {
+
/* We should have a new class, verify and check if it's implementing IConverter
* Autoloader here will do the job searching for valid file
* it should not misbehave as we are using FuelioImporter namespace
*/
- $classname = 'FuelioImporter\\Providers\\' . ucfirst($spl_file->getBasename('.class.php'));
-
- if (!class_exists($classname, true))
- continue;
+ $classname = 'FuelioImporter\\Providers\\' . ucfirst($spl_file->getBasename('.php'));
- if (in_array('FuelioImporter\\IConverter', class_implements($classname, true)))
+ if (!class_exists($classname, true)) {
+ continue;
+ }
+
+ if (is_subclass_of($classname, ProviderInterface::class, true))
{
$instance = new $classname();
- if (isset($this->providers[$instance->getName()]))
- throw new \FuelioImporter\ProviderExistsException();
+ if (isset($this->providers[$instance->getName()])) {
+ throw new ProviderExistsException();
+ }
$this->providers[$instance->getName()] = $instance;
}
@@ -77,5 +87,4 @@ public function initialize() {
}
$this->classes_loaded = true;
}
-
}
diff --git a/lib/fuelioimporter/cost.class.php b/src/Cost.php
similarity index 53%
rename from lib/fuelioimporter/cost.class.php
rename to src/Cost.php
index 488ef52..e9702c8 100644
--- a/lib/fuelioimporter/cost.class.php
+++ b/src/Cost.php
@@ -1,137 +1,142 @@
title = $sTitle;
}
- public function setDate($sDate)
+ public function setDate($sDate): void
{
$dt = new \DateTime($sDate);
$this->date = $dt->format(FuelioBackupBuilder::DATE_FORMAT);
}
- public function setOdo($iOdo)
+ public function setOdo($iOdo): void
{
- $this->odo = intval($iOdo);
+ $this->odo = (int) $iOdo;
}
- public function setCostCategoryId($iId)
+ public function setCostCategoryId($iId): void
{
$this->cost_category_id = $iId;
}
- public function setNotes($sNotes)
+ public function setNotes($sNotes): void
{
$this->notes = $sNotes;
}
- public function setCost($dCost)
+ public function setCost($dCost): void
{
$this->cost = $dCost;
$this->setIsIncome($dCost<0);
}
- public function setFlag($flag)
+ public function setFlag($flag): void
{
$this->flag = $flag;
}
- public function setIdR($iId)
+ public function setIdR($iId): void
{
$this->idR = $iId;
}
- public function setRead($bRead)
+ public function setRead($bRead): void
{
- $this->read = intval(boolval($bRead));
+ $this->read = (int)(bool) $bRead;
}
- public function setReminderOdo($iOdo)
+ public function setReminderOdo($iOdo): void
{
$this->remindOdo = $iOdo;
}
- public function setReminderDate($sDate)
+ public function setReminderDate($sDate): void
{
$dt = new \DateTime($sDate);
$this->remindDate = $dt->format(FuelioBackupBuilder::DATE_FORMAT);
}
- public function setRepeatOdo($iOdo)
+ public function setRepeatOdo($iOdo): void
{
$this->repeat_odo = (int)$iOdo;
}
- public function setRepeatMonths($sMonths)
+ public function setRepeatMonths($sMonths):void
{
$this->repeat_months = (int)$sMonths;
}
- public function setIsIncome($bIsIncome)
+ public function setIsIncome($bIsIncome): void
{
- $this->is_income = (int)(bool)$bIsIncome;
+ $this->is_income = (int) (bool) $bIsIncome;
}
- public function setUniqueId($iUniqueId)
+ public function setUniqueId($iUniqueId): void
{
$this->unique_id = (int)$iUniqueId;
}
- public function getCostDate()
+ public function getCostDate(): string
{
return $this->date;
}
- public function getData() {
+ public function getData(): array
+ {
$vars = get_object_vars($this);
return array_values($vars);
}
-}
\ No newline at end of file
+}
diff --git a/lib/fuelioimporter/costcategory.class.php b/src/CostCategory.php
similarity index 53%
rename from lib/fuelioimporter/costcategory.class.php
rename to src/CostCategory.php
index e393fb4..2dad054 100644
--- a/lib/fuelioimporter/costcategory.class.php
+++ b/src/CostCategory.php
@@ -1,23 +1,25 @@
type_id = $type_id;
$this->name = $name;
@@ -25,22 +27,27 @@ public function __construct($type_id, $name, $priority = 0, $color = '')
$this->color = $color;
}
- public function getTypeId()
+ public function getTypeId(): int
{
return $this->type_id;
}
- public function setTypeId($iId)
+ public function getName(): string
{
- $this->type_id = $iId;
+ return $this->name;
}
-
- public function getName()
+
+ public function getPriority(): int
{
- return $this->name;
+ return $this->priority;
+ }
+
+ public function getColor(): string
+ {
+ return $this->color;
}
- public function getData()
+ public function getData(): array
{
$vars = get_object_vars($this);
return array_values($vars);
diff --git a/lib/fuelioimporter/providers/acarform.class.php b/src/Form/AcarForm.php
similarity index 64%
rename from lib/fuelioimporter/providers/acarform.class.php
rename to src/Form/AcarForm.php
index fd446c2..8ec058c 100644
--- a/lib/fuelioimporter/providers/acarform.class.php
+++ b/src/Form/AcarForm.php
@@ -1,19 +1,20 @@
1, 'label' => 'Export vehicle #', 'value' => 1));
}
- public function getName()
+ public function getName(): string
{
return 'acar';
}
-}
\ No newline at end of file
+}
diff --git a/lib/fuelioimporter/form/baseform.class.php b/src/Form/BaseFormInterface.php
similarity index 70%
rename from lib/fuelioimporter/form/baseform.class.php
rename to src/Form/BaseFormInterface.php
index 9859ead..c68fe9e 100644
--- a/lib/fuelioimporter/form/baseform.class.php
+++ b/src/Form/BaseFormInterface.php
@@ -1,5 +1,7 @@
- public function offsetExists($offset)
+ public function offsetExists($offset): bool
{
if (!is_string($offset)) {
throw new \InvalidArgumentException('Offset name must be of string type.');
@@ -39,18 +41,18 @@ public function offsetExists($offset)
return array_key_exists($offset, $this->fields);
}
- public function offsetGet($offset)
+ public function offsetGet($offset): ?FormFieldInterface
{
return $this->offsetExists($offset) ? $this->fields[$offset] : null;
}
- public function offsetSet($offset, $value)
+ public function offsetSet($offset, $value): void
{
if ($offset !== null && !is_string($offset)) {
throw new \InvalidArgumentException('Offset name must be of string type.');
}
- if (!$value instanceof IFormField) {
+ if (!$value instanceof FormFieldInterface) {
throw new \InvalidArgumentException('Only IFormField instances are allowed.');
}
@@ -62,14 +64,14 @@ public function offsetSet($offset, $value)
$value->setForm($this);
}
- public function offsetUnset($offset)
+ public function offsetUnset($offset): void
{
unset($this->fields[$offset]);
}
- public function getData()
+ public function getData(): ?iterable
{
- $out = array();
+ $out = [];
foreach($this->fields as $name => $field) {
$data = null;
if ($field->isValid()) {
@@ -80,31 +82,31 @@ public function getData()
return $out;
}
- abstract public function getName();
+ abstract public function getName(): string;
- public function isSubmitted()
+ public function isSubmitted(): bool
{
return $this->is_submitted;
}
- public function isValid()
+ public function isValid(): bool
{
return $this->isSubmitted() && empty($this->errors);
}
- public function process($post_data)
+ public function process($post_data): void
{
$this->is_submitted = array_key_exists($this->getName(), $post_data);
if (!$this->is_submitted) {
return;
}
- foreach ($post_data[$this->getName()] as $name=>$value) {
- if (!$this->offsetExists($name)) {
+ foreach ($post_data[$this->getName()] as $name => $value) {
+ $field = $this[$name] ?? null;
+ if (!$field) {
throw new \InvalidArgumentException('Unexpected form field.');
}
- $field = $this->offsetGet($name);
try {
$field->setValue($value);
if (!$field->isValid()) {
@@ -118,14 +120,14 @@ public function process($post_data)
}
}
- public function getIterator()
+ public function getIterator(): \ArrayIterator
{
return new \ArrayIterator($this->fields);
}
- public function getErrors()
+ public function getErrors(): array
{
return $this->errors;
}
//
-}
\ No newline at end of file
+}
diff --git a/lib/fuelioimporter/providers/drivvoform.class.php b/src/Form/DrivvoForm.php
similarity index 66%
rename from lib/fuelioimporter/providers/drivvoform.class.php
rename to src/Form/DrivvoForm.php
index 0dfe69c..aa63763 100644
--- a/lib/fuelioimporter/providers/drivvoform.class.php
+++ b/src/Form/DrivvoForm.php
@@ -1,11 +1,13 @@
array('class' => 'mdl-textfield__input')), $options));
+ parent::__construct(
+ $name,
+ array_merge(
+ [
+ 'attributes' => [
+ 'class' => 'mdl-textfield__input'
+ ]
+ ],
+ $options)
+ );
}
- public function render()
+ public function render(): string
{
return sprintf('
%sInput is not a number!
',
parent::render(),
$this->options['label']
);
}
-}
\ No newline at end of file
+}
diff --git a/lib/fuelioimporter/form/field/numericfield.class.php b/src/Form/Field/NumericFieldInterface.php
similarity index 73%
rename from lib/fuelioimporter/form/field/numericfield.class.php
rename to src/Form/Field/NumericFieldInterface.php
index 99ddc3c..b9ba2cb 100644
--- a/lib/fuelioimporter/form/field/numericfield.class.php
+++ b/src/Form/Field/NumericFieldInterface.php
@@ -1,11 +1,12 @@
label => field label
*
attributes => html attributes
*/
-class NumericField implements IFormField
+class NumericFieldInterface implements FormFieldInterface
{
/**
* @var array Internal field options
*/
- protected $options;
+ protected array $options;
/**
* @var mixed Raw field value as processed by form
@@ -32,25 +33,25 @@ class NumericField implements IFormField
/**
* @var int|null normalized integer
*/
- protected $value = null;
+ protected ?int $value = null;
/**
* @var string Field name
*/
- protected $name;
+ protected string $name;
/**
- * @var IForm Parent form
+ * @var ?FormInterface Parent form
*/
- protected $form;
+ protected ?FormInterface $form = null;
- public function __construct($name, $options = array())
+ public function __construct(?string $name, $options = array())
{
$defaults = array('min' => 1, 'label' => $name, 'attributes' => array());
$this->options = array_merge($defaults, $options);
- if ($name === null || empty((string)$name)) {
+ if (empty($name)) {
throw new \InvalidArgumentException('Field needs a name!');
}
$this->name = $name;
@@ -63,7 +64,7 @@ public function __construct($name, $options = array())
}
//
- public function getName()
+ public function getName(): string
{
return $this->name;
}
@@ -73,9 +74,9 @@ public function getValue()
return $this->value;
}
- public function isValid()
+ public function isValid(): bool
{
- if (!empty($this->value) && !is_numeric($this->value)) {
+ if (!empty($this->value)) {
$val = '';
if (function_exists('mb_strimwidth')) {
$val = mb_strimwidth($val, 0, 20, '…');
@@ -92,19 +93,19 @@ public function isValid()
return true;
}
- public function setForm(IForm $form)
+ public function setForm(FormInterface $form): void
{
$this->form = $form;
}
- public function setValue($value)
+ public function setValue($value): void
{
$this->raw_value = $value;
$this->value = $this->normalizeValue($value);
}
- public function render()
+ public function render(): string
{
return sprintf('',
addcslashes($this->form ? sprintf('%s[%s]', $this->form->getName(), $this->getName()) : $this->getName(), '"'),
@@ -114,15 +115,17 @@ public function render()
}
//
- protected function normalizeValue($value) {
- return intval($value, 10);
+ protected function normalizeValue($value): int
+ {
+ return (int) $value;
}
- protected function getRenderingAttributes($attributes) {
+ protected function getRenderingAttributes($attributes): string
+ {
$vals = array();
- foreach ($attributes as $name=>$value) {
- $vals[] = sprintf('%s="%s"', str_replace(' ', '_', $name), addcslashes($value,'"'));
+ foreach ($attributes as $name => $value) {
+ $vals[] = sprintf('%s="%s"', str_replace(' ', '_', $name), addcslashes((string) $value,'"'));
}
return implode(' ', $vals);
}
-}
\ No newline at end of file
+}
diff --git a/lib/fuelioimporter/form/iformfield.class.php b/src/Form/FormFieldInterface.php
similarity index 67%
rename from lib/fuelioimporter/form/iformfield.class.php
rename to src/Form/FormFieldInterface.php
index 177849d..d98afea 100644
--- a/lib/fuelioimporter/form/iformfield.class.php
+++ b/src/Form/FormFieldInterface.php
@@ -1,5 +1,7 @@
1, 'label' => 'Export vehicle #', 'value' => 1]);
+ }
+
+ public function getName(): string
+ {
+ return 'fuellog';
+ }
+}
diff --git a/lib/fuelioimporter/fuellogentry.class.php b/src/FuelLogEntryInterface.php
similarity index 58%
rename from lib/fuelioimporter/fuellogentry.class.php
rename to src/FuelLogEntryInterface.php
index 4aa5c8b..c2ae76a 100644
--- a/lib/fuelioimporter/fuellogentry.class.php
+++ b/src/FuelLogEntryInterface.php
@@ -1,8 +1,10 @@
data = $dt->format(FuelioBackupBuilder::DATE_FORMAT);
}
- public function setOdo($iOdo) {
+ public function setOdo($iOdo): void
+ {
$this->odo = (int)$iOdo;
}
- public function setFuel($dFuel) {
+ public function setFuel($dFuel): void
+ {
$this->fuel = $dFuel;
}
- public function setFullFillup($bFull) {
+ public function setFullFillup($bFull): void
+ {
// force integer form of forced boolean :)
- $this->full_fillup = (int)(bool)$bFull;
+ $this->full_fillup = (int) (bool) $bFull;
}
- public function setPrice($dPrice) {
+ public function setPrice($dPrice): void
+ {
$this->price = $dPrice;
}
- public function setConsumption($dConsumption) {
+ public function setConsumption($dConsumption): void
+ {
$this->consumption = $dConsumption;
}
- public function setGeoCoords($dLatitude, $dLongitude) {
+ public function setGeoCoords($dLatitude, $dLongitude): void
+ {
$this->latitude = $dLatitude;
$this->longitude = $dLongitude;
@@ -77,33 +86,39 @@ public function setGeoCoords($dLatitude, $dLongitude) {
}
}
- public function setCity($sCity) {
+ public function setCity($sCity): void
+ {
$this->city = $sCity;
}
- public function setNotes($sNotes) {
+ public function setNotes($sNotes): void
+ {
$this->notes = $sNotes;
}
- public function setMissedEntries($iMissed) {
+ public function setMissedEntries($iMissed): void
+ {
$this->missed_entries = $iMissed;
}
- public function setTankNumber($nTankNumber) {
+ public function setTankNumber($nTankNumber): void
+ {
$this->tank_number = (int)$nTankNumber;
}
- public function setFuelType($nFuelType) {
+ public function setFuelType($nFuelType): void
+ {
$this->fuel_type = (int)$nFuelType;
}
- public function setVolumePrice($dVolumePrice) {
+ public function setVolumePrice($dVolumePrice): void
+ {
$this->volume_price = (double)$dVolumePrice;
}
- public function getData() {
+ public function getData(): array
+ {
$vars = get_object_vars($this);
return array_values($vars);
}
-
}
diff --git a/lib/fuelioimporter/FuelType.csv b/src/FuelType.csv
similarity index 100%
rename from lib/fuelioimporter/FuelType.csv
rename to src/FuelType.csv
diff --git a/lib/fuelioimporter/fueltypes.class.php b/src/FuelTypes.php
similarity index 55%
rename from lib/fuelioimporter/fueltypes.class.php
rename to src/FuelTypes.php
index 920d63f..bb256b7 100644
--- a/lib/fuelioimporter/fueltypes.class.php
+++ b/src/FuelTypes.php
@@ -1,32 +1,37 @@
*/
+ protected array $list;
public function __construct()
{
$this->list = array();
}
- public function addType($root, $id, $name, $active)
+ public function addType(?int $root, int $id, string $name, bool $active): void
{
- $root = (int)$root;
- $element = array('name' => trim($name), 'active' => (int)(bool)$active, 'parent' => null);
- if (empty($root) && !empty($name) && !empty($id) && ($root%100 === 0) ) {
- $this->list[(int)$id] = $element;
+ $element = ['name' => trim($name), 'active' => (int) $active, 'parent' => null];
+ if ($root === null && !empty($name) && !empty($id) && ($root%100 === 0) ) {
+ $this->list[$id] = $element;
return;
}
@@ -34,10 +39,11 @@ public function addType($root, $id, $name, $active)
throw new \RuntimeException('Invalid root fuel type id');
}
+ /** @psalm-suppress PossiblyNullArrayOffset */
$element['parent'] = &$this->list[$root];
}
- public function findIdByName($sName)
+ public function findIdByName($sName): int
{
$name = trim($sName);
foreach ($this->list as $id => $element) {
@@ -48,7 +54,7 @@ public function findIdByName($sName)
return -1;
}
- public function findNameById($nId)
+ public function findNameById($nId): ?string
{
if ($this->isValidId($nId)) {
return $this->list[$nId]['name'];
@@ -56,16 +62,17 @@ public function findNameById($nId)
return null;
}
- public function isValidId($nId)
+ public function isValidId($nId): bool
{
return isset($this->list[(int)$nId]);
}
- public function validRootId($nId) {
+ public function validRootId($nId): bool
+ {
return $this->isValidId($nId) && ($nId%100 === 0);
}
- public static function getTypes()
+ public static function getTypes(): FuelTypes
{
$list = new FuelTypes();
@@ -81,7 +88,7 @@ public static function getTypes()
while(!feof($fh)) {
$line = fgetcsv($fh);
$root = trim($line[1]);
- $list->addType($root === '' ? null : $root, $line[0], $line[2], $line[3]);
+ $list->addType($root === '' ? null : (int) $root, (int) $line[0], $line[2], (bool) $line[3]);
}
diff --git a/lib/fuelioimporter/fueliobackupbuilder.class.php b/src/FuelioBackupBuilder.php
similarity index 75%
rename from lib/fuelioimporter/fueliobackupbuilder.class.php
rename to src/FuelioBackupBuilder.php
index 22279c9..ba639ea 100644
--- a/lib/fuelioimporter/fueliobackupbuilder.class.php
+++ b/src/FuelioBackupBuilder.php
@@ -1,7 +1,11 @@
fwrite("## Vehicle,,,,,,,,,,,,,,\n");
$this->fputcsv(array('Name','Description','DistUnit','FuelUnit','ConsumptionUnit','ImportCSVDateFormat', 'VIN', 'Insurance', 'Plate', 'Make', 'Model', 'Year', 'TankCount', 'Tank1Type', 'Tank2Type', 'Active'));
@@ -30,9 +34,8 @@ public function writeVehicleHeader()
/**
* Writes Vehicle data
- * @param \FuelioImporter\Vehicle $vehicle
*/
- public function writeVehicle(Vehicle $vehicle)
+ public function writeVehicle(Vehicle $vehicle): void
{
$this->fputcsv($vehicle->getData());
}
@@ -40,7 +43,7 @@ public function writeVehicle(Vehicle $vehicle)
/**
* Writes fuel log header
*/
- public function writeFuelLogHeader()
+ public function writeFuelLogHeader(): void
{
$this->fwrite("## Log,,,,,,,,,,,,,\n");
$this->fputcsv(array('Data','Odo(km)','Fuel(litres)','Full','Price(optional)','l/100km(optional)','latitude(optional)','longitude(optional)','City(optional)','Notes(optional)','Missed', 'TankNumber', 'FuelType', 'VolumePrice'));
@@ -48,9 +51,8 @@ public function writeFuelLogHeader()
/**
* Writes fuel log entry
- * @param \FuelioImporter\FuelLogEntry $entry
*/
- public function writeFuelLog(FuelLogEntry $entry)
+ public function writeFuelLog(FuelLogEntryInterface $entry): void
{
$this->fputcsv($entry->getData());
}
@@ -58,7 +60,7 @@ public function writeFuelLog(FuelLogEntry $entry)
/**
* Writes cost categories header starting optional costs backup
*/
- public function writeCostCategoriesHeader()
+ public function writeCostCategoriesHeader(): void
{
$this->fwrite("## CostCategories,,,,,,,,,,,\n");
$this->fputcsv(array('CostTypeID', 'Name', 'priority'));
@@ -67,7 +69,7 @@ public function writeCostCategoriesHeader()
/**
* Writes costs header into stream
*/
- public function writeCoststHeader()
+ public function writeCoststHeader(): void
{
$this->fwrite("## Costs,,,,,,,,,,,,,,,\n");
$this->fputcsv(array('CostTitle', 'Date', 'Odo', 'CostTypeID', 'Notes', 'Cost', 'flag', 'idR', 'read', 'RemindOdo', 'RemindDate', 'isTemplate', 'RepeatOdo', 'RepeatMonths', 'isIncome', 'UniqueId'));
@@ -75,18 +77,16 @@ public function writeCoststHeader()
/**
* Writes cost category into stream
- * @param \FuelioImporter\CostCategory $category
*/
- public function writeCostCategory(CostCategory $category)
+ public function writeCostCategory(CostCategory $category): void
{
$this->fputcsv($category->getData());
}
/**
* Writes cost into stream
- * @param \FuelioImporter\Cost $cost
*/
- public function writeCost(Cost $cost)
+ public function writeCost(Cost $cost): void
{
$this->fputcsv($cost->getData());
}
diff --git a/src/InvalidFileFormatException.php b/src/InvalidFileFormatException.php
new file mode 100644
index 0000000..491fd5b
--- /dev/null
+++ b/src/InvalidFileFormatException.php
@@ -0,0 +1,17 @@
+
*/
- public function getErrors();
+ public function getErrors(): array;
/**
* Array of warnings
- * @return array()
+ * @return array
*/
- public function getWarnings();
+ public function getWarnings(): array;
/**
* Method that processes given file returning SplTempFileObject
- * @return FuelioBackupBuilder
+ * @todo Setup form_data type
*/
- public function processFile(SplFileObject $in, $form_data);
+ public function processFile(SplFileObject $in, $form_data): FuelioBackupBuilder;
/**
* Method returns a CardInterface for visual representation
- * @return ICard
*/
- public function getCard();
+ public function getCard(): CardInterface;
/**
* Optional stylesheet to include on page
- * @return string|null
*/
- public function getStylesheetLocation();
+ public function getStylesheetLocation(): ?string;
/**
* Sets car name
*
* @param string $name Car name
*/
- public function setCarName($name);
-}
\ No newline at end of file
+ public function setCarName(string $name): void;
+}
diff --git a/src/ProviderNotExistsException.php b/src/ProviderNotExistsException.php
new file mode 100644
index 0000000..d3324ea
--- /dev/null
+++ b/src/ProviderNotExistsException.php
@@ -0,0 +1,17 @@
+selected_vehicle;
}
// @see IConverter
- public function getStylesheetLocation() {
+ public function getStylesheetLocation(): ?string
+ {
return null;
}
// @see IConverter
- public function setCarName($name) {
+ public function setCarName($name): void
+ {
if (!empty($name)) {
$this->car_name = $name;
}
}
// @see IConverter
- public function processFile(SplFileObject $stream, $form_data) {
+ public function processFile(SplFileObject $in, $form_data): FuelioBackupBuilder {
// We need to verify that we've got valid archive
- $in = new ZipArchive();
+ $zip = new ZipArchive();
$out = new FuelioBackupBuilder();
/** @todo: Provide more detailed Zip-related error handling */
- if ($in->open($stream->getPathname()) !== true)
- throw new \FuelioImporter\InvalidFileFormatException(); // For basics
+ if ($zip->open($in->getPathname()) !== true) {
+ throw new InvalidFileFormatException(); // For basics
+ }
// If no metadata.inf, throw error
// list contents
$i = 0;
- while (($stat = $in->statIndex($i++)) !== false) {
+ while (($stat = $zip->statIndex($i++)) !== false) {
$normalized_name = strtolower($stat['name']);
$this->archive_files[$normalized_name] = $stat;
}
- $this->validateInputFile($in, $out);
+ $this->validateInputFile($zip, $out);
- $this->readPreferences($in, $out);
+ $this->readPreferences($zip, $out);
- $this->processFuelTypes($in);
+ $this->processFuelTypes($zip);
// Read vehicle data
- $this->selected_vehicle = intval($form_data['vehicle_id'], 10);
- $data = $this->getVehicle($this->selected_vehicle, $in);
+ $this->selected_vehicle = (int) $form_data['vehicle_id'];
+ $data = $this->getVehicle($this->selected_vehicle, $zip);
// Process vehicle header
- $this->processVehicle($data, $in, $out);
+ $this->processVehicle($data, $zip, $out);
// Process fuellings
- $this->processFuellings($data, $in, $out);
+ $this->processFuellings($data, $zip, $out);
// Process Costs (expenses and services)
- $this->processCosts($data, $in, $out);
+ $this->processCosts($data, $zip, $out);
- $in->close();
+ $zip->close();
$out->rewind();
return $out;
}
// @see IConverter
- public function getErrors() {
- return array();
+ public function getErrors(): array
+ {
+ return [];
}
// @see IConverter
- public function getWarnings() {
- return array();
+ public function getWarnings(): array
+ {
+ return [];
}
// @see IConverter
- public function getCard() {
- return new AcarCard();
+ public function getCard(): CardInterface {
+ return new AcarCardInterface();
}
/**
@@ -128,17 +138,21 @@ public function getCard() {
* @param ZipArchive $in Input archive
* @param FuelioBackupBuilder $out Output file
*/
- protected function readPreferences(ZipArchive $in, FuelioBackupBuilder $out) {
+ protected function readPreferences(ZipArchive $in, FuelioBackupBuilder $out): void
+ {
// Read all preferences and store them as array
$xml = new \SimpleXMLElement(stream_get_contents($in->getStream('preferences.xml')));
foreach ($xml->preference as $node) {
$atts = $node->attributes();
- $key = (string) $atts['name'];
- $type = (string) $atts['type'];
+ if (!$atts) {
+ continue;
+ }
+ $key = (string) ($atts['name'] ?? '');
+ $type = (string) ($atts['type'] ?? '');
$value = (string) $node;
- if ($type == 'java.lang.Boolean') {
- $value = ($value == 'true');
+ if ($type === 'java.lang.Boolean') {
+ $value = ($value === 'true');
}
$this->preferences[$key] = $value;
@@ -148,18 +162,20 @@ protected function readPreferences(ZipArchive $in, FuelioBackupBuilder $out) {
/**
* Reads metadata.inf into $metadata array
* @param ZipArchive $in Input archive
- * @throws \FuelioImporter\InvalidFileFormatException When no metadata.inf in archive
+ * @throws InvalidFileFormatException When no metadata.inf in archive
*/
- protected function readMetadata(ZipArchive $in)
+ protected function readMetadata(ZipArchive $in): void
{
$metastream = $in->getStream('metadata.inf');
- if (false === $metastream)
- throw new \FuelioImporter\InvalidFileFormatException();
+ if (false === $metastream) {
+ throw new InvalidFileFormatException();
+ }
while (!feof($metastream)) {
$entry = explode('=', fgets($metastream), 2);
- if (count($entry) == 2)
+ if (count($entry) == 2) {
$this->metadata[trim($entry[0])] = trim($entry[1]);
+ }
}
}
@@ -167,17 +183,20 @@ protected function readMetadata(ZipArchive $in)
* Throws error if provided file is not Full Backup of aCar data
* @param ZipArchive $in Input archive
* @param FuelioBackupBuilder $out Output file
- * @throws \FuelioImporter\InvalidFileFormatException
+ * @throws InvalidFileFormatException
*/
- protected function validateInputFile(ZipArchive $in, FuelioBackupBuilder $out) {
- if (!isset($this->archive_files['metadata.inf']))
+ protected function validateInputFile(ZipArchive $in, FuelioBackupBuilder $out): void
+ {
+ if (!isset($this->archive_files['metadata.inf'])) {
throw new \FuelioImporter\InvalidFileFormatException();
+ }
$this->readMetadata($in);
// At this moment we support only full backups
- if (@$this->metadata['acar.backup.type'] != 'Full-Backup')
+ if (@$this->metadata['acar.backup.type'] !== 'Full-Backup') {
throw new \FuelioImporter\InvalidFileFormatException('At this moment we support only Full Backups!');
+ }
}
/**
@@ -187,7 +206,8 @@ protected function validateInputFile(ZipArchive $in, FuelioBackupBuilder $out) {
* @param FuelioBackupBuilder $out Output file
* @throws InvalidUnitException
*/
- public function processVehicle(SimpleXMLElement $data, ZipArchive $in, FuelioBackupBuilder $out) {
+ public function processVehicle(SimpleXMLElement $data, ZipArchive $in, FuelioBackupBuilder $out): void
+ {
$out->writeVehicleHeader();
$vehicle = new Vehicle($this->car_name, '');
@@ -213,9 +233,9 @@ public function processVehicle(SimpleXMLElement $data, ZipArchive $in, FuelioBac
* Reads fuel unit from aCar preferences or vehicle node
* @param SimpleXmlElement $vehicleNode Vehicle node for additional data
* @return integer Vehicle constant
- * @throws \FuelioImporter\InvalidUnitException On unsupported unit
+ * @throws InvalidUnitException On unsupported unit
*/
- protected function getFuelUnit(SimpleXMLElement $vehicleNode) {
+ protected function getFuelUnit(SimpleXMLElement $vehicleNode): ?int {
// New aCar version stores volume unit per vehicle, not globally
if (array_key_exists('acar.volume-unit', $this->preferences)) {
$volume_unit = $this->preferences['acar.volume-unit'];
@@ -241,9 +261,10 @@ protected function getFuelUnit(SimpleXMLElement $vehicleNode) {
/**
* Reads distance unit from aCar preferences or vehicle node
* @return integer Vehicle constant
- * @throws \FuelioImporter\InvalidUnitException
+ * @throws InvalidUnitException
*/
- protected function getDistanceUnit(SimpleXMLElement $vehicleNode) {
+ protected function getDistanceUnit(SimpleXMLElement $vehicleNode): ?int
+ {
// New aCar version stores distance unit per vehicle, not globally
if (array_key_exists('acar.distance-unit', $this->preferences)) {
$distance_unit = $this->preferences['acar.distance-unit'];
@@ -267,9 +288,10 @@ protected function getDistanceUnit(SimpleXMLElement $vehicleNode) {
/**
* Reads consumption unit from aCars preferences
* @return integer Vehicle constant
- * @throws \FuelioImporter\InvalidUnitException
+ * @throws InvalidUnitException
*/
- protected function getConsumptionUnit() {
+ protected function getConsumptionUnit(): int
+ {
// @TODO: check the format behind other options:
// mpg (us), mpg (imperial), gal/100mi (us), gal/100mi (imperial), km/L, km/gal (us), km/gal (imperial). mi/L
switch ($this->preferences['acar.fuel-efficiency-unit']) {
@@ -283,7 +305,7 @@ protected function getConsumptionUnit() {
case 'km/L':
return Vehicle::KM_PER_L;
default:
- throw new \FuelioImporter\InvalidUnitException();
+ throw new InvalidUnitException();
}
}
@@ -295,7 +317,7 @@ protected function getConsumptionUnit() {
* @throws InvalidFileFormatException
* @throws FormValidatorException
*/
- protected function getVehicle($iVehicle, ZipArchive $in) {
+ protected function getVehicle($iVehicle, ZipArchive $in): SimpleXMLElement {
$stream = $in->getStream('vehicles.xml');
$xml = new \SimpleXMLElement(stream_get_contents($stream));
if (!$xml) {
@@ -316,7 +338,8 @@ protected function getVehicle($iVehicle, ZipArchive $in) {
* @param string $date
* @return string ATOM-formatted DateTime string
*/
- protected function readDate($date) {
+ protected function readDate($date): string
+ {
$dt = DateTime::createFromFormat('m/d/Y - H:i', (string) $date);
return $dt->format(DateTime::ATOM);
}
@@ -327,11 +350,12 @@ protected function readDate($date) {
* @param ZipArchive $in Input archive
* @param FuelioBackupBuilder $out Output file
*/
- protected function processFuellings(SimpleXMLElement $data, ZipArchive $in, FuelioBackupBuilder $out) {
+ protected function processFuellings(SimpleXMLElement $data, ZipArchive $in, FuelioBackupBuilder $out):void
+ {
$out->writeFuelLogHeader();
foreach ($data->{'fillup-records'}->{'fillup-record'} as $record) {
- $entry = new FuelLogEntry();
+ $entry = new FuelLogEntryInterface();
$entry->setDate($this->readDate($record->date));
$entry->setFuel((string) $record->volume);
@@ -343,8 +367,8 @@ protected function processFuellings(SimpleXMLElement $data, ZipArchive $in, Fuel
// $entry->setConsumption($this->calculateConsumption($consumption, $this->getConsumptionUnit()));
$entry->setGeoCoords((string) $record->latitude, (string) $record->longitude);
- $entry->setFullFillup((string) $record->partial != 'true');
- $entry->setMissedEntries((string) $record->{'previous-missed-fillups'} == 'true');
+ $entry->setFullFillup((string) $record->partial !== 'true');
+ $entry->setMissedEntries((string) $record->{'previous-missed-fillups'} === 'true');
$notes = (string) $record->{'fuel-brand'} . ' ' . (string) $record->{'fueling-station-address'} . ' ' . (string) $record->notes;
$entry->setNotes(trim($notes));
$entry->setMissedEntries(0);
@@ -358,7 +382,7 @@ protected function processFuellings(SimpleXMLElement $data, ZipArchive $in, Fuel
* @param float $consumption Fuel consumption
* @param int $iFormat Consumption unit
* @return float Fuel consumption at L/100km
- * @throws \FuelioImporter\InvalidUnitException
+ * @throws InvalidUnitException
*/
/*protected function calculateConsumption($consumption, $iFormat) {
$dConsumption = floatval(str_replace(',', '.', $consumption));
@@ -390,7 +414,8 @@ protected function processFuellings(SimpleXMLElement $data, ZipArchive $in, Fuel
* @param ZipArchive $in Input archive
* @throws InvalidFileFormatException
*/
- protected function readServicesAsCategories(ZipArchive $in) {
+ protected function readServicesAsCategories(ZipArchive $in): void
+ {
// Depending on aCar version, this data are in services.xml or event-subtypes.xml
if ($in->statName('event-subtypes.xml') !== false) {
$this->readNewServiceDefinition(new \SimpleXMLElement(stream_get_contents($in->getStream('event-subtypes.xml'))));
@@ -399,7 +424,8 @@ protected function readServicesAsCategories(ZipArchive $in) {
else if ($in->statName('services.xml') !== false) {
$this->readOldServiceDefinition(new \SimpleXMLElement(stream_get_contents($in->getStream('services.xml'))));
}
- else throw new InvalidFileFormatException();
+
+ throw new InvalidFileFormatException();
}
@@ -407,7 +433,7 @@ protected function readServicesAsCategories(ZipArchive $in) {
* Reads old-style service definitions
* @param SimpleXMLElement $node
*/
- private function readOldServiceDefinition(SimpleXMLElement $node)
+ private function readOldServiceDefinition(SimpleXMLElement $node): void
{
foreach ($node->service as $service) {
$atts = $service->attributes();
@@ -421,7 +447,7 @@ private function readOldServiceDefinition(SimpleXMLElement $node)
* Reads new service definitions
* @param SimpleXMLElement $node
*/
- private function readNewServiceDefinition(SimpleXMLElement $node)
+ private function readNewServiceDefinition(SimpleXMLElement $node): void
{
foreach ($node->{'event-subtype'} as $subtype) {
$atts = $subtype->attributes();
@@ -443,21 +469,23 @@ private function readNewServiceDefinition(SimpleXMLElement $node)
* @param ZipArchive $in Input archive
* @throws InvalidFileFormatException
*/
- protected function readExpensesAsCategories(ZipArchive $in) {
+ protected function readExpensesAsCategories(ZipArchive $in): void
+ {
// Depending on aCar version, this data are in expenses.xml or event-subtypes.xml
if ($in->statName('event-subtypes.xml') !== false) {
$this->readNewExpensesAsCategories(new \SimpleXMLElement(stream_get_contents($in->getStream('event-subtypes.xml'))));
}
else if ($in->statName('expenses.xml') !== false) {
$this->readOldExpensesAsCategories(new \SimpleXMLElement(stream_get_contents($in->getStream('expenses.xml'))));
- } else throw new InvalidFileFormatException();
+ }
+ throw new InvalidFileFormatException();
}
/**
* Reads new expense definitions
* @param SimpleXMLElement $node
*/
- private function readNewExpensesAsCategories(SimpleXMLElement $node)
+ private function readNewExpensesAsCategories(SimpleXMLElement $node): void
{
foreach ($node->{'event-subtype'} as $subtype) {
$atts = $subtype->attributes();
@@ -478,7 +506,7 @@ private function readNewExpensesAsCategories(SimpleXMLElement $node)
* Reads old-style expense definitions
* @param SimpleXMLElement $node
*/
- private function readOldExpensesAsCategories(SimpleXMLElement $node)
+ private function readOldExpensesAsCategories(SimpleXMLElement $node): void
{
foreach ($node->expense as $expense) {
$atts = $expense->attributes();
@@ -493,7 +521,8 @@ private function readOldExpensesAsCategories(SimpleXMLElement $node)
* @param ZipArchive $in Input archive
* @param FuelioBackupBuilder $out Output file
*/
- protected function processCostCategories(ZipArchive $in, FuelioBackupBuilder $out) {
+ protected function processCostCategories(ZipArchive $in, FuelioBackupBuilder $out): void
+ {
$this->readExpensesAsCategories($in);
$this->readServicesAsCategories($in);
@@ -514,7 +543,8 @@ protected function processCostCategories(ZipArchive $in, FuelioBackupBuilder $ou
* @param SimpleXMLElement $expense
* @param FuelioBackupBuilder $out
*/
- protected function processExpense(SimpleXMLElement $expense, FuelioBackupBuilder $out) {
+ protected function processExpense(SimpleXMLElement $expense, FuelioBackupBuilder $out): void
+ {
$cost = new Cost();
$cost->setDate($this->readDate($expense->date));
$cost->setCost((string) $expense->{'total-cost'});
@@ -547,7 +577,7 @@ protected function processExpense(SimpleXMLElement $expense, FuelioBackupBuilder
$title = trim($title[0]);
if (strpos($title, ',') !== false) {
- $title = substr($title, 0, strpos($title, ','));
+ $title = substr($title, 0, strpos($title, ',') ?: null);
}
$cost->setNotes(trim($notes));
@@ -560,7 +590,8 @@ protected function processExpense(SimpleXMLElement $expense, FuelioBackupBuilder
* @param SimpleXMLElement $service
* @param FuelioBackupBuilder $out
*/
- protected function processService(SimpleXMLElement $service, FuelioBackupBuilder $out) {
+ protected function processService(SimpleXMLElement $service, FuelioBackupBuilder $out): void
+ {
$cost = new Cost();
$cost->setDate($this->readDate($service->date));
$cost->setCost((string) $service->{'total-cost'});
@@ -593,7 +624,7 @@ protected function processService(SimpleXMLElement $service, FuelioBackupBuilder
$title = trim($title[0]);
if (strpos($title, ',') !== false) {
- $title = substr($title, 0, strpos($title, ','));
+ $title = substr($title, 0, strpos($title, ',') ?: null);
}
$cost->setNotes(trim($notes));
@@ -607,7 +638,8 @@ protected function processService(SimpleXMLElement $service, FuelioBackupBuilder
* @param ZipArchive $in Input archive
* @param FuelioBackupBuilder $out Output file
*/
- protected function processCosts(SimpleXMLElement $data, ZipArchive $in, FuelioBackupBuilder $out) {
+ protected function processCosts(SimpleXMLElement $data, ZipArchive $in, FuelioBackupBuilder $out): void
+ {
$out->writeCostCategoriesHeader();
$this->processCostCategories($in, $out);
@@ -639,7 +671,8 @@ protected function processCosts(SimpleXMLElement $data, ZipArchive $in, FuelioBa
}
}
- protected function processFuelTypes(ZipArchive $in) {
+ protected function processFuelTypes(ZipArchive $in): void
+ {
if ($in->statName('fuel-types.xml') !== false) {
$this->readFuelTypes(new \SimpleXMLElement(stream_get_contents($in->getStream('fuel-types.xml'))));
} else {
@@ -647,7 +680,8 @@ protected function processFuelTypes(ZipArchive $in) {
}
}
- protected function readFuelTypes(SimpleXMLElement $root_node) {
+ protected function readFuelTypes(SimpleXMLElement $root_node): void
+ {
$this->acar_fuels = array();
foreach ($root_node->{'fuel-type'} as $node) {
$atts = $node->attributes();
@@ -663,7 +697,8 @@ protected function readFuelTypes(SimpleXMLElement $root_node) {
$this->fuel_types = FuelTypes::getTypes();
}
- protected function getFuelType($iAcarFuelType) {
+ protected function getFuelType($iAcarFuelType): ?int
+ {
if (!$this->fuel_types) {
return null;
@@ -697,7 +732,7 @@ protected function getFuelType($iAcarFuelType) {
return $fuelio_type !== -1 ? $fuelio_type : null;
}
- protected function determineVehicleFuelType(SimpleXMLElement $vehicle)
+ protected function determineVehicleFuelType(SimpleXMLElement $vehicle): ?int
{
foreach ($vehicle->{'fillup-records'}->{'fillup-record'} as $fillup) {
$sFuelType = (string)$fillup->{'fuel-type-id'};
@@ -710,5 +745,4 @@ protected function determineVehicleFuelType(SimpleXMLElement $vehicle)
}
return null;
}
-
}
diff --git a/lib/fuelioimporter/providers/drivvoprovider.class.php b/src/Providers/DrivvoProvider.php
similarity index 76%
rename from lib/fuelioimporter/providers/drivvoprovider.class.php
rename to src/Providers/DrivvoProvider.php
index be6bc1a..5659aaf 100644
--- a/lib/fuelioimporter/providers/drivvoprovider.class.php
+++ b/src/Providers/DrivvoProvider.php
@@ -1,102 +1,106 @@
output_filename ?: $this->getTitle();
}
- public function getStylesheetLocation()
+ public function getStylesheetLocation(): ?string
{
return null;
}
- public function setCarName($name)
+ public function setCarName($name): void
{
if (!empty($name)) {
$this->output_filename = $name;
}
}
- public function getCard()
+ public function getCard(): CardInterface
{
- return new DrivvoCard();
+ return new DrivvoCardInterface();
}
- public function getErrors()
+ public function getErrors(): array
{
- return array();
+ return [];
}
- public function getWarnings()
+ public function getWarnings(): array
{
return $this->warnings;
}
- public function processFile(SplFileObject $in, $form_data)
+ public function processFile(SplFileObject $in, $form_data): FuelioBackupBuilder
{
if ($in->isDir() || ($in->isFile() && !$in->isReadable())) {
throw new InvalidFileFormatException('File is not readable');
@@ -149,7 +153,7 @@ public function processFile(SplFileObject $in, $form_data)
* @param SplFileObject $in
* @param FuelioBackupBuilder $out
*/
- protected function processVehicles(SplFileObject $in, FuelioBackupBuilder $out)
+ protected function processVehicles(SplFileObject $in, FuelioBackupBuilder $out): void
{
// Write out selected vehicle
$out->writeVehicleHeader();
@@ -169,7 +173,7 @@ protected function processVehicles(SplFileObject $in, FuelioBackupBuilder $out)
$out->writeVehicle($vehicle);
}
- protected function processFillups(SplFileObject $in, FuelioBackupBuilder $out)
+ protected function processFillups(SplFileObject $in, FuelioBackupBuilder $out): void
{
$this->rewindToHeader($in, self::FUELLING_HEADERS);
if ($in->eof()) {
@@ -186,7 +190,7 @@ protected function processFillups(SplFileObject $in, FuelioBackupBuilder $out)
do {
$data = $in->fgetcsv();
if ($data && $data[0] !== '' && $data[0] > 0) {
- $entry = new FuelLogEntry();
+ $entry = new FuelLogEntryInterface();
$entry->setDate($this->normalizeDate($data[1]));
$entry->setOdo((double)$data[0]);
$entry->setFuel((double)$data[5]);
@@ -206,10 +210,11 @@ protected function processFillups(SplFileObject $in, FuelioBackupBuilder $out)
$out->writeFuelLog($entry);
}
- } while (!$in->eof() && strpos($data[0], '#', 0) !== 0);
+ } while (!$in->eof() && $data && strpos($data[0] ?? '', '#', 0) !== 0);
}
- protected function processExpense(SplFileObject $in, FuelioBackupBuilder $out) {
+ protected function processExpense(SplFileObject $in, FuelioBackupBuilder $out): void
+ {
// make,model,title,date,mileage,costs,note,recurrence
$this->rewindToHeader($in, self::EXPENSE_HEADERS);
if ($in->eof()) {
@@ -218,27 +223,28 @@ protected function processExpense(SplFileObject $in, FuelioBackupBuilder $out) {
$header = $in->fgetcsv();
- if (count($header) < 7) {
+ if (!$header || count($header) < 7) {
$this->warnings[] = 'Skipping expenses as the header is not recognized.';
return;
}
do {
$data = $in->fgetcsv();
- if ($data !== false && $data[0]!=='' && $data[0] > 0) {
+ if ($data && $data[0] !== '' && $data[0] > 0) {
$cost = new Cost();
$cost->setOdo($data[0]);
$cost->setDate($this->normalizeDate($data[1]));
$cost->setCost((double)$data[2]);
$cost->setCostCategoryId(2);
- $cost->setTitle(trim($data[3]));
- $cost->setNotes(trim($data[6]));
+ $cost->setTitle(trim($data[3] ?? ''));
+ $cost->setNotes(trim($data[6] ?? ''));
$out->writeCost($cost);
}
- } while (!$in->eof() && strpos($data[0], '#', 0) !== 0);
+ } while (!$in->eof() && strpos($data[0] ?? '', '#', 0) !== 0);
}
- protected function processService(SplFileObject $in, FuelioBackupBuilder $out) {
+ protected function processService(SplFileObject $in, FuelioBackupBuilder $out): void
+ {
// make,model,title,date,mileage,costs,note,recurrence
$this->rewindToHeader($in, self::SERVICE_HEADERS);
@@ -260,11 +266,11 @@ protected function processService(SplFileObject $in, FuelioBackupBuilder $out) {
$cost->setDate($this->normalizeDate($data[1]));
$cost->setCost((double)$data[2]);
$cost->setCostCategoryId(1);
- $cost->setTitle(trim($data[3]));
- $cost->setNotes(trim($data[5]));
+ $cost->setTitle(trim($data[3] ?? ''));
+ $cost->setNotes(trim($data[5] ?? ''));
$out->writeCost($cost);
}
- } while (!$in->eof() && strpos($data[0], '#', 0) !== 0);
+ } while (!$in->eof() && strpos($data[0] ?? '', '#', 0) !== 0);
}
@@ -287,11 +293,11 @@ protected function normalizeDate($date): string
return $date; //no-op
}
- protected function rewindToHeader(SplFileObject $file, array $headers)
+ protected function rewindToHeader(SplFileObject $file, array $headers): void
{
$file->rewind();
do {
$line = $file->fgetcsv();
- } while (!$file->eof() && !in_array($line[0], $headers, true));
+ } while (!$file->eof() && !in_array($line[0] ?? '', $headers, true));
}
-}
\ No newline at end of file
+}
diff --git a/lib/fuelioimporter/providers/fuellogprovider.class.php b/src/Providers/FuellogProvider.php
similarity index 80%
rename from lib/fuelioimporter/providers/fuellogprovider.class.php
rename to src/Providers/FuellogProvider.php
index 26b8fc5..3291ca8 100644
--- a/lib/fuelioimporter/providers/fuellogprovider.class.php
+++ b/src/Providers/FuellogProvider.php
@@ -1,71 +1,75 @@
output_filename ?: $this->getTitle();
}
- public function getStylesheetLocation()
+ public function getStylesheetLocation(): ?string
{
return null;
}
- public function setCarName($name)
+ public function setCarName($name): void
{
if (!empty($name)) {
$this->output_filename = $name;
}
}
- public function getCard()
+ public function getCard(): CardInterface
{
- return new FuellogCard();
+ return new FuellogCardInterface();
}
- public function getErrors()
+ public function getErrors(): array
{
- return array();
+ return [];
}
- public function getWarnings()
+ public function getWarnings(): array
{
- return array();
+ return [];
}
- public function processFile(\SplFileObject $in, $form_data)
+ public function processFile(\SplFileObject $in, $form_data): FuelioBackupBuilder
{
if ($in->isDir() || ($in->isFile() && !$in->isReadable())) {
throw new InvalidFileFormatException();
@@ -103,15 +107,15 @@ public function processFile(\SplFileObject $in, $form_data)
return $out;
}
- protected function detectDelimiter(\SplFileObject $in)
+ protected function detectDelimiter(\SplFileObject $in): void
{
$pos = $in->ftell();
$line = $in->fgetcsv($this->delimiter);
- if ($line[0] !== 'make') {
+ if ($line && $line[0] !== 'make') {
$this->delimiter = ';';
$in->fseek($pos);
$line = $in->fgetcsv($this->delimiter);
- if ($line[0] !== 'make') {
+ if ($line && $line[0] !== 'make') {
throw new InvalidFileFormatException();
}
}
@@ -125,17 +129,17 @@ protected function detectDelimiter(\SplFileObject $in)
* @throws InvalidFileFormatException
* @throws InvalidUnitException
*/
- protected function processVehicles(\SplFileObject $in, FuelioBackupBuilder $out)
+ protected function processVehicles(\SplFileObject $in, FuelioBackupBuilder $out): void
{
// "make","model","note","distance","volume","consumption"
$this->detectDelimiter($in);
$header = $in->fgetcsv($this->delimiter);
- if ($header[0] !== 'make' || count($header) < 6) {
+ if (!$header || $header[0] !== 'make' || count($header) < 6) {
throw new InvalidFileFormatException();
}
do {
- if (!($line = $in->fgetcsv($this->delimiter)) || strpos($line[0], '#', 0) === 0) {
+ if (!($line = $in->fgetcsv($this->delimiter)) || strpos($line[0] ?? '', '#', 0) === 0) {
break;
}
$key = $line[0] . '.' . $line[1];
@@ -184,11 +188,11 @@ protected function processVehicles(\SplFileObject $in, FuelioBackupBuilder $out)
$out->writeVehicle($vehicle);
}
- protected function processFillups(\SplFileObject $in, FuelioBackupBuilder $out)
+ protected function processFillups(\SplFileObject $in, FuelioBackupBuilder $out): void
{
// "make","model","date","mileage","fuel","price","partial","note"
$header = $in->fgetcsv($this->delimiter);
- if ($header[0] !== 'make' || count($header) !== 8) {
+ if (!$header || $header[0] !== 'make' || count($header) !== 8) {
throw new InvalidFileFormatException();
}
@@ -206,8 +210,8 @@ protected function processFillups(\SplFileObject $in, FuelioBackupBuilder $out)
continue;
}
- $entry = new FuelLogEntry();
- $entry->setDate($this->normalizeDate($data[2]));
+ $entry = new FuelLogEntryInterface();
+ $entry->setDate($this->normalizeDate($data[2] ?? ''));
$entry->setOdo((double)$data[3]);
$entry->setFuel((double)$data[4]);
$entry->setVolumePrice((double)$data[5]);
@@ -215,17 +219,18 @@ protected function processFillups(\SplFileObject $in, FuelioBackupBuilder $out)
$entry->setNotes($data[7]);
$out->writeFuelLog($entry);
- } while (!$in->eof() && strpos($data[0], '#', 0) !== 0);
+ } while (!$in->eof() && strpos($data[0] ?? '', '#', 0) !== 0);
}
- protected function processCosts(\SplFileObject $in, FuelioBackupBuilder $out) {
+ protected function processCosts(\SplFileObject $in, FuelioBackupBuilder $out): void
+ {
// make,model,title,date,mileage,costs,note,recurrence
if ($in->eof()) {
return; // Turns out costs are optional in file, so skip if we are at its end
}
$header = $in->fgetcsv($this->delimiter);
- if ($header[0] !== 'make' || count($header) !== 8) {
+ if (!$header || $header[0] !== 'make' || count($header) !== 8) {
throw new InvalidFileFormatException();
}
@@ -251,15 +256,15 @@ protected function processCosts(\SplFileObject $in, FuelioBackupBuilder $out) {
$cost = new Cost();
$cost->setCost((double)$data[5]);
$cost->setCostCategoryId(FuelioBackupBuilder::SAFE_CATEGORY_ID);
- $cost->setDate($this->normalizeDate($data[3]));
- $cost->setTitle(trim($data[2]));
- $cost->setNotes(trim($data[6]));
+ $cost->setDate($this->normalizeDate($data[3] ?? ''));
+ $cost->setTitle(trim($data[2] ?? ''));
+ $cost->setNotes(trim($data[6] ?? ''));
$cost->setOdo($data[4]);
- $cost->setReminderDate($this->convertCostReminder($this->normalizeDate($data[3]), $data[7]));
- $cost->setRepeatMonths($this->convertRepeatMonths($data[7]));
+ $cost->setReminderDate($this->convertCostReminder($this->normalizeDate($data[3] ?? ''), $data[7] ?? ''));
+ $cost->setRepeatMonths($this->convertRepeatMonths($data[7] ?? ''));
$out->writeCost($cost);
- } while (!$in->eof() && strpos($data[0], '#', 0) !== 0);
+ } while (!$in->eof() && strpos($data[0] ?? '', '#', 0) !== 0);
}
@@ -270,28 +275,25 @@ protected function processCosts(\SplFileObject $in, FuelioBackupBuilder $out) {
*
* Currently it only detects dd/mm/YYYY format and turns it into YYYY-MM-DD
*/
- protected function normalizeDate($date)
+ protected function normalizeDate(string $date): string
{
// Let's assume date could be written as X/Y/ZZZZ
- if (strlen($date) >= 8) {
- // Let's assume it's written with '/' as separator
- // and it's actually D/M/YYYY, as we have no way of detecting M/D/YYYY when day part is < 13
- if ($date[1] === '/' || $date[2] === '/') {
- $parts = explode('/', $date, 3);
- return $parts[2] . '-' . $parts[1] . '-' . $parts[0]; // YYYY-MM-DD
- }
+ // Let's assume it's written with '/' as separator
+ // and it's actually D/M/YYYY, as we have no way of detecting M/D/YYYY when day part is < 13
+ if (strlen($date) >= 8 && ($date[1] === '/' || $date[2] === '/')) {
+ $parts = explode('/', $date, 3);
+ return $parts[2] . '-' . $parts[1] . '-' . $parts[0]; // YYYY-MM-DD
}
+
return $date; //no-op
}
-
/**
* Returns distance unit extracted from log
- * @param $raw string
* @return int Vehicle const
* @throws InvalidUnitException
*/
- protected function getDistanceUnit($raw)
+ protected function getDistanceUnit(string $raw): int
{
/* Based on FuelLog's explanations.txt */
@@ -305,11 +307,10 @@ protected function getDistanceUnit($raw)
/**
* Returns volume unit extracted from log
- * @param $raw string
* @return int Vehicle const
* @throws InvalidUnitException
*/
- protected function getVolumeUnit($raw)
+ protected function getVolumeUnit(string $raw): int
{
/* Based on FuelLog's explanations.txt */
@@ -326,11 +327,10 @@ protected function getVolumeUnit($raw)
/**
* Returns consumption unit extracted from log
- * @param $raw string
* @return int Vehicle const
* @throws InvalidUnitException
*/
- protected function getConsumptionUnit($raw)
+ protected function getConsumptionUnit(string $raw): int
{
/* Based on FuelLog's explanations.txt */
@@ -390,12 +390,11 @@ protected function getConsumptionUnit($raw)
/**
* Returns cost date moved according to recurrence type
- * @param $sDate string current cost date
- * @param $raw_recurrence string
+ * @param string $sDate current cost date
* @return null|string New reminders date
* @throws InvalidUnitException
*/
- protected function convertCostReminder($sDate, $raw_recurrence)
+ protected function convertCostReminder(string $sDate, string $raw_recurrence): ?string
{
/* Based on FuelLog's explanations.txt */
@@ -426,7 +425,7 @@ protected function convertCostReminder($sDate, $raw_recurrence)
* @param $raw_recurrence string
* @return int Number of recurrence months
*/
- protected function convertRepeatMonths($raw_recurrence)
+ protected function convertRepeatMonths(string $raw_recurrence): int
{
switch((int)$raw_recurrence) {
case 3 : return 1;
@@ -438,4 +437,4 @@ protected function convertRepeatMonths($raw_recurrence)
default: return 0; // By default there is no monthly repetition
}
}
-}
\ No newline at end of file
+}
diff --git a/lib/fuelioimporter/providers/motostatprovider.class.php b/src/Providers/MotostatProvider.php
similarity index 76%
rename from lib/fuelioimporter/providers/motostatprovider.class.php
rename to src/Providers/MotostatProvider.php
index d1bdfd9..74063b0 100644
--- a/lib/fuelioimporter/providers/motostatprovider.class.php
+++ b/src/Providers/MotostatProvider.php
@@ -1,23 +1,27 @@
getTitle();
}
- public function getCard() {
- return new MotostatCard();
+ public function getCard(): CardInterface
+ {
+ return new MotostatCardInterface();
}
- public function setCarName($name) {
+ public function setCarName($name): void
+ {
if (!empty($name)) {
$this->car_name = $name;
}
}
- public function getErrors() {
- return array();
+ public function getErrors(): array
+ {
+ return [];
}
- public function getWarnings() {
- return array();
+ public function getWarnings(): array
+ {
+ return [];
}
- public function getStylesheetLocation() {
+ public function getStylesheetLocation(): ?string
+ {
return null;
}
- public function processFile(\SplFileObject $in, $form_data) {
+ public function processFile(\SplFileObject $in, $form_data): FuelioBackupBuilder
+ {
if ($in->isDir() || ($in->isFile() && !$in->isReadable())) {
throw new InvalidFileFormatException();
}
@@ -83,14 +95,14 @@ public function processFile(\SplFileObject $in, $form_data) {
// Verify file header
$head = $in->fgetcsv(';');
- if (count($head) !== 23) {
+ if (!$head || count($head) !== 23) {
throw new InvalidFileFormatException();
}
// First column might have BOM
- $hasBOM = substr($head[0], 0, 3) === pack('CCC', 239, 187, 191);
+ $hasBOM = strpos($head[0] ?? '', pack('CCC', 239, 187, 191)) === 0;
if ($hasBOM) {
- $head[0] = substr($head[0], 3);
+ $head[0] = substr($head[0] ?? '', 3);
}
if ($head[0] !== 'cost_id') {
@@ -104,7 +116,7 @@ public function processFile(\SplFileObject $in, $form_data) {
$this->processFuelings($in, $out);
// process cost data and categories
- $this->processCostData($in, $out);
+ $this->processCostData($out);
// empty memory
$this->cleanup();
@@ -112,7 +124,8 @@ public function processFile(\SplFileObject $in, $form_data) {
}
//cost_id;fueling_id;cost_type;date;fuel_id;gas_station_id;odometer;trip_odometer;quantity;cost;notes;fueling_type;tires;driving_style;route_motorway;route_country;route_city;bc_consumption;bc_avg_speed;ac;currency;fuel_name;gas_station_name
- protected function processFuelings(SplFileObject $in, FuelioBackupBuilder $out) {
+ protected function processFuelings(SplFileObject $in, FuelioBackupBuilder $out): void
+ {
$out->writeFuelLogHeader();
while (!$in->eof() && (($log = $in->fgetcsv(';')) !== false)) {
// log only fillups, costs have dedicated category
@@ -120,10 +133,11 @@ protected function processFuelings(SplFileObject $in, FuelioBackupBuilder $out)
$this->costs_data[] = $log;
continue;
}
- if (empty($log[1]))
+ if (empty($log[1])) {
continue; // no fueling_id
+ }
- $entry = new FuelLogEntry();
+ $entry = new FuelLogEntryInterface();
$entry->setDate($log[3]);
$entry->setOdo($log[6]);
$entry->setFuel($log[8]);
@@ -139,7 +153,8 @@ protected function processFuelings(SplFileObject $in, FuelioBackupBuilder $out)
/**
* Initializes costs and cost_categories arrays
*/
- protected function processCostData(SplFileObject $in, FuelioBackupBuilder $out) {
+ protected function processCostData(FuelioBackupBuilder $out): void
+ {
foreach ($this->costs_data as $line) {
$category = $this->findCategory($line[2]);
$cost = new Cost();
@@ -169,9 +184,9 @@ protected function processCostData(SplFileObject $in, FuelioBackupBuilder $out)
/**
* Returns CostCategory instance
* @param string $category_name Category name
- * @return CostCategory
*/
- protected function findCategory($category_name) {
+ protected function findCategory(string $category_name): CostCategory
+ {
// Normalize name
$normalized_category_name = strtolower(trim($category_name));
@@ -186,9 +201,9 @@ protected function findCategory($category_name) {
return $category;
}
- protected function cleanup() {
- $this->costs = array();
- $this->categories = array();
+ protected function cleanup(): void
+ {
+ $this->costs = [];
+ $this->categories = [];
}
-
}
diff --git a/lib/fuelioimporter/uploaderror.class.php b/src/UploadError.php
similarity index 70%
rename from lib/fuelioimporter/uploaderror.class.php
rename to src/UploadError.php
index 3c9bdc8..0ca0f15 100644
--- a/lib/fuelioimporter/uploaderror.class.php
+++ b/src/UploadError.php
@@ -1,21 +1,24 @@
$file_array */
+ public function __construct(array $file_array, $code = 0, ?Throwable $previous = null)
{
- $message = 'File upload error';
switch ($file_array['error']) {
case UPLOAD_ERR_CANT_WRITE: $message = 'Cannot store file on server: Write error'; break;
case UPLOAD_ERR_FORM_SIZE:
case UPLOAD_ERR_INI_SIZE: $message = 'Exceeded file size limit.'; break;
case UPLOAD_ERR_NO_FILE: $message = 'No file sent'; break;
case UPLOAD_ERR_PARTIAL:
+ default: $message = 'File upload error'; break;
}
parent::__construct($message, $code, $previous);
}
-}
\ No newline at end of file
+}
diff --git a/lib/fuelioimporter/vehicle.class.php b/src/Vehicle.php
similarity index 55%
rename from lib/fuelioimporter/vehicle.class.php
rename to src/Vehicle.php
index 99e34a6..4d10dfc 100644
--- a/lib/fuelioimporter/vehicle.class.php
+++ b/src/Vehicle.php
@@ -1,5 +1,7 @@
setName($sName);
$this->setDescription($sDescription);
$this->setDistanceUnit($iDistance_unit);
@@ -98,55 +106,68 @@ public function __construct($sName, $sDescription, $iDistance_unit = Vehicle::KI
$this->setConsumptionUnit($iConsumption_unit);
}
- public function setName($sName) {
+ public function setName($sName): void
+ {
$this->name = $sName;
}
- public function setDescription($sDescription) {
+ public function setDescription($sDescription): void
+ {
$this->description = $sDescription;
}
- public function setDistanceUnit($iDistance_unit) {
+ public function setDistanceUnit($iDistance_unit): void
+ {
$this->distance_unit = $iDistance_unit;
}
- public function setFuelUnit($iFuel_unit) {
+ public function setFuelUnit($iFuel_unit): void
+ {
$this->fuel_unit = $iFuel_unit;
}
- public function setConsumptionUnit($iConsumption_unit) {
+ public function setConsumptionUnit($iConsumption_unit): void
+ {
$this->consumption_unit = $iConsumption_unit;
}
- public function setVIN($sVin) {
+ public function setVIN($sVin): void
+ {
$this->vin = $sVin;
}
- public function setInsurance($sInsurance) {
+ public function setInsurance($sInsurance): void
+ {
$this->insurance = $sInsurance;
}
- public function setPlate($sPlate) {
+ public function setPlate($sPlate): void
+ {
$this->plate = $sPlate;
}
- public function setMake($sMake) {
+ public function setMake($sMake): void
+ {
$this->make = $sMake;
}
- public function setModel($sModel) {
+ public function setModel($sModel): void
+ {
$this->model = $sModel;
}
- public function setYear($iYear) {
- $this->year = intval($iYear);
+ public function setYear($iYear): void
+ {
+ $this->year = (int) $iYear;
}
- public function setTankCount($nTankCount) {
+ public function setTankCount($nTankCount): void
+ {
$this->tank_count = (int)$nTankCount;
}
- public function setTankType($nIdx, $nType) {
+ public function setTankType($nIdx, $nType): void
+ {
$idx = (int)$nIdx;
if (($idx !== 1 && $idx !== 2) || $nType === null) {
return; //no-op, only two tanks storable
@@ -155,16 +176,17 @@ public function setTankType($nIdx, $nType) {
$this->{'tank_'.$idx.'_type'} = (int)$nType;
}
- public function setActive($bActive) {
+ public function setActive($bActive): void
+ {
$this->active = (int)(bool)$bActive;
}
- public function getData() {
+ public function getData(): array
+ {
$vars = get_object_vars($this);
if (empty($vars['name'])) {
$vars['name'] = 'No Name';
}
return array_values($vars);
}
-
}
diff --git a/view/_append_analytics.php b/view/_append_analytics.php
new file mode 100644
index 0000000..8dec4c3
--- /dev/null
+++ b/view/_append_analytics.php
@@ -0,0 +1,5 @@
+
-
+