Completed
Pull Request — master (#11)
by Gordon
32:16 queued 19:36
created

RandomEnglishGenerator::sentence()   C

Complexity

Conditions 10
Paths 86

Size

Total Lines 73

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 73
rs 6.7224
c 0
b 0
f 0
cc 10
nc 86
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php declare(strict_types = 1);
2
3
namespace Suilven\RandomEnglish;
4
5
use Suilven\RandomEnglish\Helper\LanguageHelper;
6
7
class RandomEnglishGenerator
8
{
9
10
    private const POSSIBLE_WORD_TYPES = [
11
        'noun',
12
        'countable_noun',
13
14
        'adjective',
15
        'preposition',
16
        'conjunction',
17
        'contraction',
18
        'control_verb',
19
20
        'sequence_adverb',
21
        'frequency_adverb',
22
23
        // pluralize and ing these?
24
        'intransitive_verb',
25
        'irregular_verb',
26
        'transitive_verb',
27
        'verb',
28
29
        'intransitive_verb_ing',
30
        'irregular_verb_ing',
31
        'transitive_verb_ing',
32
        'verb_ing',
33
34
35
        // positions
36
        'locative',
37
38
        'plural_noun',
39
40
41
        // names
42
        'mens_name',
43
        'womens_name',
44
    ];
45
46
    /** @var string configuration file for sentences */
47
    private $config = '';
48
49
    public function __construct()
50
    {
51
        $configFile = \dirname(__FILE__) . '/../config/sentence-structure.cfg';
52
        $this->setConfig(\file_get_contents($configFile));
53
    }
54
55
56
    /** @param string $newConfig configuration file of how sentence structures */
57
    public function setConfig(string $newConfig): void
58
    {
59
        $this->config = \trim($newConfig);
60
    }
61
62
63
    /**
64
     * Generate a random sentence
65
     *
66
     * @param bool $titleCase true to generate a title, false (default) to generate a sentence
67
     * @return string a random sentence
68
     */
69
    public function sentence(bool $titleCase = false): string
70
    {
71
        // choose a random sentence structure
72
        $structures = \explode(\PHP_EOL, $this->config);
73
        \shuffle($structures);
74
        $structure = $structures[0];
75
        
76
        $expression='/[\s]+/';
77
        $splits = \preg_split($expression, $structure, -1, \PREG_SPLIT_NO_EMPTY);
78
79
        $sentenceArray = [];
80
81
        foreach ($splits as $possiblyRandomWord) {
82
            $randomized = false;
83
84
            foreach (self::POSSIBLE_WORD_TYPES as $wordType) {
85
                $pluralNoun = ($wordType === 'plural_noun');
86
                if ($pluralNoun) {
87
                    $wordType = 'noun';
88
                    $possiblyRandomWord = \str_replace('plural_', '', $possiblyRandomWord);
89
                }
90
91
                $ing = \substr($wordType, -4)=== '_ing';
92
                if ($ing) {
93
                    $wordType = \str_replace('_ing', '', $wordType);
94
                    $possiblyRandomWord = \str_replace('_ing', '', $possiblyRandomWord);
95
                }
96
                $start = '[' . $wordType . ']';
97
98
                if (\substr($possiblyRandomWord, 0, \strlen($start)) !== $start) {
99
                    continue;
100
                }
101
102
                $restOfWord = \str_replace($start, '', $possiblyRandomWord);
103
                $randomWord = $this->getRandomWord($wordType);
104
                if ($pluralNoun) {
105
                    $helper = new LanguageHelper();
106
107
                    $randomWord = $helper->pluralizeNoun($randomWord);
108
                }
109
                if ($ing) {
110
                    $helper = new LanguageHelper();
111
                    $randomWord = $helper->ingVerb($randomWord);
112
                }
113
                $sentenceArray[] =$randomWord . $restOfWord;
114
                $randomized = true;
115
116
                break;
117
            }
118
119
            if ($randomized) {
120
                continue;
121
            }
122
123
            $sentenceArray[] =
124
                $possiblyRandomWord;
125
        }
126
127
        // ensure sentence starts with a capital
128
        $sentenceArray[0] = \ucfirst($sentenceArray[0]);
129
130
        $result = \implode(" ", $sentenceArray) . '.';
131
132
        if ($titleCase) {
133
            $result = \ucwords($result);
134
            $result = \substr_replace($result, "", -1);
135
        }
136
137
        $result = \str_replace('?.', '?', $result);
138
        $result = \str_replace('!.', '?', $result);
139
140
        return $result;
141
    }
142
143
144
    /**
145
     * Generate a random title
146
     *
147
     * @return string a random sentence, all in caps, no trailing full stop
148
     */
149
    public function title(): string
150
    {
151
        return $this->sentence(true);
152
    }
153
154
155
    /**
156
     * @param int $maxSentences The maximum number of sentences
157
     * @return string a paragraph of random sentences
158
     */
159
    public function paragraph(int $maxSentences = 10): string
160
    {
161
        $nParagraph = \rand(1, $maxSentences);
162
        $sentences = [];
163
164
        for ($i=0; $i< $nParagraph; $i++) {
165
            $sentences[] = $this->sentence();
166
        }
167
168
        return \implode("  ", $sentences);
169
    }
170
171
172
    /** @return string a plural noun */
173
    public function pluralNoun(): string
174
    {
175
        $plurableNoun = $this->getRandomWord('countable_noun');
176
177
        return $plurableNoun . 's';
178
    }
179
180
181
    /** @return string a plural verb */
182
    public function pluralVerb(): string
183
    {
184
        // @todo Choose a random verb source file
185
        $plurableNoun = $this->getRandomWord('verb');
186
187
        return $plurableNoun . 's';
188
    }
189
190
191
    /** @return string doing version of a verb */
192
    public function verbing(): string
193
    {
194
        // @todo Choose a random verb source file
195
        $plurableNoun = $this->getRandomWord('verb');
196
197
        return $plurableNoun . 'ing';
198
    }
199
200
201
    /**
202
     * @param string $wordType the type of word, e.g. noun, verb
203
     * @return string a random word for the given word type
204
     */
205
    private function getRandomWord(string $wordType): string
206
    {
207
        $wordsFile = \dirname(__FILE__) . '/../words/english_' . $wordType . 's.txt';
208
        $words = \explode(\PHP_EOL, \trim(\file_get_contents($wordsFile)));
209
        \shuffle($words);
210
211
        return $words[0];
212
    }
213
}
214