Completed
Push — development ( 71c1f6...1923e7 )
by Torben
47:02 queued 02:14
created

ExportService::hasWriteAccessToTempFolder()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.3731

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 5
cts 7
cp 0.7143
rs 9.6
c 0
b 0
f 0
cc 4
nc 5
nop 0
crap 4.3731
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\Folder;
16
use TYPO3\CMS\Core\Resource\ResourceFactory;
17
use TYPO3\CMS\Core\Utility\GeneralUtility;
18
19
/**
20
 * Class ExportService
21
 *
22
 * @author Torben Hansen <[email protected]>
23
 */
24
class ExportService
25
{
26
    /**
27
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository
28
     */
29
    protected $registrationRepository = null;
30
31
    /**
32
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\EventRepository
33
     */
34
    protected $eventRepository = null;
35
36
    /**
37
     * ResourceFactory
38
     *
39
     * @var \TYPO3\CMS\Core\Resource\ResourceFactory
40
     */
41
    protected $resourceFactory = null;
42
43
    /**
44
     * @param RegistrationRepository $registrationRepository
45
     */
46
    public function injectRegistrationRepository(
47
        \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository $registrationRepository
48
    ) {
49
        $this->registrationRepository = $registrationRepository;
50
    }
51
52
    /**
53 2
     * @param \DERHANSEN\SfEventMgt\Domain\Repository\EventRepository $eventRepository
54
     */
55 2
    public function injectEventRepository(\DERHANSEN\SfEventMgt\Domain\Repository\EventRepository $eventRepository)
56 2
    {
57 1
        $this->eventRepository = $eventRepository;
58
    }
59 1
60 1
    /**
61 1
     * @param ResourceFactory $resourceFactory
62 1
     */
63 1
    public function injectResourceFactory(\TYPO3\CMS\Core\Resource\ResourceFactory $resourceFactory)
64 1
    {
65 1
        $this->resourceFactory = $resourceFactory;
66
    }
67
68
    /**
69
     * Initiates the CSV downloads for registrations of the given event uid
70
     *
71
     * @param int $eventUid EventUid
72
     * @param array $settings Settings
73
     * @throws Exception RuntimeException
74
     * @return void
75
     */
76 5
    public function downloadRegistrationsCsv($eventUid, $settings = [])
77
    {
78 5
        $tempFolder = $this->getBackendUser()->getDefaultUploadTemporaryFolder();
79 5
        $storage = $this->resourceFactory->getDefaultStorage();
80 5
        if ($storage === null || $tempFolder === null) {
81 5
            throw new Exception('Could not get the default storage or default upload temp folder', 1475590001);
82 5
        }
83 5
        $registrations = $this->exportRegistrationsCsv($eventUid, $settings);
84 5
        $tempFilename = md5($eventUid . '_sf_events_export_' . time()) . '.csv';
85 5
        $tempFile = $storage->createFile($tempFilename, $tempFolder);
86 5
        $tempFile->setContents($registrations);
87 5
        $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 85 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...
88 1
        $tempFile->delete();
89 1
    }
90
91 5
   /**
92 4
     * Returns all Registrations for the given eventUid as a CSV string
93 4
     *
94 4
     * @param int $eventUid EventUid
95 4
     * @param array $settings Settings
96
     * @throws Exception RuntimeException
97
     * @return string
98
     */
99
    public function exportRegistrationsCsv($eventUid, $settings = [])
100
    {
101
        $hasRegistrationFields = false;
102
        $registrationFieldData = [];
103
        $fieldsArray = array_map('trim', explode(',', $settings['fields']));
104
105
        if (in_array('registration_fields', $fieldsArray)) {
106 5
            $hasRegistrationFields = true;
107
            $registrationFieldData = $this->getRegistrationFieldData($eventUid);
108 5
            $fieldsArray = array_diff($fieldsArray, ['registration_fields']);
109 5
        }
110
        $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...
111
        $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...
112 5
            array_merge($fieldsArray, $registrationFieldData),
113
            $settings['fieldDelimiter'],
114
            $settings['fieldQuoteCharacter']
115
        ) . chr(10);
116
        /** @var Registration $registration */
117
        foreach ($registrations as $registration) {
118
            $exportedRegistration = [];
119
            foreach ($fieldsArray as $field) {
120
                if ($registration->_hasProperty($field)) {
121
                    $exportedRegistration[] = $this->getFieldValue($registration, $field);
122
                } else {
123
                    throw new Exception('Field ' . $field .
124
                        ' is not a Property of Model Registration, please check your TS configuration', 1475590002);
125
                }
126
            }
127
            if ($hasRegistrationFields) {
128
                $exportedRegistration = array_merge(
129
                    $exportedRegistration,
130
                    $this->getRegistrationFieldValues($registration, $registrationFieldData)
131
                );
132
            }
133
            $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...
134
                $exportedRegistration,
135
                $settings['fieldDelimiter'],
136
                $settings['fieldQuoteCharacter']
137
            ) . chr(10);
138
        }
139
140
        return $this->prependByteOrderMark($exportedRegistrations, $settings);
141
    }
142
143
    /**
144
     * Returns an array with fieldvalues for the given registration
145
     *
146
     * @param Registration $registration
147
     * @param array $registrationFieldData
148
     * @return array
149
     */
150
    protected function getRegistrationFieldValues($registration, $registrationFieldData)
151
    {
152
        $result = [];
153
        $registrationFieldValues = [];
154
        /** @var Registration\FieldValue $fieldValue */
155
        foreach ($registration->getFieldValues() as $fieldValue) {
156
            $registrationFieldValues[$fieldValue->getField()->getUid()] = $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 $value;
219
    }
220
221
    /**
222
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
223
     */
224
    protected function getBackendUser()
225
    {
226
        return $GLOBALS['BE_USER'];
227
    }
228
}
229