Completed
Pull Request — master (#23)
by Nelson
03:02
created

String::format()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 32
rs 8.439
cc 6
eloc 17
nc 8
nop 2
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-2016 Nelson Martell
15
 * @link      http://nelson6e65.github.io/php_nml/
16
 * @since     v0.4.1
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;
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 String extends Text
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
     * `String::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: `String::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
     * `String::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
    public static function format($format, $args)
72
    {
73
        static $options = [
74
            'before'  => '{',
75
            'after'   => '}',
76
        ];
77
78
        $originalData = func_num_args() === 2 ? (array) $args : array_slice(func_get_args(), 1);
79
80
        $data = [];
81
        // Sanitize values to be convertibles into strings
82
        foreach ($originalData as $placeholder => $value) {
83
            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(nml_msg($msg, typeof($placeholder)));
0 ignored issues
show
Deprecated Code introduced by
The function typeof() has been deprecated with message: since v0.6.0, will be removed in v0.7.0. Use `\NelsonMartell\typeof()` instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
Deprecated Code introduced by
The function nml_msg() has been deprecated with message: since v0.6.0, will be removed in v0.7.0. Use `\NelsonMartell\msg()` instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
86
            }
87
88
            $valueType = typeof($value);
0 ignored issues
show
Deprecated Code introduced by
The function typeof() has been deprecated with message: since v0.6.0, will be removed in v0.7.0. Use `\NelsonMartell\typeof()` instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
89
90
            if ($valueType->canBeString() === false) {
91
                $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
                throw new InvalidArgumentException(nml_msg($msg, $placeholder, $valueType));
0 ignored issues
show
Deprecated Code introduced by
The function nml_msg() has been deprecated with message: since v0.6.0, will be removed in v0.7.0. Use `\NelsonMartell\msg()` instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
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
            settype($value, 'string');
98
            $data[$placeholder] = $value;
99
        }
100
101
        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
    public static function ensureIsNotNull($obj)
113
    {
114
        if (is_null($obj)) {
115
            $msg = nml_msg('Provided object must not be NULL.');
0 ignored issues
show
Deprecated Code introduced by
The function nml_msg() has been deprecated with message: since v0.6.0, will be removed in v0.7.0. Use `\NelsonMartell\msg()` instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
116
            throw new InvalidArgumentException($msg);
117
        }
118
119
        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
    public static function ensureIsString($obj)
131
    {
132
        if (!is_string(static::ensureIsNotNull($obj))) {
133
            $msg = nml_msg('Provided object must to be an string; "{0}" given.', typeof($obj));
0 ignored issues
show
Deprecated Code introduced by
The function typeof() has been deprecated with message: since v0.6.0, will be removed in v0.7.0. Use `\NelsonMartell\typeof()` instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
Deprecated Code introduced by
The function nml_msg() has been deprecated with message: since v0.6.0, will be removed in v0.7.0. Use `\NelsonMartell\msg()` instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
134
            throw new InvalidArgumentException($msg);
135
        }
136
137
        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 = nml_msg('Provided string must not be empty.');
0 ignored issues
show
Deprecated Code introduced by
The function nml_msg() has been deprecated with message: since v0.6.0, will be removed in v0.7.0. Use `\NelsonMartell\msg()` instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
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 = nml_msg('Provided string must not be white spaces.');
0 ignored issues
show
Deprecated Code introduced by
The function nml_msg() has been deprecated with message: since v0.6.0, will be removed in v0.7.0. Use `\NelsonMartell\msg()` instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
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
    public static function ensureIsValidVarName($string)
187
    {
188
        $pattern = '/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/';
189
190
        if (!preg_match($pattern, static::ensureIsString($string))) {
191
            $msg = nml_msg('Provided string do not follows PHP variables naming convention: "{0}".', $string);
0 ignored issues
show
Deprecated Code introduced by
The function nml_msg() has been deprecated with message: since v0.6.0, will be removed in v0.7.0. Use `\NelsonMartell\msg()` instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
192
            throw new InvalidArgumentException($msg);
193
        }
194
195
        return $string;
196
    }
197
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
198