WordRankManager::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace John\Cp;
4
5
use John\Exceptions\UrbanWordException;
6
use John\Exceptions\WordRankManagerException;
7
8
/**
9
 * WordRankManager: A class that returns the occurence of words in a sentence as an associative array
10
 * Class wordRanker.
11
 */
12
class WordRankManager
13
{
14
    /**
15
     * @var string
16
     */private $sentence;
17
18
    /**
19
     * WordRankManager constructor.
20
     *
21
     * @param string $sentence
22
     */
23
    public function __construct($sentence = '')
24
    {
25
        $this->sentence = $sentence;
26
    }
27
28
    /**
29
     * Return sentence to show occurence
30
     *
31
     * @return string
32
     */
33
    public function getWord()
34
    {
35
        return $this->sentence;
36
    }
37
38
    /**
39
     * Rank occurence of words in a sentence
40
     *
41
     * @return array
42
     *
43
     * @throws \John\Exceptions\WordRankManagerException
44
     */
45
    public function ranker()
46
    {
47
        if (! empty($this->sentence)) {
48
49
            $wordsArray = preg_split('/\s+/', $this->sentence);
50
            $rankedArray = [];
51
52
            foreach ($wordsArray as $word) {
53
54
                if (array_key_exists($word, $rankedArray)) {
55
56
                    $rankedArray[$word] += 1;
57
                } else {
58
                    $rankedArray[$word] = 1;
59
                }
60
            }
61
62
            if (arsort($rankedArray)) {
63
                return $rankedArray;
64
            }
65
        }
66
67
        throw new WordRankManagerException('Sentence is empty.');
68
    }
69
}
70