Completed
Push — develop ( 2eecbb...61fadb )
by John
02:55
created

ActiveRecordController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 1
eloc 5
nc 1
nop 1
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 .= $this->renderPageLinks();
563
                $body .= '<br>';
564
            }
565
        }
566
567
        return $body;
568
    }
569
570
    /**
571
     * Method for rendering the pagination links.
572
     *
573
     * @return string
574
     *
575
     * @since 2.0
576
     */
577
    protected function renderPageLinks()
578
    {
579
        $config = ConfigProvider::getInstance();
580
581
        $body = '';
582
583
        // the index of the last record displayed on this page
584
        $last = $this->start+$config->get('app.list.page.amount');
585
586
        // ensure that the last index never overruns the total record count
587
        if ($last > $this->recordCount) {
588
            $last = $this->recordCount;
589
        }
590
591
        // render a message for an empty list
592
        if ($this->recordCount > 0) {
593
            $body .= '<ul class="pagination">';
594
        } else {
595
            $body .= '<p align="center">The list is empty.&nbsp;&nbsp;</p>';
596
597
            return $body;
598
        }
599
600
        // render "Previous" link
601
        if ($this->start > 0) {
602
            // handle secure URLs
603
            if ($this->request->getParam('token', null) != null) {
604
                $body .= '<li><a href="'.FrontController::generateSecureURL('act=Alpha\Controller\ActiveRecordController&ActiveRecordType='.$this->request->getParam('ActiveRecordType').'&start='.($this->start-$this->limit).'&limit='.$this->limit).'">&lt;&lt;-Previous</a></li>';
605
            } else {
606
                $body .= '<li><a href="/records/'.urlencode($this->request->getParam('ActiveRecordType')).'/'.($this->start-$this->limit).'/'.$this->limit.'">&lt;&lt;-Previous</a></li>';
607
            }
608
        } elseif ($this->recordCount > $this->limit) {
609
            $body .= '<li class="disabled"><a href="#">&lt;&lt;-Previous</a></li>';
610
        }
611
612
        // render the page index links
613
        if ($this->recordCount > $this->limit) {
614
            $page = 1;
615
616
            for ($i = 0; $i < $this->recordCount; $i += $this->limit) {
617
                if ($i != $this->start) {
618
                    // handle secure URLs
619
                    if ($this->request->getParam('token', null) != null) {
620
                        $body .= '<li><a href="'.FrontController::generateSecureURL('act=Alpha\Controller\ActiveRecordController&ActiveRecordType='.$this->request->getParam('ActiveRecordType').'&start='.$i.'&limit='.$this->limit).'">'.$page.'</a></li>';
621
                    } else {
622
                        $body .= '<li><a href="/records/'.urlencode($this->request->getParam('ActiveRecordType')).'/'.$i.'/'.$this->limit.'">'.$page.'</a></li>';
623
                    }
624
                } elseif ($this->recordCount > $this->limit) { // render an anchor for the current page
625
                    $body .= '<li class="active"><a href="#">'.$page.'</a></li>';
626
                }
627
628
                ++$page;
629
            }
630
        }
631
632
        // render "Next" link
633
        if ($this->recordCount > $last) {
634
            // handle secure URLs
635
            if ($this->request->getParam('token', null) != null) {
636
                $body .= '<li><a href="'.FrontController::generateSecureURL('act=Alpha\Controller\ActiveRecordController&ActiveRecordType='.$this->request->getParam('ActiveRecordType').'&start='.($this->start+$this->limit).'&limit='.$this->limit).'">Next-&gt;&gt;</a></li>';
637
            } else {
638
                $body .= '<li><a href="/records/'.urlencode($this->request->getParam('ActiveRecordType')).'/'.($this->start+$this->limit.'/'.$this->limit).
639
                    '">Next-&gt;&gt;</a></li>';
640
            }
641
        } elseif ($this->recordCount > $this->limit) {
642
            $body .= '<li class="disabled"><a href="#">Next-&gt;&gt;</a></li>';
643
        }
644
645
        $body .= '</ul>';
646
647
        return $body;
648
    }
649
650
    /**
651
     * Load the requested record and render the HTML or JSON for it.
652
     *
653
     * @param array $params The request params
654
     * @param string $accept The HTTP accept heard value
655
     *
656
     * @throws \Alpha\Exception\ResourceNotFoundException
657
     * @throws \Alpha\Exception\IllegalArguementException
658
     *
659
     * @return string The display data for the requested record
660
     *
661
     * @since 3.0
662
     */
663
    private function renderRecord($params, $accept)
664
    {
665
        if (!Validator::isInteger($params['ActiveRecordID'])) {
666
            throw new IllegalArguementException('Invalid oid ['.$params['ActiveRecordID'].'] provided on the request!');
667
        }
668
669
        $ActiveRecordType = urldecode($params['ActiveRecordType']);
670
671
        if (class_exists($ActiveRecordType)) {
672
            $record = new $ActiveRecordType();
673
        } else {
674
            throw new IllegalArguementException('No ActiveRecord available to view!');
675
        }
676
677
        // set up the title and meta details
678
        if (isset($params['view']) && $params['view'] == 'edit') {
679
            if (!isset($this->title)) {
680
                $this->setTitle('Editing a '.$record->getFriendlyClassName());
681
            }
682
            if (!isset($this->description)) {
683
                $this->setDescription('Page to edit a '.$record->getFriendlyClassName().'.');
684
            }
685
            if (!isset($this->keywords)) {
686
                $this->setKeywords('edit,'.$record->getFriendlyClassName());
687
            }
688
        } else {
689
            if (!isset($this->title)) {
690
                $this->setTitle('Viewing a '.$record->getFriendlyClassName());
691
            }
692
            if (!isset($this->description)) {
693
                $this->setDescription('Page to view a '.$record->getFriendlyClassName().'.');
694
            }
695
            if (!isset($this->keywords)) {
696
                $this->setKeywords('view,'.$record->getFriendlyClassName());
697
            }
698
        }
699
700
        $record->load($params['ActiveRecordID']);
701
        ActiveRecord::disconnect();
702
703
        $view = View::getInstance($record, false, $accept);
704
705
        $body = View::displayPageHead($this);
706
707
        $message = $this->getStatusMessage();
708
        if (!empty($message)) {
709
            $body .= $message;
710
        }
711
712
        $body .= View::renderDeleteForm($this->request->getURI());
713
714
        if (isset($params['view']) && $params['view'] == 'edit') {
715
            $fields = array('formAction' => $this->request->getURI());
716
            $body .= $view->editView($fields);
717
        } else {
718
            $body .= $view->detailedView();
719
        }
720
721
        return $body;
722
    }
723
724
    /**
725
     * Load all records of the type requested and render the HTML or JSON for them.
726
     *
727
     * @param array $params The request params
728
     * @param string $accept The HTTP accept heard value
729
     *
730
     * @throws \Alpha\Exception\ResourceNotFoundException
731
     * @throws \Alpha\Exception\IllegalArguementException
732
     *
733
     * @return string The display data for the requested records
734
     *
735
     * @since 3.0
736
     */
737
    private function renderRecords($params, $accept)
738
    {
739
        $ActiveRecordType = urldecode($params['ActiveRecordType']);
740
741
        if (class_exists($ActiveRecordType)) {
742
            $record = new $ActiveRecordType();
743
        } else {
744
            throw new IllegalArguementException('No ActiveRecord available to view!');
745
        }
746
747
        // set up the title and meta details
748
        if (!isset($this->title)) {
749
            $this->setTitle('Listing all '.$record->getFriendlyClassName());
750
        }
751
        if (!isset($this->description)) {
752
            $this->setDescription('Listing all '.$record->getFriendlyClassName());
753
        }
754
        if (!isset($this->keywords)) {
755
            $this->setKeywords('list,all,'.$record->getFriendlyClassName());
756
        }
757
758
        if (isset($this->filterField) && isset($this->filterValue)) {
759
            if (isset($this->sort) && isset($this->order)) {
760
                $records = $record->loadAllByAttribute($this->filterField, $this->filterValue, $params['start'], $params['limit'],
761
                    $this->sort, $this->order);
762
            } else {
763
                $records = $record->loadAllByAttribute($this->filterField, $this->filterValue, $params['start'], $params['limit']);
764
            }
765
766
            $this->recordCount = $record->getCount(array($this->filterField), array($this->filterValue));
767
        } else {
768
            if (isset($this->sort) && isset($this->order)) {
769
                $records = $record->loadAll($params['start'], $params['limit'], $this->sort, $this->order);
770
            } else {
771
                $records = $record->loadAll($params['start'], $params['limit']);
772
            }
773
774
            $this->recordCount = $record->getCount();
775
        }
776
777
        ActiveRecord::disconnect();
778
779
        $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...
780
781
        $body = View::displayPageHead($this);
782
783
        $message = $this->getStatusMessage();
784
        if (!empty($message)) {
785
            $body .= $message;
786
        }
787
788
        $body .= View::renderDeleteForm($this->request->getURI());
789
790
        foreach ($records as $record) {
791
            $view = View::getInstance($record, false, $accept);
792
            $fields = array('formAction' => $this->request->getURI());
793
            $body .= $view->listView($fields);
794
        }
795
796
        if ($accept == 'application/json') {
797
            $body = rtrim($body, ',');
798
        }
799
800
        return $body;
801
    }
802
}
803