Completed
Pull Request — master (#2)
by
unknown
11:56
created

ActivityLogController::getFieldsAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
rs 9.4285
cc 1
eloc 6
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 Sulu\Component\Rest\ListBuilder\ListRestHelper;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\HttpFoundation\Response;
25
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
26
27
class ActivityLogController extends FOSRestController implements ClassResourceInterface
28
{
29
30
    const EXPORT_COLUMN_DELIMITER = ';';
31
    const EXPORT_FILENAME = 'acitivity-log-export';
32
33
    /**
34
     * Returns all fields that can be used by list.
35
     *
36
     * @Get("activity-log/fields")
37
     *
38
     * @param Request $request
39
     *
40
     * @return mixed
41
     */
42
    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...
43
    {
44
        // default contacts list
45
        return $this->handleView(
46
            $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...
47
                array_values(
48
                    $this->getFieldDescriptors()
49
                ),
50
                200
51
            )
52
        );
53
    }
54
55
    /**
56
     * Shows all activity-log-items
57
     *
58
     * @param Request $request
59
     *
60
     * @Get("activity-log")
61
     *
62
     * @return \Symfony\Component\HttpFoundation\Response
63
     */
64
    public function cgetAction(Request $request)
65
    {
66
        $list = $this->getActivityLogs($request);
67
68
        $view = $this->view($list, 200);
69
70
        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...
71
    }
72
73
    /**
74
     * returns datagrid list of activity-log for export
75
     *
76
     * @param Request $request
77
     *
78
     * @Get("activity-log/export")
79
     *
80
     * @return Response
81
     */
82
    public function getActivityLogExportAction(Request $request)
83
    {
84
        try {
85
            $list = $this->getActivityLogs($request);
86
87
            return $this->generateCsvResponse($this->listToCsv($list, self::EXPORT_COLUMN_DELIMITER));
88
        } catch (Exception $e) {
89
            $view = $this->view(array($e->getMessage()), 400);
90
        }
91
92
        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...
93
    }
94
95
    /**
96
     * Create field-descriptor array.
97
     *
98
     * @return FieldDescriptor[]
99
     */
100
    protected function getFieldDescriptors()
101
    {
102
        return [
103
            'uuid' => new FieldDescriptor('id', 'public.id', true, false),
104
            'data' => new FieldDescriptor('data', 'public.data', false, true),
105
        ];
106
    }
107
108
    /**
109
     * returns view of files
110
     *
111
     * @param Request $request
112
     *
113
     * @throws EntityNotFoundException
114
     *
115
     * @return ListRepresentation
116
     */
117
    protected function getActivityLogs(Request $request)
118
    {
119
        $restHelper = $this->get('sulu_core.list_rest_helper');
120
121
        /** @var ActivityLogger $activityLogger */
122
        $activityLogger = $this->get('sulu_activity_log.activity_logger');
123
124
        $page = (int)$restHelper->getPage();
125
        $limit = (int)$restHelper->getLimit();
126
        $sortColumn = $restHelper->getSortColumn();
127
        $sortOrder = $restHelper->getSortOrder();
128
        $searchPattern = $restHelper->getSearchPattern();
129
        $searchFields = $restHelper->getSearchFields();
130
131
        $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...
132
            $searchPattern,
133
            $searchFields,
134
            $page,
135
            $limit,
136
            $sortColumn,
137
            $sortOrder
138
        );
139
140
        $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...
141
142
        $list = array_values($list);
143
144
        $list = new ListRepresentation(
145
            $list,
146
            'activity-log-items',
147
            'get_activity_logs',
148
            $request->query->all(),
149
            $page,
150
            $limit,
151
            $total
152
        );
153
154
        return $list;
155
    }
156
157
    /**
158
     * @param ListRepresentation $list
159
     * @param string $delimiter
160
     *
161
     * @return string
162
     */
163
    protected function listToCsv($list, $delimiter)
164
    {
165
        $data = $list->getInline()->getResources();
166
        $csv = '';
167
        $headers = array_keys(reset($data));
168
        foreach ($headers as $header) {
169
            $csv .= $header . $delimiter;
170
        }
171
        $csv = rtrim($csv, $delimiter) . PHP_EOL;
172
173
        // iterate over data array
174
        foreach ($data as $dataline) {
175
            $csv .= $this->addLine($dataline, $delimiter);
176
        }
177
178
        return $csv;
179
    }
180
181
    /**
182
     * @param array $dataline
183
     * @param string $delimiter
184
     *
185
     * @return string
186
     */
187
    protected function addLine($dataline, $delimiter)
188
    {
189
        $csvLine = '';
190
        foreach ($dataline as $datafield) {
191
            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...
192
                $csvLine .= $datafield->format(DateTime::ISO8601);
193
            } elseif (is_scalar($datafield)) {
194
                $csvLine .= $datafield;
195
            }
196
            $csvLine .= $delimiter;
197
        }
198
        $csvLine = rtrim($csvLine, $delimiter) . PHP_EOL;
199
200
        return $csvLine;
201
    }
202
203
    /**
204
     * @param string $csv
205
     *
206
     * @return Response
207
     */
208
    protected function generateCsvResponse($csv)
209
    {
210
        $response = new Response();
211
        $response->setContent($csv);
212
213
        $name = self::EXPORT_FILENAME . '-' . date('Ymd') . '.csv';
214
        $disponent = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $name);
215
        $response->headers->set('Content-Disposition', $disponent);
216
        $response->headers->set('Content-Type', 'text/csv');
217
218
        return $response;
219
    }
220
}
221