Helper Component


Helper - 图1

Overview

Phalcon\Helper a component exposing helper classes and static methods used throughout the framework.

Arr

Phalcon\Helper\Arr exposes static methods that offer quick access to common functionality when working with arrays.

chunk

  1. final public static function chunk(
  2. array $collection,
  3. int $size,
  4. bool $preserveKeys = false
  5. ): array

Chunks an array into smaller arrays of a specified size.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $source = [
  4. 'k1' => 1,
  5. 'k2' => 2,
  6. 'k3' => 3,
  7. 'k4' => 4,
  8. 'k5' => 5,
  9. 'k6' => 6,
  10. ];
  11. $chunks = Arr::chunk($source, 2);
  12. // [
  13. // [1, 2],
  14. // [3, 4],
  15. // [5, 6],
  16. // ]

first

  1. final public static function first(
  2. array $collection,
  3. mixed $method = null
  4. ): var

Returns the first element of the collection. If a callable is passed, the element returned is the first that validates true

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. 'Phalcon',
  5. 'Framework',
  6. ];
  7. echo Arr::first($collection); // 'Phalcon'
  8. $result = Arr::first(
  9. $collection,
  10. function ($element) {
  11. return strlen($element) > 8;
  12. }
  13. );
  14. echo $result; // 'Framework'

firstKey

  1. final public static function firstKey(
  2. array $collection,
  3. mixed $method = null
  4. ): var

Returns the key of the first element of the collection. If a callable is passed, the element returned is the first that validates true

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. 1 => 'Phalcon',
  5. 3 => 'Framework',
  6. ];
  7. echo Arr::firstKey($collection); // 1
  8. $result = Arr::firstKey(
  9. $collection,
  10. function ($element) {
  11. return strlen($element) > 8;
  12. }
  13. );
  14. echo $result; // 3

flatten

  1. final public static function flatten(
  2. array $collection,
  3. bool $deep = false
  4. ): array

Flattens an array up to the one level depth. If $deep is set to true, it traverses all elements and flattens them all.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $source = [1, [2], [[3], 4], 5];
  4. var_dump(
  5. Arr::flatten($source)
  6. );
  7. // [1, 2, [3], 4, 5];
  8. $source = [1, [2], [[3], 4], 5];
  9. var_dump(
  10. Arr::flatten($source, true)
  11. );
  12. // [1, 2, 3, 4, 5];

get

  1. final public static function get(
  2. array $collection,
  3. mixed $index,
  4. mixed $defaultValue
  5. ): mixed

Retrieves an element from an array. If the element exists its value is returned. If not, the defaultValue is returned.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $data = [
  4. 'colors' => [
  5. 'red',
  6. 'white',
  7. 'blue',
  8. ],
  9. 'year' => 1776,
  10. ];
  11. echo Arr::get($data, 'year'); // 1776
  12. echo Arr::get($data, 'unknown', 1776); // 1776

group

  1. final public static function group(
  2. array $collection,
  3. mixed $method
  4. ): array

Groups the elements of an array based on the passed callable and returns the array of the groupped elements back. The callable can be a string as the element name, a callable or a method available. The array can contain sub arrays as elements or objects with relevant properties.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. ['name' => 'Paul', 'age' => 34],
  5. ['name' => 'Peter', 'age' => 31],
  6. ['name' => 'John', 'age' => 29],
  7. ];
  8. $result = Arr::group($collection, 'age');
  9. var_dump($result);
  10. // [
  11. // 34 => [
  12. // [
  13. // 'name' => 'Paul',
  14. // 'age' => 34,
  15. // ],
  16. // ],
  17. // 31 => [
  18. // [
  19. // 'name' => 'Peter',
  20. // 'age' => 31,
  21. // ],
  22. // ],
  23. // 29 => [
  24. // [
  25. // 'name' => 'John',
  26. // 'age' => 29,
  27. // ],
  28. // ],
  29. // ]
  30. $peter = new \stdClass();
  31. $peter->name = 'Peter';
  32. $peter->age = 34;
  33. $paul = new \stdClass();
  34. $paul->name = 'Paul';
  35. $paul->age = 31;
  36. $collection = [
  37. 'peter' => $peter,
  38. 'paul' => $paul,
  39. ];
  40. $result = = Arr::group($collection, 'name');
  41. var_dump($result);
  42. // [
  43. // 'Peter' => [
  44. // stdClass(
  45. // name : 'Peter',
  46. // age : 34
  47. // ),
  48. // ],
  49. // 'Paul' => [
  50. // stdClass(
  51. // name : 'Paul',
  52. // age : 31
  53. // ),
  54. // ],
  55. // ]
  56. $collection = ['one', 'two', 'three'];
  57. $result = Arr::group($collection, 'strlen');
  58. var_dump($result);
  59. // [
  60. // 3 => ['one', 'two'],
  61. // 5 => ['three']
  62. // ]

has

  1. final public static function has(array $collection, mixed $index): bool

Checks if an element exists in an array. Returns true if found, false otherwise.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $data = [
  4. 'colors' => [
  5. 'red',
  6. 'white',
  7. 'blue',
  8. ],
  9. 'year' => 1776,
  10. ];
  11. echo Arr::has($data, 'year'); // true
  12. echo Arr::has($data, 'unknown'); // false

isUnique

  1. final public static function isUnique(array $collection): bool

Checks a flat list for duplicate values. Returns true if duplicate values exist and false if values are all unique.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. 'Phalcon',
  5. 'Framework',
  6. ];
  7. $result = Arr::isUnique($collection); // true
  8. $collection = [
  9. 'Phalcon',
  10. 'Framework',
  11. 'Phalcon',
  12. ];
  13. $result = Arr::isUnique($collection); // false

last

  1. final public static function last(
  2. array $collection,
  3. mixed $method = null
  4. ): var

Returns the last element of the collection. If a callable is passed, the element returned is the last that validates true

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. 'Phalcon',
  5. 'Framework',
  6. ];
  7. echo Arr::last($collection); // 'Framework'
  8. $result = Arr::last(
  9. $collection,
  10. function ($element) {
  11. return strlen($element) < 8;
  12. }
  13. );
  14. echo $result; // 'Phalcon'

lastKey

  1. final public static function lastKey(
  2. array $collection,
  3. mixed $method = null
  4. ): var

Returns the key of the last element of the collection. If a callable is passed, the element returned is the last that validates true

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. 1 => 'Phalcon',
  5. 3 => 'Framework',
  6. ];
  7. echo Arr::firstKey($collection); // 3
  8. $result = Arr::firstKey(
  9. $collection,
  10. function ($element) {
  11. return strlen($element) < 8;
  12. }
  13. );
  14. echo $result; // 1

order

  1. final public static function order(
  2. array $collection,
  3. mixed $attribute,
  4. string $order = 'asc'
  5. ): array

Sorts a collection of arrays or objects by attribute and returns the sorted array. The third parameter controls the sort order.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. ['id' => 2],
  5. ['id' => 3],
  6. ['id' => 1],
  7. ];
  8. $result = Arr::order($collection, 'id');
  9. var_dump($result);
  10. // [
  11. // ['id' => 1],
  12. // ['id' => 2],
  13. // ['id' => 3],
  14. // ]
  15. $result = Arr::order($collection, 'id', 'desc');
  16. var_dump($result);
  17. // [
  18. // ['id' => 3],
  19. // ['id' => 2],
  20. // ['id' => 1],
  21. // ]

pluck

  1. final public static function pluck(
  2. array $collection,
  3. string element
  4. ): array

Retrieves all of the values for a given key returning them as an array

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. ['product_id' => 'prod-100', 'name' => 'Desk'],
  5. ['product_id' => 'prod-200', 'name' => 'Chair'],
  6. ];
  7. $result = Arr::pluck($collection, 'name');
  8. var_dump($result);
  9. // [
  10. // 'Desk',
  11. // 'Chair'
  12. // ]

set

  1. final public static function set(
  2. array $collection,
  3. mixed $value,
  4. mixed $index = null
  5. ): array

Sets an array element and returns the new array back. The third parameter is the index/key.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [];
  4. $result = Arr::set($collection, 'Phalcon');
  5. var_dump($result);
  6. // [
  7. // 0 => 'Phalcon',
  8. // ]
  9. $collection = [
  10. 1 => 'Phalcon'
  11. ];
  12. $result = Arr::set($collection, 'Framework', 1);
  13. var_dump($result);
  14. // [
  15. // 1 => 'Framework',
  16. // ]

sliceLeft

  1. final public static function sliceLeft(
  2. array $collection,
  3. int $elements = 1
  4. ): array

Returns a new array with n elements removed from the left.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. 'Phalcon',
  5. 'Framework',
  6. 'for',
  7. 'PHP',
  8. ];
  9. $result = Arr::sliceLeft($collection, 1);
  10. var_dump($result);
  11. // [
  12. // 'Phalcon',
  13. // ]
  14. $result = Arr::sliceLeft($collection, 3);
  15. var_dump($result);
  16. // [
  17. // 'Phalcon',
  18. // 'Framework',
  19. // 'for',
  20. // ]

sliceRight

  1. final public static function sliceRight(
  2. array $collection,
  3. int $elements = 1
  4. ): array

Returns a new array with n elements removed from the right.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. 'Phalcon',
  5. 'Framework',
  6. 'for',
  7. 'PHP',
  8. ];
  9. $result = Arr::sliceRight($collection, 1);
  10. var_dump($result);
  11. // [
  12. // 'Framework',
  13. // 'for',
  14. // 'PHP',
  15. // ]
  16. $result = Arr::sliceRight($collection, 3);
  17. var_dump($result);
  18. // [
  19. // 'PHP',
  20. // ]

split

  1. final public static function split(array $collection): array

Returns a new array with keys of the passed array as one element and values as another.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. 1 => 'Phalcon',
  5. 3 => 'Framework',
  6. ];
  7. $result = Arr::split($collection);
  8. var_dump($result);
  9. // [
  10. // [1, 3],
  11. // ['Phalcon', 'Framework']
  12. // ]

toObject

  1. final public static function toObject(array $collection)

Converts an array to an object

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. 1 => 'Phalcon',
  5. 3 => 'Framework',
  6. ];
  7. $result = Arr::toObject($collection);
  8. var_dump($result);
  9. // object(stdClass)#1 (2) {
  10. // ["1"] => string(7) "Phalcon"
  11. // ["3"] => string(9) "Framework"
  12. // }

validateAll

  1. final public static function validateAll(
  2. array $collection,
  3. mixed $method
  4. ): bool

Returns true if the provided function returns true for all elements of the collection, false otherwise.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [2, 3, 4, 5];
  4. $result = Arr::validateAll(
  5. $collection,
  6. function ($element) {
  7. return $element > 1;
  8. }
  9. );
  10. var_dump($result); // true

validateAny

  1. final public static function validateAny(
  2. array $collection,
  3. mixed $method
  4. ): bool

Returns true if the provided function returns true for at least one element of the collection, false otherwise.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [2, 3, 4, 5];
  4. $result = Arr::validateAny(
  5. $collection,
  6. function ($element) {
  7. return $element > 4;
  8. }
  9. );
  10. var_dump($result); // true

whiteList

  1. final public static function whiteList(
  2. array $collection,
  3. array $whiteList
  4. ): array

Returns a subset of the array, white listing elements by key. The returned array contains only the elements of the source array that have keys identical to the whitelist array that was passed as a parameter.

  1. <?php
  2. use Phalcon\Helper\Arr;
  3. $collection = [
  4. 2 => 'Phalcon',
  5. 3 => 'Apples',
  6. 'one' => 'Framework',
  7. 'two' => 'Oranges',
  8. ];
  9. $result = Arr::whiteList(
  10. $collection,
  11. [2, 'one']
  12. );
  13. var_dump($result);
  14. // [
  15. // 2 => 'Phalcon',
  16. // 'one' => 'Framework'
  17. // ]

Exception

Any exceptions thrown in the Phalcon\Helper* components will be of this type: Phalcon\Helper\Exception

Fs

Phalcon\Helper\Fs exposes static methods that offer file operation helper methods

basename

  1. final public static function basename(
  2. int $uri,
  3. mixed $suffix
  4. ) -> string

Gets the filename from a given path, This method is similar to PHP’s basename() but has non-ASCII character support. PHP’s basename() does not properly support streams or filenames beginning with a non-US-ASCII character.

  1. <?php
  2. use Phalcon\Helper\Fs;
  3. $file = '/file/热爱中文.txt';
  4. echo Fs::basename($file); // '热爱中文.txt'
  5. $file = '/myfolder/日本語のファイル名.txt';
  6. echo Fs::basename($file); // '日本語のファイル名.txt'
  7. $file = '/root/ελληνικά.txt';
  8. echo Fs::basename($file); // 'ελληνικά.txt';

Number

Phalcon\Helper\Number exposes static methods that offer quick access to common functionality when working with numbers.

between

final public static function between(
    int $value, 
    int $from, 
    int $to
) -> bool

Checks if the passed value is between the range specified in from and to

<?php

use Phalcon\Helper\Number;

$min   = 10;
$max   = 100;
$value = 13;

echo Number::between($value, $min, $max);   // true

$value = 2;
echo Number::between($value, $min, $max);   // false

Str

Phalcon\Helper\Str exposes static methods that offer quick manipulations to strings.

camelize

final public static function camelize(string $text, mixed $delimiter = null): string

Converts strings to camelize style

<?php

use Phalcon\Helper\Str;

echo Str::camelize('coco_bongo');         // CocoBongo
echo Str::camelize('co_co-bon_go', '-');  // Co_coBon_go
echo Str::camelize('co_co-bon_go', '_-'); // CoCoBonGo

concat

final public static function concat(
    string $separator, 
    string $a, 
    string $b 
    [, string $x] ... 
): string

Concatenates strings using the separator only once, removing duplicate delimiters. The first parameter is the separator, the subsequent ones are the strings to concatenate together. The minimum required parameters are three.

<?php

use Phalcon\Helper\Str;

$folder = Str::concat(
    '/',
    '/tmp/',
    '/folder_1/',
    '/folder_2',
    'folder_3/'
);

echo $folder; // /tmp/folder_1/folder_2/folder_3/

countVowels

final public static function countVowels(string $text): int

Returns number of vowels in provided string. Uses a regular expression to count the number of vowels (A, E, I, O, U) in a string.

<?php

use Phalcon\Helper\Str;

$source = 'Luke, I am your father!';

echo Str::countVowels($source); // 8

decapitalize

final public static function decapitalize(
    string $text, 
    bool $upperRest = false, 
    string $encoding = 'UTF-8'
): string

Decapitalizes the first letter of the string and then adds it back. If the upperRest parameter is set to false the rest of the string remains intact, otherwise it is converted to uppercase. The method will try to use methods provided by the mbstring extension and use the PHP equivalent as a fallback. The last parameter is the encoding that mbstring methods will use. It defaults to UTF-8.

<?php

use Phalcon\Helper\Str;

$source   = 'BeetleJuice';

echo Str::decapitalize($source);       // beetleJuice
echo Str::decapitalize($source, true); // bEETLEJUICE

decrement

final public static function decrement(
    string $text, 
    string $separator = '_'
): string

Removes a number from a string or decrements that number if it already is defined.

<?php

use Phalcon\Helper\Str;

echo Str::decrement('a_1'); // 'a'
echo Str::decrement('a_2'); // 'a_1'

dirFromFile

final public static function dirFromFile(string $file): string

Accepts a file name (without extension) and returns a calculated directory structure with the filename in the end

<?php

use Phalcon\Helper\Str;

echo Str::dirFromFile("file1234.jpg"); // fi/le/12/

dirSeparator

final public static function dirSeparator(string $directory): string

Accepts a directory name and ensures that it ends with DIRECTORY_SEPARATOR

<?php

use Phalcon\Helper\Str;

echo Str::dirSeparator("/home/phalcon"); // /home/phalcon/

dynamic

final public static function dynamic(
    string $text,
    string $leftDelimiter = '{',
    string $rightDelimiter = '}',
    string $separator = '|'
): string

Generates random text based on the template. The template needs separators as well as a delimiter for the different values. The defaults for those can be overridden with the method parameters.

<?php

use Phalcon\Helper\Str;

echo Str::dynamic('{Han|Leia|Luke} {Solo|Skywalker}!');  // Han Solo
echo Str::dynamic('{Han|Leia|Luke} {Solo|Skywalker}!');  // Leia Skywalker
echo Str::dynamic('{Han|Leia|Luke} {Solo|Skywalker}!');  // Luke Solo

endsWith

final public static function endsWith(
    string $text, 
    string $end, 
    bool $ignoreCase = true
): bool

Returns true if a string ends with a given string. If the last parameter is true (default), the search is made in a case-insensitive manner.

<?php

use Phalcon\Helper\Str;

echo Str::endsWith('Hello', 'llo');        // true
echo Str::endsWith('Hello', 'LLO', false); // false
echo Str::endsWith('Hello', 'LLO');        // true

firstBetween

final public static function firstBetween(
    string $haystack,
    string $start,
    string $end
): string

Returns the first string there is between the strings from the parameter start and end. The method will try to use methods provided by the mbstring extension and use the PHP equivalent as a fallback.

<?php

use Phalcon\Helper\Str;

$source   = 'This is a [custom] string with [other] stuff';

echo Str::firstBetween($source, '[', ']'); // custom

humanize

final public static function humanize(string $text): string

Makes an underscored or dashed phrase human-readable

<?php

use Phalcon\Helper\Str;

echo Str::humanize('start-a-horse'); // 'start a horse'
echo Str::humanize('five_cats');     // 'five cats'

includes

final public static function includes(
    string $needle, 
    string $haystack
): bool

Checks if a string is included in another string. Returns true if it is included, false otherwise. The method will try to use methods provided by the mbstring extension and use the PHP equivalent as a fallback.

<?php

use Phalcon\Helper\Str;

echo Str::includes('start', 'start-a-horse'); // true
echo Str::includes('end', 'start-a-horse'); // false

increment

final public static function increment(
    string $text, 
    string $separator = '_'
): string

Adds a number to a string or increment that number if it already is defined.

<?php

use Phalcon\Helper\Str;

echo Str::increment('a');   // 'a_1'
echo Str::increment('a_1'); // 'a_2'

isAnagram

final public static function isAnagram(
    string $first, 
    string $second
): bool

Compare two strings and returns true if both strings are anagram, false otherwise.

<?php

use Phalcon\Helper\Str;

echo Str::isAnagram('rail safety', 'fairy tales'); // true

isLower

final public static function isLower(
    string $text, 
    string $encoding = 'UTF-8'
):  bool

Returns true if the given string is lower case, false otherwise. The method will try to use methods provided by the mbstring extension and use the PHP equivalent as a fallback. The last parameter is the encoding that mbstring methods will use. It defaults to UTF-8.

<?php

use Phalcon\Helper\Str;

echo Str::isLower('phalcon framework'); // true
echo Str::isLower('Phalcon Framework'); // false

isPalindrome

final public static function isPalindrome(string $text): bool

Returns true if the given string is a palindrome, false otherwise.

<?php

use Phalcon\Helper\Str;

echo Str::isPalindrome('racecar'); // true

isUpper

final public static function isUpper(
    string $text, 
    string $encoding = 'UTF-8'
):  bool

Returns true if the given string is upper case, false otherwise. The method will try to use methods provided by the mbstring extension and use the PHP equivalent as a fallback. The last parameter is the encoding that mbstring methods will use. It defaults to UTF-8.

<?php

use Phalcon\Helper\Str;

echo Str::isUpper('PHALCON FRAMEWORK'); // true
echo Str::isUpper('Phalcon Framework'); // false

lower

final public static function lower(
    string $text, 
    string $encoding = 'UTF-8'
): string

Converts a string to lowercase characters. The method will try to use methods provided by the mbstring extension and use the PHP equivalent as a fallback. The last parameter is the encoding that mbstring methods will use. It defaults to UTF-8.

<?php

use Phalcon\Helper\Str;

echo Str::lower('PHALCON FRAMEWORK'); // phalcon framework

random

final public static function random(
    int $type = 0, 
    long $length = 8
): string

Generates a random string based on the given type. The first parameter is one of the RANDOM_* constants. The second parameter specifies the length of the string (defaults to 8).

  • RANDOM_ALNUM
  • RANDOM_ALPHA
  • RANDOM_DISTINCT
  • RANDOM_HEXDEC
  • RANDOM_NOZERO
  • RANDOM_NUMERIC
<?php

use Phalcon\Helper\Str;

echo Str::random(Str::RANDOM_ALNUM); // 'aloiwkqz'

reduceSlashes

final public static function reduceSlashes(string $text): string

Reduces multiple slashes in a string to single slashes. If a scheme is present (https://, ftp:// it will not be changed)

<?php

use Phalcon\Helper\Str;

echo Str::reduceSlashes('foo//bar/baz');             // foo/bar/baz
echo Str::reduceSlashes('http://foo.bar///baz/buz'); // http://foo.bar/baz/buz
echo Str::reduceSlashes('//foo.bar///baz/buz');      // /foo.bar/baz/buz
echo Str::reduceSlashes('ftp://foo.bar///baz/buz');  // ftp://foo.bar/baz/buz
echo Str::reduceSlashes('ftp//foo.bar///baz/buz');   // ftp/foo.bar/baz/buz

startsWith

final public static function startsWith(
    string $text, 
    string $start, 
    bool $ignoreCase = true
): bool

Returns true if a string starts with a given string. If the last parameter is true (default), the search is made in a case-insensitive manner.

<?php

use Phalcon\Helper\Str;

echo Str::startsWith('Hello', 'He');        // true
echo Str::startsWith('Hello', 'he', false); // false
echo Str::startsWith('Hello', 'he');        // true

uncamelize

final public static function uncamelize(
    string $text,   
    mixed $delimiter = null
): string

Uncamelize strings which are camelized

<?php

use Phalcon\Helper\Str;

echo Str::uncamelize('CocoBongo');      // coco_bongo
echo Str::uncamelize('CocoBongo', '-'); // coco-bongo

underscore

final public static function underscore(string $text): string

Makes a phrase underscored instead of spaced.

<?php

use Phalcon\Helper\Str;

echo Str::underscore('look behind');     // 'look_behind'
echo Str::underscore('Awesome Phalcon'); // 'Awesome_Phalcon'

upper

final public static function upper(
    string $text, 
    string $encoding = 'UTF-8'
): string

Converts a string to uppercase characters. The method will try to use methods provided by the mbstring extension and use the PHP equivalent as a fallback. The last parameter is the encoding that mbstring methods will use. It defaults to UTF-8.

<?php

use Phalcon\Helper\Str;

echo Str::upper('phalcon framework'); // PHALCON FRAMEWORK