Completed
Pull Request — master (#2)
by
unknown
22:32 queued 07:27
created

ActivityLogController::cgetAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of Sulu.
5
 *
6
 * (c) MASSIVE ART WebServices GmbH
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Sulu\Bundle\ActivityLogBundle\Controller;
13
14
use Exception;
15
use FOS\RestBundle\Controller\Annotations\Get;
16
use FOS\RestBundle\Controller\FOSRestController;
17
use FOS\RestBundle\Routing\ClassResourceInterface;
18
use Sulu\Component\ActivityLog\ActivityLogger;
19
use Sulu\Component\Rest\Exception\EntityNotFoundException;
20
use Sulu\Component\Rest\ListBuilder\FieldDescriptor;
21
use Sulu\Component\Rest\ListBuilder\ListRepresentation;
22
use Symfony\Component\HttpFoundation\Request;
23
use Symfony\Component\HttpFoundation\Response;
24
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
25
26
class ActivityLogController extends FOSRestController implements ClassResourceInterface
27
{
28
    const EXPORT_COLUMN_DELIMITER = ';';
29
    const EXPORT_FILENAME = 'acitivity-log-export';
30
31
    /**
32
     * Returns all fields that can be used by list.
33
     *
34
     * @Get("activity-log/fields")
35
     *
36
     * @param Request $request
37
     *
38
     * @return mixed
39
     */
40
    public function getFieldsAction(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
41
    {
42
        // default contacts list
43
        return $this->handleView(
44
            $this->view(
0 ignored issues
show
Documentation introduced by
$this->view(array_values...eldDescriptors()), 200) is of type this<Sulu\Bundle\Activit...\ActivityLogController>, but the function expects a object<FOS\RestBundle\View\View>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
45
                array_values(
46
                    $this->getFieldDescriptors()
47
                ),
48
                200
49
            )
50
        );
51
    }
52
53
    /**
54
     * Shows all activity-log-items.
55
     *
56
     * @param Request $request
57
     *
58
     * @Get("activity-log")
59
     *
60
     * @return \Symfony\Component\HttpFoundation\Response
61
     */
62
    public function cgetAction(Request $request)
63
    {
64
        $list = $this->getActivityLogs($request);
65
66
        $view = $this->view($list, 200);
67
68
        return $this->handleView($view);
0 ignored issues
show
Documentation introduced by
$view is of type this<Sulu\Bundle\Activit...\ActivityLogController>, but the function expects a object<FOS\RestBundle\View\View>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
69
    }
70
71
    /**
72
     * returns datagrid list of activity-log for export.
73
     *
74
     * @param Request $request
75
     *
76
     * @Get("activity-log/export")
77
     *
78
     * @return Response
79
     */
80
    public function getActivityLogExportAction(Request $request)
81
    {
82
        try {
83
            $list = $this->getActivityLogs($request);
84
85
            return $this->generateCsvResponse($this->listToCsv($list, self::EXPORT_COLUMN_DELIMITER));
86
        } catch (Exception $e) {
87
            $view = $this->view([$e->getMessage()], 400);
88
        }
89
90
        return $this->handleView($view);
0 ignored issues
show
Documentation introduced by
$view is of type this<Sulu\Bundle\Activit...\ActivityLogController>, but the function expects a object<FOS\RestBundle\View\View>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
91
    }
92
93
    /**
94
     * Create field-descriptor array.
95
     *
96
     * @return FieldDescriptor[]
97
     */
98
    protected function getFieldDescriptors()
99
    {
100
        return [
101
            'uuid' => new FieldDescriptor('id', 'public.id', true, false),
102
            'data' => new FieldDescriptor('data', 'public.data', false, true),
103
        ];
104
    }
105
106
    /**
107
     * returns view of files.
108
     *
109
     * @param Request $request
110
     *
111
     * @throws EntityNotFoundException
112
     *
113
     * @return ListRepresentation
114
     */
115
    protected function getActivityLogs(Request $request)
116
    {
117
        $restHelper = $this->get('sulu_core.list_rest_helper');
118
119
        /** @var ActivityLogger $activityLogger */
120
        $activityLogger = $this->get('sulu_activity_log.activity_logger');
121
122
        $page = (int) $restHelper->getPage();
123
        $limit = (int) $restHelper->getLimit();
124
        $sortColumn = $restHelper->getSortColumn();
125
        $sortOrder = $restHelper->getSortOrder();
126
        $searchPattern = $restHelper->getSearchPattern();
127
        $searchFields = $restHelper->getSearchFields();
128
129
        $list = $activityLogger->findAllWithSearch(
0 ignored issues
show
Bug introduced by
The method findAllWithSearch() does not exist on Sulu\Component\ActivityLog\ActivityLogger. Did you maybe mean findAll()?

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...
130
            $searchPattern,
131
            $searchFields,
132
            $page,
133
            $limit,
134
            $sortColumn,
135
            $sortOrder
136
        );
137
138
        $total = $activityLogger->getCountForAllWithSearch($searchPattern, $searchFields);
0 ignored issues
show
Bug introduced by
The method getCountForAllWithSearch() does not seem to exist on object<Sulu\Component\ActivityLog\ActivityLogger>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
139
140
        $list = array_values($list);
141
142
        $list = new ListRepresentation(
143
            $list,
144
            'activity-log-items',
145
            'get_activity_logs',
146
            $request->query->all(),
147
            $page,
148
            $limit,
149
            $total
150
        );
151
152
        return $list;
153
    }
154
155
    /**
156
     * @param ListRepresentation $list
157
     * @param string $delimiter
158
     *
159
     * @return string
160
     */
161
    protected function listToCsv($list, $delimiter)
162
    {
163
        $data = $list->getInline()->getResources();
164
        $csv = '';
165
        $headers = array_keys(reset($data));
166
        foreach ($headers as $header) {
167
            $csv .= $header . $delimiter;
168
        }
169
        $csv = rtrim($csv, $delimiter) . PHP_EOL;
170
171
        // iterate over data array
172
        foreach ($data as $dataLine) {
173
            $csv .= $this->addLine($dataLine, $delimiter);
174
        }
175
176
        return $csv;
177
    }
178
179
    /**
180
     * @param array $dataLine
181
     * @param string $delimiter
182
     *
183
     * @return string
184
     */
185
    protected function addLine($dataLine, $delimiter)
186
    {
187
        $csvLine = '';
188
        foreach ($dataLine as $dataField) {
189
            if ($dataField instanceof DateTime) {
0 ignored issues
show
Bug introduced by
The class Sulu\Bundle\ActivityLogBundle\Controller\DateTime does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
190
                $csvLine .= $dataField->format(DateTime::ISO8601);
191
            } elseif (is_scalar($dataField)) {
192
                $csvLine .= $dataField;
193
            }
194
            $csvLine .= $delimiter;
195
        }
196
        $csvLine = rtrim($csvLine, $delimiter) . PHP_EOL;
197
198
        return $csvLine;
199
    }
200
201
    /**
202
     * @param string $csv
203
     *
204
     * @return Response
205
     */
206
    protected function generateCsvResponse($csv)
207
    {
208
        $response = new Response();
209
        $response->setContent($csv);
210
211
        $name = self::EXPORT_FILENAME . '-' . date('Ymd') . '.csv';
212
        $disponent = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $name);
213
        $response->headers->set('Content-Disposition', $disponent);
214
        $response->headers->set('Content-Type', 'text/csv');
215
216
        return $response;
217
    }
218
}
219