Passed
Push — Showing-Posts ( c935cd...ca7424 )
by Stone
01:51
created

StringFunctions::endsWith()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Core\Traits;
4
5
use Core\Constant;
6
use Twig\Error\Error;
7
8
/**
9
 * a trait with some string related helpers
10
 * Trait StringFunctions
11
 * @package Core\Traits
12
 */
13
trait StringFunctions
14
{
15
    /**
16
     * does a haystack start with a needle ?
17
     * @param $haystack string the string to search in
18
     * @param $needle string the string to search for
19
     * @return bool
20
     */
21
    public function startsWith(string $haystack, string $needle): bool
22
    {
23
        $length = strlen($needle);
24
        return (substr($haystack, 0, $length) === $needle);
25
    }
26
27
    /**
28
     * Does a haystack end with a needle
29
     * @param $haystack string the string to search in
30
     * @param $needle string the string to search for
31
     * @return bool
32
     */
33
    public function endsWith(string $haystack, string $needle): bool
34
    {
35
        $length = strlen($needle);
36
        if ($length == 0) {
37
            return true;
38
        }
39
40
        return (substr($haystack, -$length) === $needle);
41
    }
42
43
    /**
44
     * Remove the tail of a string
45
     * @param $string string to slice apart
46
     * @param $tail string the string to remove
47
     * @return string
48
     */
49
    public function removeFromEnd(string $string, string $tail): string
50
    {
51
        if ($this->endsWith($string, $tail)) {
52
            $string = substr($string, 0, -strlen($tail));
53
        }
54
        return $string;
55
    }
56
57
    /**
58
     * remove some characters from the front of the string
59
     * @param string $string the string to be decapitated
60
     * @param string $head the head to be cut off ("OFF WITH HIS HEAD")
61
     * @return string
62
     */
63
    public function removeFromBeginning(string $string, string $head): string
64
    {
65
        if ($this->startsWith($string, $head)) {
66
            $string = substr($string, strlen($head));
67
        }
68
        return $string;
69
    }
70
71
    /**
72
     * create an excerpt, shortening the text to a specific number of words
73
     * @param string $text the text to shorten
74
     * @param int $count number of words
75
     * @return string the shortend text
76
     * @throws \ErrorException
77
     */
78
    public function getExcerpt(string $text, int $count = Constant::EXCERPT_WORD_COUNT)
79
    {
80
        if ($count < 1) {
81
            throw new \ErrorException('excerpt length too low');
82
        }
83
        $text = str_replace("  ", " ", $text);
84
        //exploding on space except for in img, p and span.
85
        $string = preg_split('/(<img[^>]+\>)|(<p[^>]+\>)|(<span[^>]+\>)|\s/', $text, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
86
        if (count($string) <= $count) {
0 ignored issues
show
Bug introduced by
It seems like $string can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

86
        if (count(/** @scrutinizer ignore-type */ $string) <= $count) {
Loading history...
87
            return $text;
88
        }
89
        $trimed = '';
90
        for ($wordCounter = 0; $wordCounter < $count; $wordCounter++) {
91
            //TODO Take into account the "read more" tag
92
            $trimed .= $string[$wordCounter];
93
            if ($wordCounter < $count - 1) {
94
                $trimed .= " ";
95
            } else {
96
                $trimed .= "[...]";
97
            }
98
        }
99
100
        //clean up unclosed html
101
        //grabbed from https://gist.github.com/JayWood/348752b568ecd63ae5ce#gistcomment-2310550
102
        libxml_use_internal_errors(true);
103
104
        $dom = new \DOMDocument;
105
        $dom->loadHTML($trimed);
106
107
        // Strip wrapping <html> and <body> tags
108
        $mock = new \DOMDocument;
109
        $body = $dom->getElementsByTagName('body')->item(0);
110
        foreach ($body->childNodes as $child) {
111
            $mock->appendChild($mock->importNode($child, true));
112
        }
113
114
        $fixed = trim($mock->saveHTML());
115
        
116
        return $fixed;
117
    }
118
119
    /**
120
     * check passed string, returns true if the string contains alphaNum or _ or -. use for checking database tables, column names or slugs
121
     * @param string $string the string to analyse
122
     * @return bool
123
     */
124
    public function isAlphaNum(string $string): bool
125
    {
126
        if (preg_match("/^[A-Za-z0-9_-]+$/", $string)) {
127
            return true;
128
        }
129
        return false;
130
    }
131
}