Completed
Pull Request — master (#2)
by
unknown
12:10
created

ActivityLogController::getActivityLogs()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 39
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

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