Completed
Push — develop ( 2a3366...be87d5 )
by John
03:07
created

ActiveRecordController::getRecordCount()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Alpha\Controller;
4
5
use Alpha\Controller\Front\FrontController;
6
use Alpha\Util\Logging\Logger;
7
use Alpha\Util\Config\ConfigProvider;
8
use Alpha\Util\Http\Request;
9
use Alpha\Util\Http\Response;
10
use Alpha\Util\Helper\Validator;
11
use Alpha\View\View;
12
use Alpha\View\ViewState;
13
use Alpha\Exception\IllegalArguementException;
14
use Alpha\Exception\ResourceNotFoundException;
15
use Alpha\Exception\ResourceNotAllowedException;
16
use Alpha\Exception\SecurityException;
17
use Alpha\Exception\AlphaException;
18
use Alpha\Exception\RecordNotFoundException;
19
use Alpha\Exception\ValidationException;
20
use Alpha\Model\ActiveRecord;
21
22
/**
23
 * The main active record CRUD controller for the framework.
24
 *
25
 * @since 2.0
26
 *
27
 * @author John Collins <[email protected]>
28
 * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
29
 * @copyright Copyright (c) 2017, John Collins (founder of Alpha Framework).
30
 * All rights reserved.
31
 *
32
 * <pre>
33
 * Redistribution and use in source and binary forms, with or
34
 * without modification, are permitted provided that the
35
 * following conditions are met:
36
 *
37
 * * Redistributions of source code must retain the above
38
 *   copyright notice, this list of conditions and the
39
 *   following disclaimer.
40
 * * Redistributions in binary form must reproduce the above
41
 *   copyright notice, this list of conditions and the
42
 *   following disclaimer in the documentation and/or other
43
 *   materials provided with the distribution.
44
 * * Neither the name of the Alpha Framework nor the names
45
 *   of its contributors may be used to endorse or promote
46
 *   products derived from this software without specific
47
 *   prior written permission.
48
 *
49
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
50
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
51
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
52
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
53
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
54
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
55
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
56
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
57
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
58
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
59
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
60
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
61
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
62
 * </pre>
63
 */
64
class ActiveRecordController extends Controller implements ControllerInterface
65
{
66
    /**
67
     * The start number for list pageination.
68
     *
69
     * @var int
70
     *
71
     * @since 2.0
72
     */
73
    protected $start = 0;
74
75
    /**
76
     * The amount of records to return during pageination.
77
     *
78
     * @var int
79
     *
80
     * @since 2.0
81
     */
82
    protected $limit;
83
84
    /**
85
     * The count of the records of this type in the database (used during pagination).
86
     *
87
     * @var int
88
     *
89
     * @since 2.0
90
     */
91
    protected $recordCount = 0;
92
93
    /**
94
     * The field name to sort the list by (optional, default is ID).
95
     *
96
     * @var string
97
     *
98
     * @since 2.0
99
     */
100
    protected $sort;
101
102
    /**
103
     * The order to sort the list by (optional, should be ASC or DESC, default is ASC).
104
     *
105
     * @var string
106
     *
107
     * @since 2.0
108
     */
109
    protected $order;
110
111
    /**
112
     * The name of the Record field to filter the list by (optional).
113
     *
114
     * @var string
115
     *
116
     * @since 2.0
117
     */
118
    protected $filterField;
119
120
    /**
121
     * The value of the filterField to filter by (optional).
122
     *
123
     * @var string
124
     *
125
     * @since 2.0
126
     */
127
    protected $filterValue;
128
129
    /**
130
     * Trace logger.
131
     *
132
     * @var \Alpha\Util\Logging\Logger
133
     *
134
     * @since 2.0
135
     */
136
    private static $logger = null;
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
137
138
    /**
139
     * Constructor to set up the object.
140
     *
141
     * @param string $visibility The name of the rights group that can access this controller.
142
     *
143
     * @since 1.0
144
     */
145
    public function __construct($visibility = 'Admin')
146
    {
147
        self::$logger = new Logger('ActiveRecordController');
148
        self::$logger->debug('>>__construct()');
149
150
        // ensure that the super class constructor is called, indicating the rights group
151
        parent::__construct($visibility);
152
153
        self::$logger->debug('<<__construct');
154
    }
155
156
    /**
157
     * Handle GET requests.
158
     *
159
     * @param \Alpha\Util\Http\Request $request
160
     *
161
     * @throws \Alpha\Exception\ResourceNotFoundException
162
     * @throws \Alpha\Exception\IllegalArguementException
163
     *
164
     * @return \Alpha\Util\Http\Response
165
     *
166
     * @since 2.0
167
     */
168
    public function doGET($request)
169
    {
170
        self::$logger->debug('>>doGET(request=['.var_export($request, true).'])');
171
172
        $params = $request->getParams();
173
        $accept = $request->getAccept();
174
175
        $body = '';
176
177
        try {
178
            // get a single record
179
            if (isset($params['ActiveRecordType']) && isset($params['ActiveRecordID'])) {
180
                $body .= $this->renderRecord($params, $accept);
181
            } elseif (isset($params['ActiveRecordType']) && isset($params['start'])) {
182
                // list all records of this type
183
                $body .= $this->renderRecords($params, $accept);
184
            } elseif (isset($params['ActiveRecordType'])) {
185
                // create a new record of this type
186
                $ActiveRecordType = urldecode($params['ActiveRecordType']);
187
188
                if (class_exists($ActiveRecordType)) {
189
                    $record = new $ActiveRecordType();
190
                } else {
191
                    throw new IllegalArguementException('No ActiveRecord available to create!');
192
                }
193
194
                // set up the title and meta details
195
                if (!isset($this->title)) {
196
                    $this->setTitle('Create a new '.$record->getFriendlyClassName());
197
                }
198
                if (!isset($this->description)) {
199
                    $this->setDescription('Create a new '.$record->getFriendlyClassName().'.');
200
                }
201
                if (!isset($this->keywords)) {
202
                    $this->setKeywords('create,new,'.$record->getFriendlyClassName());
203
                }
204
205
                $view = View::getInstance($record, false, $accept);
206
207
                $body .= View::displayPageHead($this);
208
                $fields = array('formAction' => $this->request->getURI());
209
                $body .= $view->createView($fields);
210
            } else {
211
                throw new IllegalArguementException('No ActiveRecord available to display!');
212
            }
213
        } catch (IllegalArguementException $e) {
214
            self::$logger->warn($e->getMessage());
215
            throw new ResourceNotFoundException('The record that you have requested cannot be found!');
216
        } catch (RecordNotFoundException $e) {
217
            self::$logger->warn($e->getMessage());
218
            throw new ResourceNotFoundException('The record that you have requested cannot be found!');
219
        }
220
221
        $body .= View::displayPageFoot($this);
222
223
        self::$logger->debug('<<doGET');
224
225
        return new Response(200, $body, array('Content-Type' => ($accept == 'application/json' ? 'application/json' : 'text/html')));
226
    }
227
228
    /**
229
     * Method to handle POST requests.
230
     *
231
     * @param \Alpha\Util\Http\Request $request
232
     *
233
     * @throws \Alpha\Exception\IllegalArguementException
234
     * @throws \Alpha\Exception\SecurityException
235
     *
236
     * @return \Alpha\Util\Http\Response
237
     *
238
     * @since 2.0
239
     */
240
    public function doPOST($request)
241
    {
242
        self::$logger->debug('>>doDPOST(request=['.var_export($request, true).'])');
243
244
        $config = ConfigProvider::getInstance();
245
246
        $params = $request->getParams();
247
        $accept = $request->getAccept();
248
249
        try {
250
            if (isset($params['ActiveRecordType'])) {
251
                $ActiveRecordType = urldecode($params['ActiveRecordType']);
252
            } else {
253
                throw new IllegalArguementException('No ActiveRecord available to create!');
254
            }
255
256
            if (class_exists($ActiveRecordType)) {
257
                $record = new $ActiveRecordType();
258
            } else {
259
                throw new IllegalArguementException('No ActiveRecord ['.$ActiveRecordType.'] available to create!');
260
            }
261
262
            // check the hidden security fields before accepting the form POST data
263
            if (!$this->checkSecurityFields()) {
264
                throw new SecurityException('This page cannot accept post data from remote servers!');
265
            }
266
267
            $record->populateFromArray($params);
268
269
            try {
270
                $record->save();
271
            } catch (ValidationException $e) {
272
                self::$logger->warn($e->getMessage());
273
                $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
274
            }
275
276
            self::$logger->action('Created new '.$ActiveRecordType.' instance with ID '.$record->getID());
277
278
            if (isset($params['statusMessage'])) {
279
                $this->setStatusMessage(View::displayUpdateMessage($params['statusMessage']));
280
            } else {
281
                $this->setStatusMessage(View::displayUpdateMessage('Created'));
282
            }
283
284
            ActiveRecord::disconnect();
285
286
            if ($accept == 'application/json') {
287
                $view = View::getInstance($record, false, $accept);
288
                $body = $view->detailedView();
289
                $response = new Response(201);
290
                $response->setHeader('Content-Type', 'application/json');
291
                $response->setHeader('Location', $config->get('app.url').'/record/'.$params['ActiveRecordType'].'/'.$record->getID());
292
                $response->setBody($body);
293
294
                self::$logger->debug('<<doPOST');
295
296
                return $response;
297
            } else {
298
                $response = new Response(301);
299
300
                if ($this->getNextJob() != '') {
301
                    $response->redirect($this->getNextJob());
302
                } else {
303
                    if ($this->request->isSecureURI()) {
304
                        $response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType='.$ActiveRecordType.'&ActiveRecordID='.$record->getID()));
305
                    } else {
306
                        $response->redirect($config->get('app.url').'/record/'.$params['ActiveRecordType'].'/'.$record->getID());
307
                    }
308
                }
309
310
                self::$logger->debug('<<doPOST');
311
312
                return $response;
313
            }
314
        } catch (SecurityException $e) {
315
            self::$logger->warn($e->getMessage());
316
            throw new ResourceNotAllowedException($e->getMessage());
317
        } catch (IllegalArguementException $e) {
318
            self::$logger->warn($e->getMessage());
319
            throw new ResourceNotFoundException('The record that you have requested cannot be found!');
320
        }
321
    }
322
323
    /**
324
     * Method to handle PUT requests.
325
     *
326
     * @param \Alpha\Util\Http\Request $request
327
     *
328
     * @throws \Alpha\Exception\IllegalArguementException
329
     * @throws \Alpha\Exception\SecurityException
330
     *
331
     * @return \Alpha\Util\Http\Response
332
     *
333
     * @since 2.0
334
     */
335
    public function doPUT($request)
336
    {
337
        self::$logger->debug('>>doPUT(request=['.var_export($request, true).'])');
338
339
        $config = ConfigProvider::getInstance();
340
341
        $params = $request->getParams();
342
        $accept = $request->getAccept();
343
344
        try {
345
            if (isset($params['ActiveRecordType'])) {
346
                $ActiveRecordType = urldecode($params['ActiveRecordType']);
347
            } else {
348
                throw new IllegalArguementException('No ActiveRecord available to edit!');
349
            }
350
351
            if (class_exists($ActiveRecordType)) {
352
                $record = new $ActiveRecordType();
353
            } else {
354
                throw new IllegalArguementException('No ActiveRecord ['.$ActiveRecordType.'] available to edit!');
355
            }
356
357
            // check the hidden security fields before accepting the form POST data
358
            if (!$this->checkSecurityFields()) {
359
                throw new SecurityException('This page cannot accept post data from remote servers!');
360
            }
361
362
            $record->load($params['ActiveRecordID']);
363
            $record->populateFromArray($params);
364
365
            try {
366
                $record->save();
367
            } catch (ValidationException $e) {
368
                self::$logger->warn($e->getMessage());
369
                $this->setStatusMessage(View::displayErrorMessage($e->getMessage()));
370
            }
371
372
            self::$logger->action('Saved '.$ActiveRecordType.' instance with ID '.$record->getID());
373
374
            if (isset($params['statusMessage'])) {
375
                $this->setStatusMessage(View::displayUpdateMessage($params['statusMessage']));
376
            } else {
377
                $this->setStatusMessage(View::displayUpdateMessage('Saved'));
378
            }
379
380
            ActiveRecord::disconnect();
381
382
            if ($accept == 'application/json') {
383
                $view = View::getInstance($record, false, $accept);
384
                $body = $view->detailedView();
385
                $response = new Response(200);
386
                $response->setHeader('Content-Type', 'application/json');
387
                $response->setHeader('Location', $config->get('app.url').'/record/'.$params['ActiveRecordType'].'/'.$record->getID());
388
                $response->setBody($body);
389
            } else {
390
                $response = new Response(301);
391
392
                if ($this->getNextJob() != '') {
393
                    $response->redirect($this->getNextJob());
394
                } else {
395
                    if ($this->request->isSecureURI()) {
396
                        $response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType='.urldecode($params['ActiveRecordType']).'&ActiveRecordID='.$record->getID().'&view=edit'));
397
                    } else {
398
                        $response->redirect($config->get('app.url').'/record/'.$params['ActiveRecordType'].'/'.$record->getID().'/edit');
399
                    }
400
                }
401
            }
402
403
            self::$logger->debug('<<doPUT');
404
405
            return $response;
406
        } catch (SecurityException $e) {
407
            self::$logger->warn($e->getMessage());
408
            throw new ResourceNotAllowedException($e->getMessage());
409
        } catch (IllegalArguementException $e) {
410
            self::$logger->warn($e->getMessage());
411
            throw new ResourceNotFoundException('The record that you have requested cannot be found!');
412
        } catch (RecordNotFoundException $e) {
413
            self::$logger->warn($e->getMessage());
414
            throw new ResourceNotFoundException('The record that you have requested cannot be found!');
415
        }
416
    }
417
418
    /**
419
     * Method to handle DELETE requests.
420
     *
421
     * @param \Alpha\Util\Http\Request $request
422
     *
423
     * @throws \Alpha\Exception\IllegalArguementException
424
     * @throws \Alpha\Exception\SecurityException
425
     * @throws \Alpha\Exception\ResourceNotAllowedException
426
     *
427
     * @return \Alpha\Util\Http\Response
428
     *
429
     * @since 2.0
430
     */
431
    public function doDELETE($request)
432
    {
433
        self::$logger->debug('>>doDELETE(request=['.var_export($request, true).'])');
434
435
        $config = ConfigProvider::getInstance();
436
437
        $params = $request->getParams();
438
        $accept = $request->getAccept();
439
440
        try {
441
            // check the hidden security fields before accepting the form data
442
            if (!$this->checkSecurityFields()) {
443
                throw new SecurityException('This page cannot accept data from remote servers!');
444
            }
445
446
            if (isset($params['ActiveRecordType'])) {
447
                $ActiveRecordType = urldecode($params['ActiveRecordType']);
448
            } else {
449
                throw new IllegalArguementException('No ActiveRecord available to edit!');
450
            }
451
452
            if (class_exists($ActiveRecordType)) {
453
                $record = new $ActiveRecordType();
454
            } else {
455
                throw new IllegalArguementException('No ActiveRecord ['.$ActiveRecordType.'] available to edit!');
456
            }
457
458
            // check the hidden security fields before accepting the form POST data
459
            if (!$this->checkSecurityFields()) {
460
                throw new SecurityException('This page cannot accept post data from remote servers!');
461
            }
462
463
            $record->load($params['ActiveRecordID']);
464
465
            ActiveRecord::begin();
466
            $record->delete();
467
            ActiveRecord::commit();
468
            ActiveRecord::disconnect();
469
470
            self::$logger->action('Deleted '.$ActiveRecordType.' instance with ID '.$params['ActiveRecordID']);
471
472
            if ($accept == 'application/json') {
473
                $response = new Response(200);
474
                $response->setHeader('Content-Type', 'application/json');
475
                $response->setBody(json_encode(array('message' => 'deleted')));
476
            } else {
477
                $response = new Response(301);
478
479
                if (isset($params['statusMessage'])) {
480
                    $this->setStatusMessage(View::displayUpdateMessage($params['statusMessage']));
481
                } else {
482
                    $this->setStatusMessage(View::displayUpdateMessage('Deleted'));
483
                }
484
485
                if ($this->getNextJob() != '') {
486
                    $response->redirect($this->getNextJob());
487
                } else {
488
                    if ($this->request->isSecureURI()) {
489
                        $response->redirect(FrontController::generateSecureURL('act=Alpha\\Controller\\ActiveRecordController&ActiveRecordType='.$ActiveRecordType.'&start=0&limit='.$config->get('app.list.page.amount')));
490
                    } else {
491
                        $response->redirect($config->get('app.url').'/records/'.$params['ActiveRecordType']);
492
                    }
493
                }
494
            }
495
496
            self::$logger->debug('<<doDELETE');
497
498
            return $response;
499
        } catch (SecurityException $e) {
500
            self::$logger->warn($e->getMessage());
501
            throw new ResourceNotAllowedException($e->getMessage());
502
        } catch (RecordNotFoundException $e) {
503
            self::$logger->warn($e->getMessage());
504
            throw new ResourceNotFoundException('The item that you have requested cannot be found!');
505
        } catch (AlphaException $e) {
506
            self::$logger->error($e->getMessage());
507
            ActiveRecord::rollback();
508
            throw new ResourceNotAllowedException($e->getMessage());
509
        }
510
    }
511
512
    /**
513
     * Sets up the pagination start point and limit.
514
     *
515
     * @since 2.0
516
     */
517
    public function after_displayPageHead_callback()
518
    {
519
        $body = parent::after_displayPageHead_callback();
520
521
        // set the start point for the list pagination
522
        if ($this->request->getParam('start') != null) {
523
            $this->start = $this->request->getParam('start');
0 ignored issues
show
Documentation Bug introduced by
The property $start was declared of type integer, but $this->request->getParam('start') is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
524
525
            $viewState = ViewState::getInstance();
526
            $viewState->set('selectedStart', $this->start);
527
528
            if ($this->request->getParam('limit') != null) {
529
                $this->limit = $this->request->getParam('limit');
0 ignored issues
show
Documentation Bug introduced by
The property $limit was declared of type integer, but $this->request->getParam('limit') is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
530
            } else {
531
                $config = ConfigProvider::getInstance();
532
                $this->limit = $config->get('app.list.page.amount');
533
            }
534
535
            $accept = $this->request->getAccept();
536
537
            if ($accept == 'application/json') {
538
                $body .= '[';
539
            }
540
        }
541
542
        return $body;
543
    }
544
545
    /**
546
     * Method to display the page footer with pageination links.
547
     *
548
     * @return string
549
     *
550
     * @since 2.0
551
     */
552
    public function before_displayPageFoot_callback()
553
    {
554
        $body = '';
555
556
        if ($this->request->getParam('start') != null) {
557
            $accept = $this->request->getAccept();
558
559
            if ($accept == 'application/json') {
560
                $body .= ']';
561
            } else {
562
                $body .= View::displayPageLinks($this);
563
                $body .= '<br>';
564
            }
565
        }
566
567
        return $body;
568
    }
569
570
    /**
571
     * Load the requested record and render the HTML or JSON for it.
572
     *
573
     * @param array $params The request params
574
     * @param string $accept The HTTP accept heard value
575
     *
576
     * @throws \Alpha\Exception\ResourceNotFoundException
577
     * @throws \Alpha\Exception\IllegalArguementException
578
     *
579
     * @return string The display data for the requested record
580
     *
581
     * @since 3.0
582
     */
583
    private function renderRecord($params, $accept)
584
    {
585
        if (!Validator::isInteger($params['ActiveRecordID'])) {
586
            throw new IllegalArguementException('Invalid oid ['.$params['ActiveRecordID'].'] provided on the request!');
587
        }
588
589
        $ActiveRecordType = urldecode($params['ActiveRecordType']);
590
591
        if (class_exists($ActiveRecordType)) {
592
            $record = new $ActiveRecordType();
593
        } else {
594
            throw new IllegalArguementException('No ActiveRecord available to view!');
595
        }
596
597
        // set up the title and meta details
598
        if (isset($params['view']) && $params['view'] == 'edit') {
599
            if (!isset($this->title)) {
600
                $this->setTitle('Editing a '.$record->getFriendlyClassName());
601
            }
602
            if (!isset($this->description)) {
603
                $this->setDescription('Page to edit a '.$record->getFriendlyClassName().'.');
604
            }
605
            if (!isset($this->keywords)) {
606
                $this->setKeywords('edit,'.$record->getFriendlyClassName());
607
            }
608
        } else {
609
            if (!isset($this->title)) {
610
                $this->setTitle('Viewing a '.$record->getFriendlyClassName());
611
            }
612
            if (!isset($this->description)) {
613
                $this->setDescription('Page to view a '.$record->getFriendlyClassName().'.');
614
            }
615
            if (!isset($this->keywords)) {
616
                $this->setKeywords('view,'.$record->getFriendlyClassName());
617
            }
618
        }
619
620
        $record->load($params['ActiveRecordID']);
621
        ActiveRecord::disconnect();
622
623
        $view = View::getInstance($record, false, $accept);
624
625
        $body = View::displayPageHead($this);
626
627
        $message = $this->getStatusMessage();
628
        if (!empty($message)) {
629
            $body .= $message;
630
        }
631
632
        $body .= View::renderDeleteForm($this->request->getURI());
633
634
        if (isset($params['view']) && $params['view'] == 'edit') {
635
            $fields = array('formAction' => $this->request->getURI());
636
            $body .= $view->editView($fields);
637
        } else {
638
            $body .= $view->detailedView();
639
        }
640
641
        return $body;
642
    }
643
644
    /**
645
     * Load all records of the type requested and render the HTML or JSON for them.
646
     *
647
     * @param array $params The request params
648
     * @param string $accept The HTTP accept heard value
649
     *
650
     * @throws \Alpha\Exception\ResourceNotFoundException
651
     * @throws \Alpha\Exception\IllegalArguementException
652
     *
653
     * @return string The display data for the requested records
654
     *
655
     * @since 3.0
656
     */
657
    private function renderRecords($params, $accept)
658
    {
659
        $ActiveRecordType = urldecode($params['ActiveRecordType']);
660
661
        if (class_exists($ActiveRecordType)) {
662
            $record = new $ActiveRecordType();
663
        } else {
664
            throw new IllegalArguementException('No ActiveRecord available to view!');
665
        }
666
667
        // set up the title and meta details
668
        if (!isset($this->title)) {
669
            $this->setTitle('Listing all '.$record->getFriendlyClassName());
670
        }
671
        if (!isset($this->description)) {
672
            $this->setDescription('Listing all '.$record->getFriendlyClassName());
673
        }
674
        if (!isset($this->keywords)) {
675
            $this->setKeywords('list,all,'.$record->getFriendlyClassName());
676
        }
677
678
        if (isset($this->filterField) && isset($this->filterValue)) {
679
            if (isset($this->sort) && isset($this->order)) {
680
                $records = $record->loadAllByAttribute($this->filterField, $this->filterValue, $params['start'], $params['limit'],
681
                    $this->sort, $this->order);
682
            } else {
683
                $records = $record->loadAllByAttribute($this->filterField, $this->filterValue, $params['start'], $params['limit']);
684
            }
685
686
            $this->recordCount = $record->getCount(array($this->filterField), array($this->filterValue));
687
        } else {
688
            if (isset($this->sort) && isset($this->order)) {
689
                $records = $record->loadAll($params['start'], $params['limit'], $this->sort, $this->order);
690
            } else {
691
                $records = $record->loadAll($params['start'], $params['limit']);
692
            }
693
694
            $this->recordCount = $record->getCount();
695
        }
696
697
        ActiveRecord::disconnect();
698
699
        $view = View::getInstance($record, false, $accept);
0 ignored issues
show
Unused Code introduced by
$view is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
700
701
        $body = View::displayPageHead($this);
702
703
        $message = $this->getStatusMessage();
704
        if (!empty($message)) {
705
            $body .= $message;
706
        }
707
708
        $body .= View::renderDeleteForm($this->request->getURI());
709
710
        foreach ($records as $record) {
711
            $view = View::getInstance($record, false, $accept);
712
            $fields = array('formAction' => $this->request->getURI());
713
            $body .= $view->listView($fields);
714
        }
715
716
        if ($accept == 'application/json') {
717
            $body = rtrim($body, ',');
718
        }
719
720
        return $body;
721
    }
722
723
    /**
724
     * Get the pagination start point
725
     *
726
     * @return int
727
     *
728
     * @since 3.0
729
     */
730
    public function getStart()
731
    {
732
        return $this->start;
733
    }
734
735
    /**
736
     * Get the pagination record count
737
     *
738
     * @return int
739
     *
740
     * @since 3.0
741
     */
742
    public function getRecordCount()
743
    {
744
        return $this->recordCount;
745
    }
746
747
    /**
748
     * Get the pagination limit
749
     *
750
     * @return int
751
     *
752
     * @since 3.0
753
     */
754
    public function getLimit()
755
    {
756
        return $this->limit;
757
    }
758
}
759