MailLogger   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 61
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A log() 0 16 3
A getLogFile() 0 19 3
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @copyright   Copyright (c) 2015 ublaboo <[email protected]>
7
 * @author      Pavel Janda <[email protected]>
8
 * @package     Ublaboo
9
 */
10
11
namespace Ublaboo\Mailing;
12
13
use Nette\Mail\Message;
14
15
class MailLogger implements ILogger
16
{
17
18
	private const LOG_EXTENSION = '.eml';
19
20
	/**
21
	 * @var string
22
	 */
23
	protected $logDirectory;
24
25
26
	public function __construct($logDirectory)
27
	{
28
		$this->logDirectory = $logDirectory;
29
	}
30
31
32
	/**
33
	 * Log mail messages to eml file
34
	 */
35
	public function log($type, Message $mail): void
36
	{
37
		$timestamp = date('Y-m-d H:i:s');
38
		$type .= '.' . time();
39
		$file = $this->getLogFile($type, $timestamp);
40
41
		if (file_exists($file) && filesize($file)) {
42
			$file = str_replace(
43
				static::LOG_EXTENSION,
44
				'.' . uniqid() . static::LOG_EXTENSION,
45
				$file
46
			);
47
		}
48
49
		file_put_contents($file, $mail->generateMessage());
50
	}
51
52
53
	/**
54
	 * If not already created, create a directory path that sticks to the standard described above
55
	 */
56
	public function getLogFile(string $type, string $timestamp): string
57
	{
58
		preg_match('/^((([0-9]{4})-[0-9]{2})-[0-9]{2}).*/', $timestamp, $fragments);
59
60
		$yearDir = $this->logDirectory . '/' . $fragments[3];
61
		$monthDir = $yearDir . '/' . $fragments[2];
62
		$dayDir = $monthDir . '/' . $fragments[1];
63
		$file = $dayDir . '/' . $type . static::LOG_EXTENSION;
64
65
		if (!file_exists($dayDir)) {
66
			mkdir($dayDir, 0777, true);
67
		}
68
69
		if (!file_exists($file)) {
70
			touch($file);
71
		}
72
73
		return $file;
74
	}
75
}
76