|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace WebVision\DeeplWrite\Readability\Calculator; |
| 6 | + |
| 7 | +use Symfony\Component\DependencyInjection\Attribute\AsTaggedItem; |
| 8 | +use WebVision\DeeplWrite\Readability\Result\ReadabilityResult; |
| 9 | + |
| 10 | +/** |
| 11 | + * This class is an implementation generating the Flesch Reading Ease score for German. |
| 12 | + * It calculates as follows: |
| 13 | + * |
| 14 | + * FRE = 206.835 - (1.015 * Average sentence Length (ASL)) - (84.6 * Average word length (AWL)) |
| 15 | + * |
| 16 | + * ASL = (number of words) / (number of sentences) |
| 17 | + * ASW = (number of syllables) / (number of words) |
| 18 | + * |
| 19 | + * The corresponding score is between 0 and 100, where |
| 20 | + * * 0 means really difficult to read |
| 21 | + * * 100 means really easy to read |
| 22 | + * |
| 23 | + * For a better overview of the different scoring levels, |
| 24 | + * @see https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests#Flesch_reading_ease |
| 25 | + */ |
| 26 | +#[AsTaggedItem('deepl.readability')] |
| 27 | +final class FleschKincaidEnglish extends AbstractReadabilityCalculator |
| 28 | +{ |
| 29 | + protected const LANGUAGE = 'en-us'; |
| 30 | + public function calculateReadability(string $text): ReadabilityResult |
| 31 | + { |
| 32 | + $sentences = $this->countSentences($text); |
| 33 | + $words = $this->countWords($text); |
| 34 | + $syllables = $this->countSyllables($text); |
| 35 | + $characters = $this->countCharacters($text); |
| 36 | + return new ReadabilityResult( |
| 37 | + $text, |
| 38 | + $sentences, |
| 39 | + $words, |
| 40 | + $syllables, |
| 41 | + $characters, |
| 42 | + $this->calculateScore($words, $sentences, $syllables) |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + private function calculateScore( |
| 47 | + int $words, |
| 48 | + int $sentences, |
| 49 | + int $syllables |
| 50 | + ): float { |
| 51 | + if ($sentences <= 0) { |
| 52 | + $sentences = 1; |
| 53 | + } |
| 54 | + if ($words <= 0) { |
| 55 | + throw new \InvalidArgumentException( |
| 56 | + 'The number of words can not be negative or zero!', |
| 57 | + 1757680362 |
| 58 | + ); |
| 59 | + } |
| 60 | + |
| 61 | + // Too easy sentences and short texts COULD result in calculating a value above 100. In this case |
| 62 | + // set the result to 100, as this is the maximum. |
| 63 | + // This is a known issue in this formula, but can be ignored for a quick overview, as |
| 64 | + // 100 means very easy to read. |
| 65 | + $fleschKincaid = 206.835 - 1.015 * ($words/$sentences) - (84.6 * $syllables/$words); |
| 66 | + return ($fleschKincaid <= 100.0) ? $fleschKincaid : 100.0; |
| 67 | + } |
| 68 | +} |
0 commit comments