RequestsTable.php
2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace DebugKit\Model\Table;
use Cake\Core\Configure;
use Cake\ORM\Query;
use Cake\ORM\Table;
use DebugKit\Model\Table\LazyTableTrait;
/**
* The requests table tracks basic information about each request.
*/
class RequestsTable extends Table
{
use LazyTableTrait;
/**
* initialize method
*
* @param array $config Config data.
* @return void
*/
public function initialize(array $config)
{
$this->hasMany('DebugKit.Panels', [
'sort' => ['Panels.title' => 'ASC'],
]);
$this->addBehavior('Timestamp', [
'events' => [
'Model.beforeSave' => ['requested_at' => 'new']
]
]);
$this->ensureTables(['DebugKit.Requests', 'DebugKit.Panels']);
}
/**
* DebugKit tables are special.
*
* @return string
*/
public static function defaultConnectionName()
{
return 'debug_kit';
}
/**
* Finder method to get recent requests as a simple array
*
* @param Cake\ORM\Query $query The query
* @param array $options The options
* @return Query The query.
*/
public function findRecent(Query $query, array $options)
{
return $query->order(['Requests.requested_at' => 'DESC'])
->limit(10);
}
/**
* Garbage collect old request data.
*
* Delete request data that is older than 2 weeks old.
* This method will only trigger periodically.
*
* @return void
*/
public function gc()
{
if (time() % 100 !== 0) {
return;
}
$noPurge = $this->find()
->select(['id'])
->hydrate(false)
->order(['requested_at' => 'desc'])
->limit(Configure::read('DebugKit.requestCount') ?: 20)
->extract('id')
->toArray();
$query = $this->Panels->query()
->delete()
->where(['request_id NOT IN' => $noPurge]);
$statement = $query->execute();
$statement->closeCursor();
$query = $this->query()
->delete()
->where(['id NOT IN' => $noPurge]);
$statement = $query->execute();
$statement->closeCursor();
}
}