Completed
Push — master ( e2b1b5...0394bc )
by Ryan
02:27
created

UserMentions   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 3
lcom 0
cbo 0
dl 0
loc 55
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A find() 0 11 1
A linkify() 0 10 1
1
<?php namespace Anomaly\UsersModule\User;
2
3
use Anomaly\Streams\Platform\Routing\UrlGenerator;
4
5
/**
6
 * Class UserMentions
7
 *
8
 * @link   http://pyrocms.com/
9
 * @author PyroCMS, Inc. <[email protected]>
10
 * @author Ryan Thompson <[email protected]>
11
 */
12
class UserMentions
13
{
14
15
    /**
16
     * The URL generator.
17
     *
18
     * @var UrlGenerator
19
     */
20
    protected $url;
21
22
    /**
23
     * Create a new UserMentions instance.
24
     *
25
     * @param UrlGenerator $url
26
     */
27
    public function __construct(UrlGenerator $url)
28
    {
29
        $this->url = $url;
30
    }
31
32
    /**
33
     * Find all mentions in the text.
34
     *
35
     * @param $text
36
     * @return array
37
     */
38
    public function find($text)
39
    {
40
        preg_match_all('/(@\w+)/', $text, $matches);
41
42
        return array_map(
43
            function ($match) {
44
                return str_slug(substr($match, 1), '_');
45
            },
46
            array_unique(array_flatten($matches))
47
        );
48
    }
49
50
    /**
51
     * Replace mentions in the text with links.
52
     *
53
     * @param $text
54
     * @return string
55
     */
56
    public function linkify($text)
57
    {
58
        $url = str_replace(
59
            '__username__',
60
            '$2',
61
            route('anomaly.module.users::users.view', ['username' => '__username__'])
62
        );
63
64
        return preg_replace('/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '$1<a href="' . $url . '">@$2</a>', $text);
65
    }
66
}
67