Completed
Push — master ( 808f8c...952fde )
by Vladimir
11s
created

StrUtils::canBeCastedToString()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 7
nc 7
nop 1
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Utilities;
9
10
abstract class StrUtils
11
{
12
    /**
13
     * Interpolates context values into the message placeholders.
14
     *
15
     * @author PHP Framework Interoperability Group
16
     *
17
     * @param string $message
18
     * @param array  $context
19
     *
20
     * @return string
21
     */
22 View Code Duplication
    public static function interpolate($message, array $context)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
23
    {
24
        // build a replacement array with braces around the context keys
25
        $replace = [];
26
27
        foreach ($context as $key => $val)
28
        {
29
            if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString')))
30
            {
31
                $replace[sprintf('{%s}', $key)] = $val;
32
            }
33
        }
34
35
        // interpolate replacement values into the message and return
36
        return strtr($message, $replace);
37
    }
38
39
    /**
40
     * Check if an object can be casted into a string.
41
     *
42
     * @param mixed $mixed
43
     *
44
     * @link https://stackoverflow.com/a/5496674
45
     *
46
     * @return bool
47
     */
48
    public static function canBeCastedToString($mixed)
49
    {
50
        if (is_string($mixed))
51
        {
52
            return true;
53
        }
54
55
        return (
56
            (!is_array($mixed)) &&
57
            (
58
                (!is_object($mixed) && settype($mixed, 'string') !== false) ||
59
                (is_object($mixed) && method_exists($mixed, '__toString'))
60
            )
61
        );
62
    }
63
}
64