Completed
Push — development ( 178cf5...deb2fc )
by Torben
13:04
created

ExportService::injectResourceFactory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 4
cts 4
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
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
     * Repository with registrations for the events
31
     *
32
     * @var \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository
33
     */
34
    protected $registrationRepository;
35
36
    /**
37
     * ResourceFactory
38
     *
39
     * @var \TYPO3\CMS\Core\Resource\ResourceFactory
40
     */
41
    protected $resourceFactory = null;
42
43
    /**
44
     * DI for $registrationRepository
45
     *
46
     * @param RegistrationRepository $registrationRepository
47
     */
48
    public function injectRegistrationRepository(
49
        \DERHANSEN\SfEventMgt\Domain\Repository\RegistrationRepository $registrationRepository
50
    ) {
51
        $this->registrationRepository = $registrationRepository;
52
    }
53 2
54
    /**
55 2
     * DI for $resourceFactory
56 2
     *
57 1
     * @param ResourceFactory $resourceFactory
58
     */
59 1
    public function injectResourceFactory(\TYPO3\CMS\Core\Resource\ResourceFactory $resourceFactory)
60 1
    {
61 1
        $this->resourceFactory = $resourceFactory;
62 1
    }
63 1
64 1
    /**
65 1
     * Initiates the CSV downloads for registrations of the given event uid
66
     *
67
     * @param int $eventUid EventUid
68
     * @param array $settings Settings
69
     * @throws Exception RuntimeException
70
     * @return void
71
     */
72
    public function downloadRegistrationsCsv($eventUid, $settings = [])
73
    {
74
        $storage = $this->resourceFactory->getDefaultStorage();
75
        if ($storage === null) {
76 5
            throw new Exception('Could not get the default storage', 1475590001);
77
        }
78 5
        $registrations = $this->exportRegistrationsCsv($eventUid, $settings);
79 5
        $tempFolder = $storage->getFolder('_temp_');
80 5
        $tempFile = $storage->createFile('sf_events_export.csv', $tempFolder);
81 5
        $tempFile->setContents($registrations);
82 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('sf...port.csv', $tempFolder) on line 80 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...
83 5
        $tempFile->delete();
84 5
    }
85 5
86 5
    /**
87 5
     * Returns all Registrations for the given eventUid as a CSV string
88 1
     *
89 1
     * @param int $eventUid EventUid
90
     * @param array $settings Settings
91 5
     * @throws Exception RuntimeException
92 4
     * @return string
93 4
     */
94 4
    public function exportRegistrationsCsv($eventUid, $settings = [])
95 4
    {
96
        $fieldsArray = array_map('trim', explode(',', $settings['fields']));
97
        $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...
98
        $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...
99
                $fieldsArray,
100
                $settings['fieldDelimiter'],
101
                $settings['fieldQuoteCharacter']
102
            ) . chr(10);
103
        foreach ($registrations as $registration) {
104
            $exportedRegistration = [];
105
            foreach ($fieldsArray as $field) {
106 5
                if ($registration->_hasProperty($field)) {
107
                    $exportedRegistration[] = $this->getFieldValue($registration, $field);
108 5
                } else {
109 5
                    throw new Exception('Field ' . $field .
110
                        ' is not a Property of Model Registration, please check your TS configuration', 1475590002);
111
                }
112 5
            }
113
            $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...
114
                    $exportedRegistration,
115
                    $settings['fieldDelimiter'],
116
                    $settings['fieldQuoteCharacter']
117
                ) . chr(10);
118
        }
119
        return $this->prependByteOrderMark($exportedRegistrations, $settings);
120
    }
121
122
    /**
123
     * Prepends Byte Order Mark to exported registrations
124
     *
125
     * @param string $exportedRegistrations
126
     * @param array $settings
127
     * @return string
128
     */
129
    protected function prependByteOrderMark($exportedRegistrations, $settings)
130
    {
131
        if ((bool)$settings['prependBOM']) {
132
            $exportedRegistrations = chr(239) . chr(187) . chr(191) . $exportedRegistrations;
133
        }
134
        return $exportedRegistrations;
135
    }
136
137
    /**
138
     * Returns the requested field from the given registration. If the field is a DateTime object,
139
     * a formatted date string is returned
140
     *
141
     * @param \DERHANSEN\SfEventMgt\Domain\Model\Registration $registration
142
     * @param string $field
143
     * @return string
144
     */
145
    protected function getFieldValue($registration, $field)
146
    {
147
        $value = $registration->_getCleanProperty($field);
148
        if ($value instanceof \DateTime) {
149
            $value = $value->format('d.m.Y');
150
        }
151
        return $value;
152
    }
153
}
154