Completed
Push — development ( c96382...3fa72d )
by Torben
03:47
created

ExportService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 1
cts 1
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
namespace DERHANSEN\SfEventMgt\Service;
3
4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
 * It is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU General Public License, either version 2
9
 * of the License, or any later version.
10
 *
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
 * The TYPO3 project - inspiring people to share!
15
 */
16
17
use DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository;
18
use TYPO3\CMS\Core\Resource\ResourceFactory;
19
use \TYPO3\CMS\Core\Utility\GeneralUtility;
20
use \DERHANSEN\SfEventMgt\Exception;
21
22
/**
23
 * Class ExportService
24
 *
25
 * @author Torben Hansen <[email protected]>
26
 */
27
class ExportService
28
{
29
30
    /**
31
     * Repository with registrations for the events
32
     *
33
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository
34
     */
35
    protected $registrationRepository;
36
37
    /**
38
     * ResourceFactory
39
     *
40
     * @var \TYPO3\CMS\Core\Resource\ResourceFactory
41
     */
42
    protected $resourceFactory = null;
43
44
    /**
45
     * ExportService constructor.
46
     *
47
     * @param RegistrationRepository $registrationRepository
48
     * @param ResourceFactory $resourceFactory
49
     */
50
    public function __construct(RegistrationRepository $registrationRepository, ResourceFactory $resourceFactory)
51
    {
52
        $this->registrationRepository = $registrationRepository;
53 2
        $this->resourceFactory = $resourceFactory;
54
    }
55 2
56 2
    /**
57 1
     * Initiates the CSV downloads for registrations of the given event uid
58
     *
59 1
     * @param int $eventUid EventUid
60 1
     * @param array $settings Settings
61 1
     * @throws Exception RuntimeException
62 1
     * @return void
63 1
     */
64 1
    public function downloadRegistrationsCsv($eventUid, $settings = [])
65 1
    {
66
        $storage = $this->resourceFactory->getDefaultStorage();
67
        if ($storage === null) {
68
            throw new Exception('Could not get the default storage', 1475590001);
69
        }
70
        $registrations = $this->exportRegistrationsCsv($eventUid, $settings);
71
        $tempFolder = $storage->getFolder('_temp_');
72
        $tempFile = $storage->createFile('sf_events_export.csv', $tempFolder);
73
        $tempFile->setContents($registrations);
74
        $storage->dumpFileContents($tempFile, true, 'registrations_' . date('dmY_His') . '.csv');
0 ignored issues
show
Bug introduced by
It seems like $tempFile defined by $storage->createFile('sf...port.csv', $tempFolder) on line 72 can also be of type null; however, TYPO3\CMS\Core\Resource\...age::dumpFileContents() does only seem to accept object<TYPO3\CMS\Core\Resource\FileInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
75
        $tempFile->delete();
76 5
    }
77
78 5
    /**
79 5
     * Returns all Registrations for the given eventUid as a CSV string
80 5
     *
81 5
     * @param int $eventUid EventUid
82 5
     * @param array $settings Settings
83 5
     * @throws Exception RuntimeException
84 5
     * @return string
85 5
     */
86 5
    public function exportRegistrationsCsv($eventUid, $settings = [])
87 5
    {
88 1
        $fieldsArray = array_map('trim', explode(',', $settings['fields']));
89 1
        $registrations = $this->registrationRepository->findByEvent($eventUid);
0 ignored issues
show
Documentation Bug introduced by
The method findByEvent does not exist on object<DERHANSEN\SfEvent...RegistrationRepository>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
90
        $exportedRegistrations = GeneralUtility::csvValues(
0 ignored issues
show
Deprecated Code introduced by
The method TYPO3\CMS\Core\Utility\GeneralUtility::csvValues() has been deprecated with message: since TYPO3 v8, will be removed in TYPO3 v9.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
91 5
            $fieldsArray,
92 4
            $settings['fieldDelimiter'],
93 4
            $settings['fieldQuoteCharacter']
94 4
        ) . chr(10);
95 4
        foreach ($registrations as $registration) {
96
            $exportedRegistration = [];
97
            foreach ($fieldsArray as $field) {
98
                if ($registration->_hasProperty($field)) {
99
                    $exportedRegistration[] = $this->getFieldValue($registration, $field);
100
                } else {
101
                    throw new Exception('Field ' . $field .
102
                        ' is not a Property of Model Registration, please check your TS configuration', 1475590002);
103
                }
104
            }
105
            $exportedRegistrations .= GeneralUtility::csvValues(
0 ignored issues
show
Deprecated Code introduced by
The method TYPO3\CMS\Core\Utility\GeneralUtility::csvValues() has been deprecated with message: since TYPO3 v8, will be removed in TYPO3 v9.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
106 5
                $exportedRegistration,
107
                $settings['fieldDelimiter'],
108 5
                $settings['fieldQuoteCharacter']
109 5
            ) . chr(10);
110
        }
111
        return $this->prependByteOrderMark($exportedRegistrations, $settings);
112 5
    }
113
114
    /**
115
     * Prepends Byte Order Mark to exported registrations
116
     *
117
     * @param string $exportedRegistrations
118
     * @param array $settings
119
     * @return string
120
     */
121
    protected function prependByteOrderMark($exportedRegistrations, $settings)
122
    {
123
        if ((bool)$settings['prependBOM']) {
124
            $exportedRegistrations = chr(239) . chr(187) . chr(191) . $exportedRegistrations;
125
        }
126
        return $exportedRegistrations;
127
    }
128
    
129
    /**
130
     * Returns the requested field from the given registration. If the field is a DateTime object,
131
     * a formatted date string is returned
132
     *
133
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration
134
     * @param string $field
135
     * @return string
136
     */
137
    protected function getFieldValue($registration, $field)
138
    {
139
        $value = $registration->_getCleanProperty($field);
140
        if ($value instanceof \DateTime) {
141
            $value = $value->format('d.m.Y');
142
        }
143
        return $value;
144
    }
145
}