Completed
Push — master ( c18e86...b01b7f )
by Torben
04:02
created

ExportService   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 217
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 94.29%

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 8
dl 0
loc 217
ccs 33
cts 35
cp 0.9429
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getRegistrationFieldData() 0 11 2
A prependByteOrderMark() 0 8 2
A getFieldValue() 0 9 2
A injectRegistrationRepository() 0 5 1
A injectEventRepository() 0 4 1
A injectResourceFactory() 0 4 1
A downloadRegistrationsCsv() 0 14 3
B exportRegistrationsCsv() 0 43 6
A getRegistrationFieldValues() 0 19 4
A replaceLineBreaks() 0 4 1
A getBackendUser() 0 4 1
1
<?php
2
namespace DERHANSEN\SfEventMgt\Service;
3
4
/*
5
 * This file is part of the Extension "sf_event_mgt" for TYPO3 CMS.
6
 *
7
 * For the full copyright and license information, please read the
8
 * LICENSE.txt file that was distributed with this source code.
9
 */
10
11
use DERHANSEN\SfEventMgt\Domain\Model\Event;
12
use DERHANSEN\SfEventMgt\Domain\Model\Registration;
13
use DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository;
14
use DERHANSEN\SfEventMgt\Exception;
15
use TYPO3\CMS\Core\Resource\ResourceFactory;
16
use TYPO3\CMS\Core\Utility\CsvUtility;
17
18
/**
19
 * Class ExportService
20
 *
21
 * @author Torben Hansen <[email protected]>
22
 */
23
class ExportService
24
{
25
    /**
26
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository
27
     */
28
    protected $registrationRepository = null;
29
30
    /**
31
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\EventRepository
32
     */
33
    protected $eventRepository = null;
34
35
    /**
36
     * ResourceFactory
37
     *
38
     * @var \TYPO3\CMS\Core\Resource\ResourceFactory
39
     */
40
    protected $resourceFactory = null;
41
42
    /**
43
     * @param RegistrationRepository $registrationRepository
44
     */
45
    public function injectRegistrationRepository(
46
        \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository $registrationRepository
47
    ) {
48
        $this->registrationRepository = $registrationRepository;
49
    }
50
51
    /**
52
     * @param \DERHANSEN\SfEventMgt\Domain\Repository\EventRepository $eventRepository
53 4
     */
54
    public function injectEventRepository(\DERHANSEN\SfEventMgt\Domain\Repository\EventRepository $eventRepository)
55 4
    {
56 4
        $this->eventRepository = $eventRepository;
57 2
    }
58
59 2
    /**
60 2
     * @param ResourceFactory $resourceFactory
61 2
     */
62 2
    public function injectResourceFactory(\TYPO3\CMS\Core\Resource\ResourceFactory $resourceFactory)
63 2
    {
64 2
        $this->resourceFactory = $resourceFactory;
65 2
    }
66
67
    /**
68
     * Initiates the CSV downloads for registrations of the given event uid
69
     *
70
     * @param int $eventUid EventUid
71
     * @param array $settings Settings
72
     * @throws Exception RuntimeException
73
     * @return void
74
     */
75
    public function downloadRegistrationsCsv($eventUid, $settings = [])
76 10
    {
77
        $tempFolder = $this->getBackendUser()->getDefaultUploadTemporaryFolder();
78 10
        $storage = $this->resourceFactory->getDefaultStorage();
79 10
        if ($storage === null || $tempFolder === null) {
80 10
            throw new Exception('Could not get the default storage or default upload temp folder', 1475590001);
81 10
        }
82 10
        $registrations = $this->exportRegistrationsCsv($eventUid, $settings);
83 10
        $tempFilename = md5($eventUid . '_sf_events_export_' . time()) . '.csv';
84 10
        $tempFile = $storage->createFile($tempFilename, $tempFolder);
85 10
        $tempFile->setContents($registrations);
86 10
        $storage->dumpFileContents($tempFile, true, 'registrations_' . date('dmY_His') . '.csv');
0 ignored issues
show
Bug introduced by
It seems like $tempFile defined by $storage->createFile($tempFilename, $tempFolder) on line 84 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...
Deprecated Code introduced by
The method TYPO3\CMS\Core\Resource\...age::dumpFileContents() has been deprecated with message: since TYPO3 v9.5, will be removed in TYPO3 v10.0.

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...
87 10
        $tempFile->delete();
88 2
    }
89 2
90
    /**
91 10
     * Returns all Registrations for the given eventUid as a CSV string
92 8
     *
93 8
     * @param int $eventUid EventUid
94 8
     * @param array $settings Settings
95 8
     * @throws Exception RuntimeException
96
     * @return string
97
     */
98
    public function exportRegistrationsCsv($eventUid, $settings = [])
99
    {
100
        $hasRegistrationFields = false;
101
        $registrationFieldData = [];
102
        $fieldsArray = array_map('trim', explode(',', $settings['fields']));
103
104
        if (in_array('registration_fields', $fieldsArray)) {
105
            $hasRegistrationFields = true;
106 10
            $registrationFieldData = $this->getRegistrationFieldData($eventUid);
107
            $fieldsArray = array_diff($fieldsArray, ['registration_fields']);
108 10
        }
109 10
        $registrations = $this->registrationRepository->findByEvent($eventUid);
0 ignored issues
show
Bug introduced by
The method findByEvent() does not exist on DERHANSEN\SfEventMgt\Dom...\RegistrationRepository. Did you maybe mean findByEventAndWaitlist()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
110
        $exportedRegistrations = CsvUtility::csvValues(
111
            array_merge($fieldsArray, $registrationFieldData),
112 10
            $settings['fieldDelimiter'],
113
            $settings['fieldQuoteCharacter']
114
        ) . chr(10);
115
        /** @var Registration $registration */
116
        foreach ($registrations as $registration) {
117
            $exportedRegistration = [];
118
            foreach ($fieldsArray as $field) {
119
                if ($registration->_hasProperty($field)) {
120
                    $exportedRegistration[] = $this->getFieldValue($registration, $field);
121
                } else {
122
                    throw new Exception('Field ' . $field .
123
                        ' is not a Property of Model Registration, please check your TS configuration', 1475590002);
124
                }
125
            }
126
            if ($hasRegistrationFields) {
127
                $exportedRegistration = array_merge(
128
                    $exportedRegistration,
129
                    $this->getRegistrationFieldValues($registration, $registrationFieldData)
130
                );
131
            }
132
            $exportedRegistrations .= CsvUtility::csvValues(
133
                $exportedRegistration,
134
                $settings['fieldDelimiter'],
135
                $settings['fieldQuoteCharacter']
136
            ) . chr(10);
137
        }
138
139
        return $this->prependByteOrderMark($exportedRegistrations, $settings);
140
    }
141
142
    /**
143
     * Returns an array with fieldvalues for the given registration
144
     *
145
     * @param Registration $registration
146
     * @param array $registrationFieldData
147
     * @return array
148
     */
149
    protected function getRegistrationFieldValues($registration, $registrationFieldData)
150
    {
151
        $result = [];
152
        $registrationFieldValues = [];
153
        /** @var Registration\FieldValue $fieldValue */
154
        foreach ($registration->getFieldValues() as $fieldValue) {
155
            $registrationFieldValues[$fieldValue->getField()->getUid()] =
156
                $this->replaceLineBreaks($fieldValue->getValueForCsvExport());
157
        }
158
        foreach ($registrationFieldData as $fieldUid => $fieldTitle) {
159
            if (isset($registrationFieldValues[$fieldUid])) {
160
                $result[] = $registrationFieldValues[$fieldUid];
161
            } else {
162
                $result[] = '';
163
            }
164
        }
165
166
        return $result;
167
    }
168
169
    /**
170
     * Returns an array of registration field uids and title
171
     *
172
     * @param int $eventUid
173
     * @return array
174
     */
175
    protected function getRegistrationFieldData($eventUid)
176
    {
177
        $result = [];
178
        /** @var Event $event */
179
        $event = $this->eventRepository->findByUid($eventUid);
180
        if ($event) {
181
            $result = $event->getRegistrationFieldUidsWithTitle();
182
        }
183
184
        return $result;
185
    }
186
187
    /**
188
     * Prepends Byte Order Mark to exported registrations
189
     *
190
     * @param string $exportedRegistrations
191
     * @param array $settings
192
     * @return string
193
     */
194
    protected function prependByteOrderMark($exportedRegistrations, $settings)
195
    {
196
        if ((bool)$settings['prependBOM']) {
197
            $exportedRegistrations = chr(239) . chr(187) . chr(191) . $exportedRegistrations;
198
        }
199
200
        return $exportedRegistrations;
201
    }
202
203
    /**
204
     * Returns the requested field from the given registration. If the field is a DateTime object,
205
     * a formatted date string is returned
206
     *
207
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration
208
     * @param string $field
209
     * @return string
210
     */
211
    protected function getFieldValue($registration, $field)
212
    {
213
        $value = $registration->_getCleanProperty($field);
214
        if ($value instanceof \DateTime) {
215
            $value = $value->format('d.m.Y');
216
        }
217
218
        return $this->replaceLineBreaks($value);
219
    }
220
221
    /**
222
     * Replaces all line breaks with a space
223
     *
224
     * @param mixed $value
225
     * @return mixed
226
     */
227
    protected function replaceLineBreaks($value)
228
    {
229
        return str_replace(["\r\n", "\r", "\n"], ' ', $value);
230
    }
231
232
    /**
233
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
234
     */
235
    protected function getBackendUser()
236
    {
237
        return $GLOBALS['BE_USER'];
238
    }
239
}
240