Passed
Push — master ( f22cf7...1cd2c2 )
by Mihail
04:42
created

UserLog::cleanup()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 18
rs 9.4285
cc 2
eloc 8
nc 2
nop 0
1
<?php
2
3
namespace Apps\ActiveRecord;
4
5
use Ffcms\Core\App;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Apps\ActiveRecord\App.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use Ffcms\Core\Arch\ActiveModel;
7
use Ffcms\Core\Helper\Date;
8
9
/**
10
 * Class UserLog. Active record model.
11
 * @property $id int
12
 * @property $user_id int
13
 * @property $type string
14
 * @property $message string
15
 * @property $created_at string
16
 * @property $updated_at string
17
 */
18
class UserLog extends ActiveModel
19
{
20
    const RAND_CHANCE = 10; // chance in percentage to run cleanup
21
22
    /**
23
     * Cleanup rows oldest then 1 week
24
     */
25
    public static function cleanup()
26
    {
27
        // run cleanup with chance
28
        if (mt_rand(0, 100) > static::RAND_CHANCE) {
29
            return;
30
        }
31
32
        // get session max lifetime
33
        $lifetime = App::$Session->getMetadataBag()->getLifetime();
34
        // multiple x2 to prevent any shits ;D
35
        $lifetime *= 2;
36
        // current unixtime minus lifetime
37
        $timestamp = time() - $lifetime;
38
        $sqlFormatedTime = Date::convertToDatetime($timestamp, Date::FORMAT_SQL_DATE);
39
40
        /// remove oldest rows
41
        self::where('created_at', '<=', $sqlFormatedTime)->delete();
42
    }
43
44
    /**
45
     * Override save method - cleanup before save
46
     * {@inheritDoc}
47
     * @see \Illuminate\Database\Eloquent\Model::save()
48
     */
49
    public function save(array $opt = [])
50
    {
51
        self::cleanup();
52
        parent::save($opt);
53
    }
54
}