Completed
Push — master ( b90e1d...11acf7 )
by Nelson
05:52
created

Text::ensureIsString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
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 Cake\Utility\Text as TextBase;
22
use \InvalidArgumentException;
23
24
/**
25
 * Provides extension methods to handle strings.
26
 * This class is based on \Cake\Utility\Text of CakePHP(tm) class.
27
 *
28
 * @see \Cake\Utility\Text::insert
29
 * @see http://book.cakephp.org/3.0/en/core-libraries/text.html
30
 * */
31
class Text extends TextBase
32
{
33
34
    /**
35
     * Replaces format elements in a string with the string representation of an
36
     * object matching the list of arguments specified. You can give as many
37
     * params as you need, or an array with values.
38
     *
39
     * ##Usage
40
     * Using numbers as placeholders (encloses between `{` and `}`), you can get
41
     * the matching string representation of each object given. Use `{0}` for
42
     * the fist object, `{1}` for the second, and so on.
43
     * Example:
44
     * `Text::format('{0} is {1} years old, and have {2} cats.', 'Bob', 65, 101);`
45
     * Returns: 'Bob is 65 years old, and have 101 cats.'
46
     *
47
     * You can also use an array to give objects values.
48
     * Example: `Text::Format('{0} is {1} years old.', ['Bob', 65, 101]);`
49
     * Returns: 'Bob is 65 years old, and have 101 cats.'
50
     *
51
     * If give an key => value array, each key stands for a placeholder variable
52
     * name to be replaced with value key. In this case, order of keys do not
53
     * matter.
54
     * Example:
55
     * `$arg0 = ['name' => 'Bob', 'n' => 101, 'age' => 65];`
56
     * `$format = '{name} is {age} years old, and have {n} cats.';`
57
     * `Text::Format($format, $arg0);`
58
     * Returns: 'Bob is 65 years old, and have 101 cats.'
59
     *
60
     * @param string               $format An string containing variable placeholders to be replaced.
61
     * @param string[]|array|mixed $args   Object(s) to be replaced into $format.
62
     *   placeholders.
63
     *
64
     * @return string
65
     * @throws InvalidArgumentException if $format is not an string or placeholder values are not string-convertibles.
66
     * @todo   Implement, for php 5.6+:
67
     *   php.net/functions.arguments.html#functions.variable-arg-list.new
68
     * @todo   Implement formatting, like IFormatProvider or something like that.
69
     * @author Nelson Martell <[email protected]>
70
     */
71 197
    public static function format($format, $args)
72
    {
73
        static $options = [
74
            'before'  => '{',
75
            'after'   => '}',
76 197
        ];
77
78 197
        $originalData = func_num_args() === 2 ? (array) $args : array_slice(func_get_args(), 1);
79
80 197
        $data = [];
81
        // Sanitize values to be convertibles into strings
82 197
        foreach ($originalData as $placeholder => $value) {
83 197
            if (!is_string($placeholder) && !is_integer($placeholder)) {
84
                $msg = 'Placeholder must to be a of string or integer type; "{1}" type given.';
85
                throw new InvalidArgumentException(\NelsonMartell\msg($msg, \NelsonMartell\typeof($placeholder)));
86
            }
87
88 197
            $valueType = \NelsonMartell\typeof($value);
89
90 197
            if ($valueType->canBeString() === false) {
91 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...
92 3
                throw new InvalidArgumentException(\NelsonMartell\msg($msg, $placeholder, $valueType));
93
            }
94
95
            // 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...
96
            // without SORT_STRING flag... by forcing value to be string.
97 197
            settype($value, 'string');
98 197
            $data[$placeholder] = $value;
99 197
        }
100
101 197
        return static::insert($format, $data, $options);
102
    }
103
104
    /**
105
     * Ensures that object given is not null. If is `null`, throws and exception.
106
     *
107
     * @param mixed $obj Object to validate
108
     *
109
     * @return mixed Same object
110
     * @throws InvalidArgumentException if object is `null`.
111
     */
112 272
    public static function ensureIsNotNull($obj)
113
    {
114 272
        if (is_null($obj)) {
115
            $msg = \NelsonMartell\msg('Provided object must not be NULL.');
116
            throw new InvalidArgumentException($msg);
117
        }
118
119 272
        return $obj;
120
    }
121
122
    /**
123
     * Ensures that object given is an string. Else, thows an exception
124
     *
125
     * @param mixed $obj Object to validate.
126
     *
127
     * @return string Same object given, but ensured that is an string.
128
     * @throws InvalidArgumentException if object is not an `string`.
129
     */
130 272
    public static function ensureIsString($obj)
131
    {
132 272
        if (!is_string(static::ensureIsNotNull($obj))) {
133 1
            $msg = \NelsonMartell\msg('Provided object must to be an string; "{0}" given.', \NelsonMartell\typeof($obj));
1 ignored issue
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 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...
134 1
            throw new InvalidArgumentException($msg);
135
        }
136
137 272
        return $obj;
138
    }
139
140
    /**
141
     * Ensures that given string is not empty.
142
     *
143
     * @param string $string String to validate.
144
     *
145
     * @return string Same string given, but ensured that is not empty.
146
     * @throws InvalidArgumentException if string is null or empty.
147
     */
148 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...
149
    {
150
        if (static::ensureIsString($string) === '') {
151
            $msg = \NelsonMartell\msg('Provided string must not be empty.');
152
            throw new InvalidArgumentException($msg);
153
        }
154
155
        return $string;
156
    }
157
158
    /**
159
     * Ensures that given string is not empty or whitespaces.
160
     *
161
     * @param string $string String to validate.
162
     *
163
     * @return string Same string given, but ensured that is not whitespaces.
164
     * @throws InvalidArgumentException if object is not an `string`.
165
     * @see    trim
166
     */
167 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...
168
    {
169
        if (trim(static::ensureIsNotEmpty($string)) === '') {
170
            $msg = \NelsonMartell\msg('Provided string must not be white spaces.');
171
            throw new InvalidArgumentException($msg);
172
        }
173
174
        return $string;
175
    }
176
177
    /**
178
     * Ensures that an string follows the PHP variables naming convention.
179
     *
180
     * @param string $string String to be ensured.
181
     *
182
     * @return string
183
     * @throws InvalidArgumentException if object is not an `string` or do not
184
     *   follows the PHP variables naming convention.
185
     */
186 272
    public static function ensureIsValidVarName($string)
187
    {
188 272
        $pattern = '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/';
189
190 272
        if (!preg_match($pattern, static::ensureIsString($string))) {
191
            $msg = \NelsonMartell\msg('Provided string do not follows PHP variables naming convention: "{0}".', $string);
1 ignored issue
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 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...
192
            throw new InvalidArgumentException($msg);
193
        }
194
195 272
        return $string;
196
    }
197
}
198