Passed
Pull Request — master (#19)
by Rustam
02:40
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\Aliases\Aliases;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Aliases\Aliases was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Yiisoft\Files\FileHelper;
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
 *     'profiler' => [
18
 *         'targets' => [
19
 *             [
20
 *                 '__class' => Yiisoft\Profile\FileTarget::class,
21
 *                 //'filename' => '@runtime/profiling/{date}-{time}.txt',
22
 *             ],
23
 *         ],
24
 *         // ...
25
 *     ],
26
 *     // ...
27
 * ];
28
 * ```
29
 */
30
final class FileTarget extends Target
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 = 0775;
52
53 3
    public function __construct(string $filename = '@runtime/profiling/{date}-{time}.txt')
54
    {
55 3
        $this->filename = $filename;
56 3
    }
57
58 3
    public function export(array $messages): void
59
    {
60 3
        $memoryPeakUsage = memory_get_peak_usage();
61
62
        // TODO: make sure it works with RoadRunner and alike servers
63 3
        $totalTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
64 3
        $text = "Total processing time: {$totalTime} ms; Peak memory: {$memoryPeakUsage} B. \n\n";
65
66 3
        $text .= implode("\n", array_map([$this, 'formatMessage'], $messages));
67
68 3
        $filename = $this->resolveFilename();
69
70 3
        if (file_exists($filename)) {
71 2
            FileHelper::unlink($filename);
72
        } else {
73 1
            $filePath = dirname($filename);
74
75 1
            if (!is_dir($filePath)) {
76 1
                FileHelper::createDirectory($filePath, $this->dirMode);
77
            }
78
        }
79
80 3
        file_put_contents($filename, $text);
81 3
    }
82
83
    /**
84
     * Resolves value of {@see filename} processing path alias and placeholders.
85
     *
86
     * @return string actual target filename.
87
     */
88 3
    private function resolveFilename(): string
89
    {
90 3
        return preg_replace_callback(
91 3
            '/{\\w+}/',
92 3
            static function ($matches) {
93 1
                switch ($matches[0]) {
94 1
                    case '{ts}':
95 1
                        return time();
96 1
                    case '{date}':
97 1
                        return gmdate('ymd');
98 1
                    case '{time}':
99 1
                        return gmdate('His');
100
                }
101 1
                return $matches[0];
102 3
            },
103 3
            $this->filename
104
        );
105
    }
106
107
    /**
108
     * Formats a profiling message for display as a string.
109
     *
110
     * @param Message $message the profiling message to be formatted.
111
     * The message structure follows that in {@see Profiler::$messages}.
112
     *
113
     * @return string the formatted message.
114
     */
115 3
    private function formatMessage(Message $message): string
116
    {
117 3
        return date('Y-m-d H:i:s', (int)$message->context('beginTime'))
118 3
            . " [{$message->context('duration')} ms][{$message->context('memoryDiff')} B][{$message->level()}] {$message->message()}"
119 3
            . __METHOD__;
120
    }
121
}
122