Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
Code
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
3 / 3
3
100.00% covered (success)
100.00%
1 / 1
 toLiteralString
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 using
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 toString
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace PeServer\Core;
6
7use PeServer\Core\Collection\Arr;
8use PeServer\Core\IDisposable;
9use PeServer\Core\Throws\ArgumentException;
10use PeServer\Core\Throws\NotImplementedException;
11use PeServer\Core\Throws\TypeException;
12use ReflectionClass;
13
14/**
15 * コーディング上のあれ。
16 */
17abstract class Code
18{
19    #region function
20
21    /**
22     * 文字列をリテラル文字列に変換。
23     *
24     * PHPStan用のラッパー(関数にしとけば後で探すの楽でしょ感で作った)。
25     *
26     * @param string $s
27     * @phpstan-return literal-string
28     */
29    public static function toLiteralString(string $s): string
30    {
31        /** @phpstan-var literal-string */
32        return $s;
33    }
34
35    /**
36     * 疑似コード: C# using
37     *
38     * これつっかえんわぁ。。。
39     * `=>` が複数行使えればなぁ。
40     *
41     * @template TDisposable of IDisposable
42     * @template TResult
43     * @param IDisposable $disposable
44     * @phpstan-param TDisposable $disposable
45     * @param callable $callback
46     * @phpstan-param callable(TDisposable $disposable):TResult $callback
47     * @return mixed
48     * @phpstan-return TResult
49     */
50    public static function using(IDisposable $disposable, callable $callback)
51    {
52        try {
53            return $callback($disposable);
54        } finally {
55            $disposable->dispose();
56        }
57    }
58
59    /**
60     *
61     * @param object $obj
62     * @param string[] $propertyNames
63     * @param string $separator
64     * @return string
65     */
66    public static function toString(object $obj, array $propertyNames, string $separator = ','): string
67    {
68        $rc = new ReflectionClass($obj);
69
70        return
71            get_class($obj) .
72            '(' .
73            Text::join($separator, Arr::map($propertyNames, fn ($a) => $a . ':' . $rc->getProperty($a)->getValue($obj))) .
74            ')';
75    }
76
77    #endregion
78}