Passed
Push — develop ( e47c87...44bf39 )
by Torben
13:23
created

ExportService::getBackendUser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Extension "sf_event_mgt" for TYPO3 CMS.
7
 *
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 */
11
12
namespace DERHANSEN\SfEventMgt\Service;
13
14
use DateTime;
15
use DERHANSEN\SfEventMgt\Domain\Model\Event;
16
use DERHANSEN\SfEventMgt\Domain\Model\Registration;
17
use DERHANSEN\SfEventMgt\Domain\Repository\EventRepository;
18
use DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository;
19
use TYPO3\CMS\Core\Utility\CsvUtility;
20
use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
21
22
class ExportService
23
{
24
    protected RegistrationRepository $registrationRepository;
25
    protected EventRepository $eventRepository;
26
27
    public function __construct(RegistrationRepository $registrationRepository, EventRepository $eventRepository)
28
    {
29
        $this->registrationRepository = $registrationRepository;
30
        $this->eventRepository = $eventRepository;
31
    }
32
33
    /**
34
     * Initiates the CSV downloads for registrations of the given event uid
35
     */
36
    public function downloadRegistrationsCsv(int $eventUid, array $settings = []): void
37
    {
38
        $content = $this->exportRegistrationsCsv($eventUid, $settings);
39
        header('Content-Disposition: attachment; filename="event_' . $eventUid . '_reg_' . date('dmY_His') . '.csv"');
40
        header('Content-Type: text/csv');
41
        header('Content-Length: ' . strlen($content));
42
        header('Expires: 0');
43
        header('Cache-Control: must-revalidate');
44
        header('Pragma: no-cache');
45
        echo $content;
46
    }
47
48
    /**
49
     * Returns all Registrations for the given eventUid as a CSV string
50
     */
51
    public function exportRegistrationsCsv(int $eventUid, array $settings = []): string
52
    {
53
        $hasRegistrationFields = false;
54
        $registrationFieldData = [];
55
        $fieldsArray = array_map('trim', explode(',', ($settings['fields'] ?? '')));
56
57
        if (in_array('registration_fields', $fieldsArray)) {
58
            $hasRegistrationFields = true;
59
            $registrationFieldData = $this->getRegistrationFieldData($eventUid);
60
            $fieldsArray = array_diff($fieldsArray, ['registration_fields']);
61
        }
62
        $registrations = $this->registrationRepository->findByEvent($eventUid);
0 ignored issues
show
Deprecated Code introduced by
The function DERHANSEN\SfEventMgt\Dom...ionRepository::__call() has been deprecated: since v12, will be removed in v14, use {@see findBy}, {@see findOneBy} and {@see count} instead ( Ignorable by Annotation )

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

62
        $registrations = /** @scrutinizer ignore-deprecated */ $this->registrationRepository->findByEvent($eventUid);

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

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

Loading history...
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

62
        /** @scrutinizer ignore-call */ 
63
        $registrations = $this->registrationRepository->findByEvent($eventUid);
Loading history...
63
        $exportedRegistrations = CsvUtility::csvValues(
64
            array_merge($fieldsArray, $registrationFieldData),
65
            $settings['fieldDelimiter'] ?? ',',
66
            $settings['fieldQuoteCharacter'] ?? '"'
67
        ) . chr(10);
68
        /** @var Registration $registration */
69
        foreach ($registrations as $registration) {
70
            $exportedRegistration = [];
71
            foreach ($fieldsArray as $field) {
72
                $exportedRegistration[] = $this->getFieldValue($registration, $field, $settings);
73
            }
74
            if ($hasRegistrationFields) {
75
                $exportedRegistration = array_merge(
76
                    $exportedRegistration,
77
                    $this->getRegistrationFieldValues($registration, $registrationFieldData)
78
                );
79
            }
80
            $exportedRegistrations .= CsvUtility::csvValues(
81
                $exportedRegistration,
82
                $settings['fieldDelimiter'] ?? ',',
83
                $settings['fieldQuoteCharacter'] ?? '"'
84
            ) . chr(10);
85
        }
86
87
        return $this->prependByteOrderMark($exportedRegistrations, $settings);
88
    }
89
90
    /**
91
     * Returns an array with fieldvalues for the given registration
92
     */
93
    protected function getRegistrationFieldValues(Registration $registration, array $registrationFieldData): array
94
    {
95
        $result = [];
96
        $registrationFieldValues = [];
97
        /** @var Registration\FieldValue $fieldValue */
98
        foreach ($registration->getFieldValues() as $fieldValue) {
99
            $field = $fieldValue->getField();
100
            if ($field !== null) {
101
                $registrationFieldValues[$field->getUid()] =
102
                    $this->replaceLineBreaks($fieldValue->getValueForCsvExport());
103
            }
104
        }
105
        foreach ($registrationFieldData as $fieldUid => $fieldTitle) {
106
            if (isset($registrationFieldValues[$fieldUid])) {
107
                $result[] = $registrationFieldValues[$fieldUid];
108
            } else {
109
                $result[] = '';
110
            }
111
        }
112
113
        return $result;
114
    }
115
116
    /**
117
     * Returns an array of registration field uids and title
118
     */
119
    protected function getRegistrationFieldData(int $eventUid): array
120
    {
121
        $result = [];
122
        /** @var Event $event */
123
        $event = $this->eventRepository->findByUid($eventUid);
124
        if ($event !== null) {
125
            $result = $event->getRegistrationFieldUidsWithTitle();
126
        }
127
128
        return $result;
129
    }
130
131
    /**
132
     * Prepends Byte Order Mark to exported registrations
133
     */
134
    protected function prependByteOrderMark(string $exportedRegistrations, array $settings): string
135
    {
136
        if ((bool)($settings['prependBOM'] ??  false)) {
137
            $exportedRegistrations = chr(239) . chr(187) . chr(191) . $exportedRegistrations;
138
        }
139
140
        return $exportedRegistrations;
141
    }
142
143
    /**
144
     * Returns the requested field from the given registration. If the field is a DateTime object,
145
     * a formatted date string is returned
146
     */
147
    protected function getFieldValue(Registration $registration, string $field, array $settings): string
148
    {
149
        $value = ObjectAccess::getPropertyPath($registration, $field);
150
        if ($value instanceof DateTime) {
151
            $dateFormat = $settings['dateFieldFormat'] ?? 'd.m.Y';
152
            $value = $value->format($dateFormat);
153
        }
154
155
        return $this->replaceLineBreaks((string)$value);
156
    }
157
158
    /**
159
     * Replaces all line breaks with a space
160
     */
161
    protected function replaceLineBreaks(string $value): string
162
    {
163
        return str_replace(["\r\n", "\r", "\n"], ' ', $value);
164
    }
165
}
166