Completed
Pull Request — master (#2)
by
unknown
15:31 queued 36s
created

ActivityLogController   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 194
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 14
c 3
b 0
f 1
lcom 1
cbo 7
dl 0
loc 194
rs 10

8 Methods

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