Passed
Branch master (283c0c)
by Nelson
02:38
created

Text::ensureIsNotNull()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.2559

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 9
ccs 3
cts 5
cp 0.6
crap 2.2559
rs 9.6666
c 0
b 0
f 0
1
<?php
2
/**
3
 * PHP: Nelson Martell Library file
4
 *
5
 * Content:
6
 * - Class definition:  [NelsonMartell\Extensions]  String
7
 *
8
 * Copyright © 2015-2016 Nelson Martell (http://nelson6e65.github.io)
9
 *
10
 * Licensed under The MIT License (MIT)
11
 * For full copyright and license information, please see the LICENSE
12
 * Redistributions of files must retain the above copyright notice.
13
 *
14
 * @copyright 2015-2017 Nelson Martell
15
 * @link      http://nelson6e65.github.io/php_nml/
16
 * @since     v0.7.0
17
 * @license   http://www.opensource.org/licenses/mit-license.php The MIT License (MIT)
18
 * */
19
namespace NelsonMartell\Extensions;
20
21
use InvalidArgumentException;
22
use Cake\Utility\Text as TextBase;
23
24
use function NelsonMartell\msg;
25
use function NelsonMartell\typeof;
26
27
/**
28
 * Provides extension methods to handle strings.
29
 * This class is based on \Cake\Utility\Text of CakePHP(tm) class.
30
 *
31
 * @see \Cake\Utility\Text::insert
32
 * @link http://book.cakephp.org/3.0/en/core-libraries/text.html
33
 * */
34
class Text extends TextBase
35
{
36
37
    /**
38
     * Replaces format elements in a string with the string representation of an
39
     * object matching the list of arguments specified. You can give as many
40
     * params as you need, or an array with values.
41
     *
42
     * ##Usage
43
     * Using numbers as placeholders (encloses between `{` and `}`), you can get
44
     * the matching string representation of each object given. Use `{0}` for
45
     * the fist object, `{1}` for the second, and so on.
46
     * Example:
47
     * `Text::format('{0} is {1} years old, and have {2} cats.', 'Bob', 65, 101);`
48
     * Returns: 'Bob is 65 years old, and have 101 cats.'
49
     *
50
     * You can also use an array to give objects values.
51
     * Example: `Text::Format('{0} is {1} years old.', ['Bob', 65, 101]);`
52
     * Returns: 'Bob is 65 years old, and have 101 cats.'
53
     *
54
     * If give an key => value array, each key stands for a placeholder variable
55
     * name to be replaced with value key. In this case, order of keys do not
56
     * matter.
57
     * Example:
58
     * `$arg0 = ['name' => 'Bob', 'n' => 101, 'age' => 65];`
59
     * `$format = '{name} is {age} years old, and have {n} cats.';`
60
     * `Text::Format($format, $arg0);`
61
     * Returns: 'Bob is 65 years old, and have 101 cats.'
62
     *
63
     * @param string               $format An string containing variable placeholders to be replaced.
64
     * @param string[]|array|mixed $args   Object(s) to be replaced into $format.
65
     *   placeholders.
66
     *
67
     * @return string
68
     * @throws InvalidArgumentException if $format is not an string or placeholder values are not string-convertibles.
69
     * @todo   Implement, for php 5.6+:
70
     *   php.net/functions.arguments.html#functions.variable-arg-list.new
71
     * @todo   Implement formatting, like IFormatProvider or something like that.
72
     * @author Nelson Martell <[email protected]>
73
     */
74 197
    public static function format($format, $args)
75
    {
76 197
        static $options = [
77
            'before'  => '{',
78
            'after'   => '}',
79
        ];
80
81 197
        $originalData = func_num_args() === 2 ? (array) $args : array_slice(func_get_args(), 1);
82
83 197
        $data = [];
84
        // Sanitize values to be convertibles into strings
85 197
        foreach ($originalData as $placeholder => $value) {
86 197
            if (!is_string($placeholder) && !is_integer($placeholder)) {
87
                $msg = 'Placeholder must to be a of string or integer type; "{1}" type given.';
88
                throw new InvalidArgumentException(msg($msg, typeof($placeholder)));
89
            }
90
91 197
            $valueType = typeof($value);
92
93 197
            if ($valueType->canBeString() === false) {
94 3
                $msg = 'Value for "{{0}}" placeholder must to be a string or object convertible to string; "{1}" type given.';
1 ignored issue
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
95 3
                throw new InvalidArgumentException(msg($msg, $placeholder, $valueType));
96
            }
97
98
            // This is to work-arround a bug in use of ``asort()`` function in ``Text::insert`` (at v3.2.5)
0 ignored issues
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
99
            // without SORT_STRING flag... by forcing value to be string.
100 197
            settype($value, 'string');
101 197
            $data[$placeholder] = $value;
102
        }
103
104 197
        return static::insert($format, $data, $options);
105
    }
106
107
    /**
108
     * Ensures that object given is not null. If is `null`, throws and exception.
109
     *
110
     * @param mixed $obj Object to validate
111
     *
112
     * @return mixed Same object
113
     * @throws InvalidArgumentException if object is `null`.
114
     */
115 272
    public static function ensureIsNotNull($obj)
116
    {
117 272
        if (is_null($obj)) {
118
            $msg = msg('Provided object must not be NULL.');
119
            throw new InvalidArgumentException($msg);
120
        }
121
122 272
        return $obj;
123
    }
124
125
    /**
126
     * Ensures that object given is an string. Else, thows an exception
127
     *
128
     * @param mixed $obj Object to validate.
129
     *
130
     * @return string Same object given, but ensured that is an string.
131
     * @throws InvalidArgumentException if object is not an `string`.
132
     */
133 272
    public static function ensureIsString($obj)
134
    {
135 272
        if (!is_string(static::ensureIsNotNull($obj))) {
136 1
            $msg = msg('Provided object must to be an string; "{0}" given.', typeof($obj));
137 1
            throw new InvalidArgumentException($msg);
138
        }
139
140 272
        return $obj;
141
    }
142
143
    /**
144
     * Ensures that given string is not empty.
145
     *
146
     * @param string $string String to validate.
147
     *
148
     * @return string Same string given, but ensured that is not empty.
149
     * @throws InvalidArgumentException if string is null or empty.
150
     */
151 View Code Duplication
    public static function ensureIsNotEmpty($string)
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...
152
    {
153
        if (static::ensureIsString($string) === '') {
154
            $msg = msg('Provided string must not be empty.');
155
            throw new InvalidArgumentException($msg);
156
        }
157
158
        return $string;
159
    }
160
161
    /**
162
     * Ensures that given string is not empty or whitespaces.
163
     *
164
     * @param string $string String to validate.
165
     *
166
     * @return string Same string given, but ensured that is not whitespaces.
167
     * @throws InvalidArgumentException if object is not an `string`.
168
     * @see    \trim()
169
     */
170 View Code Duplication
    public static function ensureIsNotWhiteSpaces($string)
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...
171
    {
172
        if (trim(static::ensureIsNotEmpty($string)) === '') {
173
            $msg = msg('Provided string must not be white spaces.');
174
            throw new InvalidArgumentException($msg);
175
        }
176
177
        return $string;
178
    }
179
180
    /**
181
     * Ensures that an string follows the PHP variables naming convention.
182
     *
183
     * @param string $string String to be ensured.
184
     *
185
     * @return string
186
     * @throws InvalidArgumentException if object is not an `string` or do not
187
     *   follows the PHP variables naming convention.
188
     */
189 272
    public static function ensureIsValidVarName($string)
190
    {
191 272
        $pattern = '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/';
192
193 272
        if (!preg_match($pattern, static::ensureIsString($string))) {
194
            $msg = msg('Provided string do not follows PHP variables naming convention: "{0}".', $string);
195
            throw new InvalidArgumentException($msg);
196
        }
197
198 272
        return $string;
199
    }
200
}
201