Passed
Pull Request — master (#24)
by Rustam
02:01
created

FileTarget   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Test Coverage

Coverage 97.14%

Importance

Changes 0
Metric Value
eloc 32
dl 0
loc 91
ccs 34
cts 35
cp 0.9714
rs 10
c 0
b 0
f 0
wmc 10

4 Methods

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