Passed
Pull Request — master (#19)
by Rustam
02:38
created

FileTarget::resolveFilename()   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

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