SharedUtilityTrait::match()   C
last analyzed

Complexity

Conditions 8
Paths 10

Size

Total Lines 30
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 8

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 16
cts 16
cp 1
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 14
nc 10
nop 2
crap 8
1
<?php
2
3
namespace mpyw\HardBotter\Traits;
4
5
trait SharedUtilityTrait
6
{
7
    /**
8
     * パターンマッチング
9
     */
10 4
    public static function match($text, array $pairs)
11
    {
12 4
        static $callback;
13
14 4
        if (!$callback) {
15
            // 文字列で指定された場合に置換フォーマットをパースして処理するクロージャ
16 1
            $callback = function ($m) use (&$matches) {
17 1
                $key = isset($m[2]) ? $m[2] : $m[1];
18 1
                return isset($matches[$key]) ? $matches[$key] : '';
19 1
            };
20
        }
21
22
        // 連想配列の先頭からチェック
23 4
        foreach ($pairs as $pattern => $value) {
24 3
            if (!preg_match($pattern, $text, $matches)) {
25
                // パターンにマッチしなかった場合は次へ
26 1
                continue;
27
            }
28 3
            if (is_scalar($value)) {
29
                // 文字列で指定された場合
30 1
                return preg_replace_callback('/\$(?:\{([^}]*+)}|(\d++))/', $callback, $value);
31
            }
32 2
            if (is_callable($value)) {
33
                // クロージャで指定された場合
34 1
                return $value($matches);
35
            }
36
            // マッチしたのに指定がなかった場合はNULL
37 1
            return;
38
        }
39 1
    }
40
41
    /**
42
     * $past + $interval と現在を比較して期限が過ぎているかどうかをチェック
43
     */
44 4
    protected static function expired($past, $interval)
45
    {
46 4
        $past = new \DateTimeImmutable($past, new \DateTimeZone('UTC'));
47 4
        $future = $past->add(new \DateInterval("PT{$interval}S"));
48 4
        $now = new \DateTimeImmutable('now', new \DateTimeZone('UTC'));
49 4
        return $future <= $now;
50
    }
51
52
    /**
53
     * 結果出力用
54
     */
55 1
    protected static function out($msg)
56
    {
57 1
        if (PHP_SAPI === 'cli') {
58 1
            echo $msg . PHP_EOL;
59
        } else {
60
            // @codeCoverageIgnoreStart
61
            echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') . '<br>' . PHP_EOL;
62
            // @codeCoverageIgnoreEnd
63
        }
64 1
    }
65
}
66