summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/stdlib/src/Str.php
blob: 9cf1cae23835c1f405458ed802e879cef4fb5ba2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php

namespace ipl\Stdlib;

/**
 * Collection of string manipulation functions
 */
class Str
{
    /**
     * Convert the given string to camel case
     *
     * The given string may be delimited by the following characters: '_' (underscore), '-' (dash), ' ' (space).
     *
     * @param ?string $subject
     *
     * @return string
     */
    public static function camel(?string $subject)
    {
        if ($subject === null) {
            return '';
        }

        $normalized = str_replace(['-', '_'], ' ', $subject);

        return lcfirst(str_replace(' ', '', ucwords(strtolower($normalized))));
    }

    /**
     * Check if the given string starts with the specified substring
     *
     * @param ?string $subject
     * @param string $start
     * @param bool   $caseSensitive
     *
     * @return bool
     */
    public static function startsWith(?string $subject, string $start, bool $caseSensitive = true)
    {
        $subject = $subject ?? '';
        if (! $caseSensitive) {
            return strncasecmp($subject, $start, strlen($start)) === 0;
        }

        return substr($subject, 0, strlen($start)) === $start;
    }

    /**
     * Split string into an array padded to the size specified by limit
     *
     * This method is a perfect fit if you need default values for symmetric array destructuring.
     *
     * @param ?string $subject
     * @param string $delimiter
     * @param int    $limit
     * @param mixed  $default
     *
     * @return array<int, mixed>
     */
    public static function symmetricSplit(?string $subject, string $delimiter, int $limit, $default = null)
    {
        if ($subject === null) {
            return array_pad([], $limit, $default);
        }

        return array_pad(explode($delimiter, $subject, $limit), $limit, $default);
    }

    /**
     * Split string into an array and trim spaces
     *
     * @param ?string $subject
     * @param string $delimiter
     * @param ?int    $limit
     *
     * @return array<string>
     */
    public static function trimSplit(?string $subject, string $delimiter = ',', int $limit = null)
    {
        if ($subject === null) {
            return [];
        }

        if ($limit !== null) {
            $exploded = explode($delimiter, $subject, $limit);
        } else {
            $exploded = explode($delimiter, $subject);
        }

        return array_map('trim', $exploded);
    }
}