Passed
Push — master ( da5c3a...138f6a )
by Torben
132:09 queued 128:49
created

ExportService::exportRegistrationsCsv()   A

Complexity

Conditions 5
Paths 10

Size

Total Lines 37
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 5
eloc 27
nc 10
nop 2
dl 0
loc 37
ccs 18
cts 18
cp 1
crap 5
rs 9.1768
c 2
b 1
f 0
1
<?php
2
3
/*
4
 * This file is part of the Extension "sf_event_mgt" for TYPO3 CMS.
5
 *
6
 * For the full copyright and license information, please read the
7
 * LICENSE.txt file that was distributed with this source code.
8
 */
9
10
namespace DERHANSEN\SfEventMgt\Service;
11
12
use DERHANSEN\SfEventMgt\Domain\Model\Event;
13
use DERHANSEN\SfEventMgt\Domain\Model\Registration;
14
use DERHANSEN\SfEventMgt\Domain\Repository\EventRepository;
15
use DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository;
16
use DERHANSEN\SfEventMgt\Exception;
17
use TYPO3\CMS\Core\Utility\CsvUtility;
18
use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
19
20
/**
21
 * Class ExportService
22
 */
23
class ExportService
24
{
25
    /**
26
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository
27
     */
28
    protected $registrationRepository;
29
30
    /**
31
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\EventRepository
32
     */
33
    protected $eventRepository;
34
35
    public function __construct(RegistrationRepository $registrationRepository, EventRepository $eventRepository)
36
    {
37
        $this->registrationRepository = $registrationRepository;
38
        $this->eventRepository = $eventRepository;
39
    }
40
41
    /**
42
     * Initiates the CSV downloads for registrations of the given event uid
43
     *
44
     * @param int $eventUid EventUid
45
     * @param array $settings Settings
46
     * @throws Exception RuntimeException
47
     */
48
    public function downloadRegistrationsCsv($eventUid, $settings = [])
49
    {
50
        $content = $this->exportRegistrationsCsv($eventUid, $settings);
51
        header('Content-Disposition: attachment; filename="event_' . $eventUid . '_reg_' . date('dmY_His') . '.csv"');
52
        header('Content-Type: text/csv');
53 4
        header('Content-Length: ' . strlen($content));
54
        header('Expires: 0');
55 4
        header('Cache-Control: must-revalidate');
56 4
        header('Pragma: no-cache');
57 2
        echo $content;
58
    }
59 2
60 2
    /**
61 2
     * Returns all Registrations for the given eventUid as a CSV string
62 2
     *
63 2
     * @param int $eventUid EventUid
64 2
     * @param array $settings Settings
65 2
     * @throws Exception RuntimeException
66
     * @return string
67
     */
68
    public function exportRegistrationsCsv($eventUid, $settings = [])
69
    {
70
        $hasRegistrationFields = false;
71
        $registrationFieldData = [];
72
        $fieldsArray = array_map('trim', explode(',', $settings['fields']));
73
74
        if (in_array('registration_fields', $fieldsArray)) {
75
            $hasRegistrationFields = true;
76 10
            $registrationFieldData = $this->getRegistrationFieldData($eventUid);
77
            $fieldsArray = array_diff($fieldsArray, ['registration_fields']);
78 10
        }
79 10
        $registrations = $this->registrationRepository->findByEvent($eventUid);
0 ignored issues
show
Bug introduced by
The method findByEvent() does not exist on DERHANSEN\SfEventMgt\Dom...\RegistrationRepository. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

79
        /** @scrutinizer ignore-call */ 
80
        $registrations = $this->registrationRepository->findByEvent($eventUid);
Loading history...
80 10
        $exportedRegistrations = CsvUtility::csvValues(
81 10
            array_merge($fieldsArray, $registrationFieldData),
82 10
            $settings['fieldDelimiter'],
83 10
            $settings['fieldQuoteCharacter']
84 10
        ) . chr(10);
85 10
        /** @var Registration $registration */
86 10
        foreach ($registrations as $registration) {
87 10
            $exportedRegistration = [];
88 2
            foreach ($fieldsArray as $field) {
89 2
                $exportedRegistration[] = $this->getFieldValue($registration, $field);
90
            }
91 10
            if ($hasRegistrationFields) {
92 8
                $exportedRegistration = array_merge(
93 8
                    $exportedRegistration,
94 8
                    $this->getRegistrationFieldValues($registration, $registrationFieldData)
95 8
                );
96
            }
97
            $exportedRegistrations .= CsvUtility::csvValues(
98
                $exportedRegistration,
99
                $settings['fieldDelimiter'],
100
                $settings['fieldQuoteCharacter']
101
            ) . chr(10);
102
        }
103
104
        return $this->prependByteOrderMark($exportedRegistrations, $settings);
105
    }
106 10
107
    /**
108 10
     * Returns an array with fieldvalues for the given registration
109 10
     *
110
     * @param Registration $registration
111
     * @param array $registrationFieldData
112 10
     * @return array
113
     */
114
    protected function getRegistrationFieldValues($registration, $registrationFieldData)
115
    {
116
        $result = [];
117
        $registrationFieldValues = [];
118
        /** @var Registration\FieldValue $fieldValue */
119
        foreach ($registration->getFieldValues() as $fieldValue) {
120
            $field = $fieldValue->getField();
0 ignored issues
show
Bug introduced by
The method getField() does not exist on TYPO3\CMS\Extbase\Domain...t\DomainObjectInterface. It seems like you code against a sub-type of TYPO3\CMS\Extbase\Domain...t\DomainObjectInterface such as DERHANSEN\SfEventMgt\Dom...Registration\FieldValue. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

120
            /** @scrutinizer ignore-call */ 
121
            $field = $fieldValue->getField();
Loading history...
121
            if ($field) {
122
                $registrationFieldValues[$field->getUid()] =
123
                    $this->replaceLineBreaks($fieldValue->getValueForCsvExport());
0 ignored issues
show
Bug introduced by
The method getValueForCsvExport() does not exist on TYPO3\CMS\Extbase\Domain...t\DomainObjectInterface. It seems like you code against a sub-type of TYPO3\CMS\Extbase\Domain...t\DomainObjectInterface such as DERHANSEN\SfEventMgt\Dom...Registration\FieldValue. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

123
                    $this->replaceLineBreaks($fieldValue->/** @scrutinizer ignore-call */ getValueForCsvExport());
Loading history...
124
            }
125
        }
126
        foreach ($registrationFieldData as $fieldUid => $fieldTitle) {
127
            if (isset($registrationFieldValues[$fieldUid])) {
128
                $result[] = $registrationFieldValues[$fieldUid];
129
            } else {
130
                $result[] = '';
131
            }
132
        }
133
134
        return $result;
135
    }
136
137
    /**
138
     * Returns an array of registration field uids and title
139
     *
140
     * @param int $eventUid
141
     * @return array
142
     */
143
    protected function getRegistrationFieldData($eventUid)
144
    {
145
        $result = [];
146
        /** @var Event $event */
147
        $event = $this->eventRepository->findByUid($eventUid);
148
        if ($event) {
0 ignored issues
show
introduced by
$event is of type DERHANSEN\SfEventMgt\Domain\Model\Event, thus it always evaluated to true.
Loading history...
149
            $result = $event->getRegistrationFieldUidsWithTitle();
150
        }
151
152
        return $result;
153
    }
154
155
    /**
156
     * Prepends Byte Order Mark to exported registrations
157
     *
158
     * @param string $exportedRegistrations
159
     * @param array $settings
160
     * @return string
161
     */
162
    protected function prependByteOrderMark($exportedRegistrations, $settings)
163
    {
164
        if ((bool)$settings['prependBOM']) {
165
            $exportedRegistrations = chr(239) . chr(187) . chr(191) . $exportedRegistrations;
166
        }
167
168
        return $exportedRegistrations;
169
    }
170
171
    /**
172
     * Returns the requested field from the given registration. If the field is a DateTime object,
173
     * a formatted date string is returned
174
     *
175
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration
176
     * @param string $field
177
     * @return string
178
     */
179
    protected function getFieldValue($registration, $field)
180
    {
181
        $value = ObjectAccess::getPropertyPath($registration, $field);
182
        if ($value instanceof \DateTime) {
183
            $value = $value->format('d.m.Y');
184
        }
185
186
        return $this->replaceLineBreaks($value);
187
    }
188
189
    /**
190
     * Replaces all line breaks with a space
191
     *
192
     * @param mixed $value
193
     * @return mixed
194
     */
195
    protected function replaceLineBreaks($value)
196
    {
197
        return str_replace(["\r\n", "\r", "\n"], ' ', $value);
198
    }
199
200
    /**
201
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
202
     */
203
    protected function getBackendUser()
204
    {
205
        return $GLOBALS['BE_USER'];
206
    }
207
}
208