StringFunctions   A
last analyzed

Complexity

Total Complexity 22

Size/Duplication

Total Lines 171
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 44
dl 0
loc 171
rs 10
c 0
b 0
f 0
wmc 22

11 Methods

Rating   Name   Duplication   Size   Complexity  
A isInt() 0 3 1
A isAlphaNum() 0 3 1
A endsWith() 0 8 2
A isEmail() 0 3 1
A completeDom() 0 5 1
A startsWith() 0 4 1
A isHexa() 0 3 1
A removeFromEnd() 0 6 2
A removeFromBeginning() 0 6 2
A isAllAlphaNum() 0 11 3
B getExcerpt() 0 36 7
1
<?php
2
3
namespace Core\Traits;
4
5
use Core\Constant;
6
use HTMLPurifier;
7
use HTMLPurifier_Config;
8
9
/**
10
 * a trait with some string related helpers
11
 * Trait StringFunctions
12
 * @package Core\Traits
13
 */
14
trait StringFunctions
15
{
16
    /**
17
     * does a haystack start with a needle ?
18
     * @param $haystack string the string to search in
19
     * @param $needle string the string to search for
20
     * @return bool
21
     */
22
    public function startsWith(string $haystack, string $needle): bool
23
    {
24
        $length = strlen($needle);
25
        return (substr($haystack, 0, $length) === $needle);
26
    }
27
28
    /**
29
     * Does a haystack end with a needle
30
     * @param $haystack string the string to search in
31
     * @param $needle string the string to search for
32
     * @return bool
33
     */
34
    public function endsWith(string $haystack, string $needle): bool
35
    {
36
        $length = strlen($needle);
37
        if ($length == 0) {
38
            return true;
39
        }
40
41
        return (substr($haystack, -$length) === $needle);
42
    }
43
44
    /**
45
     * Remove the tail of a string
46
     * @param $string string to slice apart
47
     * @param $tail string the string to remove
48
     * @return string
49
     */
50
    public function removeFromEnd(string $string, string $tail): string
51
    {
52
        if ($this->endsWith($string, $tail)) {
53
            $string = substr($string, 0, -strlen($tail));
54
        }
55
        return $string;
56
    }
57
58
    /**
59
     * remove some characters from the front of the string
60
     * @param string $string the string to be decapitated
61
     * @param string $head the head to be cut off ("OFF WITH HIS HEAD")
62
     * @return string
63
     */
64
    public function removeFromBeginning(string $string, string $head): string
65
    {
66
        if ($this->startsWith($string, $head)) {
67
            $string = substr($string, strlen($head));
68
        }
69
        return $string;
70
    }
71
72
    /**
73
     * create an excerpt, shortening the text to a specific number of words
74
     * @param string $text the text to shorten
75
     * @param int $count number of words
76
     * @return string the shortend text
77
     * @throws \ErrorException
78
     */
79
    public function getExcerpt(string $text, int $count = Constant::EXCERPT_WORD_COUNT):string
80
    {
81
        if ($count < 1) {
82
            throw new \ErrorException('excerpt length too low');
83
        }
84
        $text = str_replace("  ", " ", $text);
85
86
        //Searching for the page break tag
87
        $breakTagPosition = strpos($text, "<!-- EndOfExcerptBlogOc -->");
88
        if($breakTagPosition > 0){
89
            return $this->completeDom(substr($text, 0, $breakTagPosition));
90
        }
91
92
        //exploding on space except for in img, p and span.
93
        $string = preg_split('/(<img[^>]+\>)|(<p[^>]+\>)|(<span[^>]+\>)|\s/', $text, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
94
95
        //The preg split can return false, probably will never happen but just in case.
96
        if(!$string)
97
        {
98
            throw new \Error("excerpt generation failed");
99
        }
100
101
        if (count($string) <= $count) {
102
            return $text;
103
        }
104
        $trimmed = '';
105
        for ($wordCounter = 0; $wordCounter < $count; $wordCounter++) {
106
            $trimmed .= $string[$wordCounter];
107
            if ($wordCounter < $count - 1) {
108
                $trimmed .= " ";
109
            } else {
110
                $trimmed .= "[...]";
111
            }
112
        }
113
114
        return $this->completeDom($trimmed);
115
    }
116
117
    /**
118
     * Close the dom in given $text
119
     * @param string $text unclean html
120
     * @return string cleaned up html
121
     */
122
    private function completeDom(string $text): string
123
    {
124
        $config = HTMLPurifier_Config::createDefault();
125
        $purifier = new HTMLPurifier($config);
126
        return $purifier->purify($text);
127
    }
128
129
    /**
130
     * check passed string, returns true if the string contains alphaNum or _ or -. use for checking database tables, column names or slugs
131
     * @param string $string the string to analyse
132
     * @return bool
133
     */
134
    public function isAlphaNum(string $string): bool
135
    {
136
        return preg_match("/^[A-Za-z0-9_-]+$/", $string) === 1;
137
    }
138
139
    /**
140
     * check if each string in passed array is valid
141
     * @param array $strings
142
     * @return bool
143
     */
144
    public function isAllAlphaNum(array $strings):bool
145
    {
146
        $result = true;
147
        foreach ($strings as $string)
148
        {
149
            if(!$this->isAlphaNum($string))
150
            {
151
                $result = false;
152
            }
153
        }
154
        return $result;
155
    }
156
157
    /**
158
     * check is a string is hexadecimal
159
     * @param string $string
160
     * @return bool
161
     */
162
    public function isHexa(string $string):bool
163
    {
164
        return preg_match("/[\da-f]/",$string) === 1;
165
    }
166
167
    /**
168
     * check if the sent var is an integer
169
     * @param $int
170
     * @return bool
171
     */
172
    public function isInt($int):bool
173
    {
174
        return filter_var($int, FILTER_VALIDATE_INT) !== false;
175
    }
176
177
    /**
178
     * Verify if a string is a valid email
179
     * @param string $email
180
     * @return bool
181
     */
182
    public function isEmail(string $email):bool
183
    {
184
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
185
    }
186
187
}