103 lines
2.7 KiB
PHP
103 lines
2.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace RprtCli\Utils\CsvReport;
|
|
|
|
use RprtCli\Utils\Configuration\ConfigurationInterface;
|
|
|
|
use function array_key_first;
|
|
use function array_keys;
|
|
use function fgetcsv;
|
|
use function fopen;
|
|
use function preg_match;
|
|
use function reset;
|
|
|
|
/**
|
|
* Creates a report of projects and hours.
|
|
*/
|
|
class CsvReport implements CsvReportInterface
|
|
{
|
|
/**
|
|
* A configuration service.
|
|
*
|
|
* @var ConfigurationInterface
|
|
*/
|
|
protected $configurationService;
|
|
|
|
public function __construct(ConfigurationInterface $config)
|
|
{
|
|
$this->configurationService = $config;
|
|
}
|
|
|
|
/**
|
|
* {@inheritdoc}
|
|
*/
|
|
public function getReportData(string $filePath) : array
|
|
{
|
|
$output = [];
|
|
// @TODO replace with config service.
|
|
// $config = $this->dummyConfig()['projects'];
|
|
$config = $this->configurationService->get('projects');
|
|
foreach (array_keys($config) as $key) {
|
|
$output[$key] = 0;
|
|
}
|
|
if ($file = fopen($filePath, 'r')) {
|
|
while (($line = fgetcsv($file)) !== false) {
|
|
$parsed = $this->parseCsvFile($line);
|
|
// $key = reset(array_keys($parsed));
|
|
$key = array_key_first($parsed);
|
|
if (isset($output[$key])) {
|
|
$output[$key] += (int) reset($parsed);
|
|
}
|
|
}
|
|
}
|
|
return $output;
|
|
}
|
|
|
|
/**
|
|
* Get correct values from the raw data lines of csv.
|
|
*
|
|
*
|
|
* Columns with data are specified in config.
|
|
*
|
|
* Project key and unit of time spent.
|
|
*/
|
|
protected function parseCsvFile(array $rawData) : array
|
|
{
|
|
$config = $this->configurationService->get('projects');
|
|
foreach ($config as $key => $project) {
|
|
if (preg_match('/' . $project['pattern'] . '/', $rawData[1])) {
|
|
return [$key => $rawData[4]];
|
|
}
|
|
}
|
|
return [];
|
|
}
|
|
|
|
protected function dummyConfig() : array
|
|
{
|
|
return [
|
|
'projects' => [
|
|
'LDP' => [
|
|
'name' => 'lupus.digital',
|
|
'pattern' => 'LDP-[0-9]+',
|
|
'price' => 26,
|
|
// optional specify columns
|
|
],
|
|
'WV' => [
|
|
'name' => 'Wirtschaftsverlag',
|
|
'pattern' => 'WV-[0-9]+',
|
|
'price' => 26,
|
|
// optional specify columns
|
|
],
|
|
'Other' => [
|
|
'name' => 'Other projects',
|
|
'pattern' => '(?!.\bLDP\b)(?!.\bWV\b)',
|
|
'price' => 26,
|
|
// optional specify columns
|
|
],
|
|
],
|
|
];
|
|
}
|
|
}
|