Completed
Push — 2.1 ( 497a07...c421a1 )
by
unknown
11:23
created

FileTarget::export()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3.004

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 12
cts 13
cp 0.9231
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 13
nc 3
nop 1
crap 3.004
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\profile;
9
10
use Yii;
11
use yii\helpers\FileHelper;
12
13
/**
14
 * FileTarget records profiling messages in a file specified via [[filename]].
15
 *
16
 * Application configuration example:
17
 *
18
 * ```php
19
 * return [
20
 *     'profiler' => [
21
 *         'targets' => [
22
 *             [
23
 *                 'class' => yii\profile\FileTarget::class,
24
 *                 //'filename' => '@runtime/profiling/{date}-{time}.txt',
25
 *             ],
26
 *         ],
27
 *         // ...
28
 *     ],
29
 *     // ...
30
 * ];
31
 * ```
32
 *
33
 * @author Paul Klimov <[email protected]>
34
 * @since 2.1.0
35
 */
36
class FileTarget extends Target
37
{
38
    /**
39
     * @var string file path or [path alias](guide:concept-aliases). File name may contain the placeholders,
40
     * which will be replaced by computed values. The supported placeholders are:
41
     *
42
     * - '{ts}' - profiling completion timestamp.
43
     * - '{date}' - profiling completion date in format 'ymd'.
44
     * - '{time}' - profiling completion time in format 'His'.
45
     *
46
     * The directory containing the file will be automatically created if not existing.
47
     * If target file is already exist it will be overridden.
48
     */
49
    public $filename = '@runtime/profiling/{date}-{time}.txt';
50
    /**
51
     * @var int the permission to be set for newly created files.
52
     * This value will be used by PHP chmod() function. No umask will be applied.
53
     * If not set, the permission will be determined by the current environment.
54
     */
55
    public $fileMode;
56
    /**
57
     * @var int the permission to be set for newly created directories.
58
     * This value will be used by PHP chmod() function. No umask will be applied.
59
     * Defaults to 0775, meaning the directory is read-writable by owner and group,
60
     * but read-only for other users.
61
     */
62
    public $dirMode = 0775;
63
64
65
    /**
66
     * {@inheritdoc}
67
     */
68 1
    public function export(array $messages)
69
    {
70 1
        $memoryPeakUsage = memory_get_peak_usage();
71 1
        $totalTime = microtime(true) - YII_BEGIN_TIME;
72 1
        $text = "Total processing time: {$totalTime} ms; Peak memory: {$memoryPeakUsage} B. \n\n";
73
74 1
        $text .= implode("\n", array_map([$this, 'formatMessage'], $messages));
75
76 1
        $filename = $this->resolveFilename();
77 1
        if (file_exists($filename)) {
78
            unlink($filename);
79
        } else {
80 1
            $filePath = dirname($filename);
81 1
            if (!is_dir($filePath)) {
82 1
                FileHelper::createDirectory($filePath, $this->dirMode, true);
83
            }
84
        }
85 1
        file_put_contents($filename, $text);
86 1
    }
87
88
    /**
89
     * Resolves value of [[filename]] processing path alias and placeholders.
90
     * @return string actual target filename.
91
     */
92 1
    protected function resolveFilename()
93
    {
94 1
        $filename = Yii::getAlias($this->filename);
95
96 1
        return preg_replace_callback('/{\\w+}/', function ($matches) {
97
            switch ($matches[0]) {
98
                case '{ts}':
99
                    return time();
100
                case '{date}':
101
                    return gmdate('ymd');
102
                case '{time}':
103
                    return gmdate('His');
104
            }
105
            return $matches[0];
106 1
        }, $filename);
107
    }
108
109
    /**
110
     * Formats a profiling message for display as a string.
111
     * @param array $message the profiling message to be formatted.
112
     * The message structure follows that in [[Profiler::$messages]].
113
     * @return string the formatted message.
114
     */
115 1
    protected function formatMessage(array $message)
116
    {
117 1
        return date('Y-m-d H:i:s', $message['beginTime']) . " [{$message['duration']} ms][{$message['memoryDiff']} B][{$message['category']}] {$message['token']}";
118
    }
119
}