├── .all-contributorsrc
├── .github
└── workflows
│ └── php.yml
├── .gitignore
├── LICENSE
├── README.md
├── composer.json
├── phpunit.xml.dist
├── readable.png
├── src
├── ReadableURL.php
└── lang
│ ├── Language.php
│ ├── LanguageHelper.php
│ ├── en
│ ├── En.php
│ └── words
│ │ ├── adjectives.txt
│ │ └── nouns.txt
│ └── ko
│ ├── Ko.php
│ └── words
│ ├── adjectives.txt
│ └── nouns.txt
└── tests
├── GenerateTest.php
└── lang
├── EnTest.php
└── KoTest.php
/.all-contributorsrc:
--------------------------------------------------------------------------------
1 | {
2 | "files": [
3 | "README.md"
4 | ],
5 | "imageSize": 100,
6 | "commit": false,
7 | "contributors": [
8 | {
9 | "login": "ddarkr",
10 | "name": "도다",
11 | "avatar_url": "https://avatars1.githubusercontent.com/u/6638675?v=4",
12 | "profile": "https://github.com/ddarkr",
13 | "contributions": [
14 | "code"
15 | ]
16 | },
17 | {
18 | "login": "JulianOtten",
19 | "name": "Yukihyõ",
20 | "avatar_url": "https://avatars.githubusercontent.com/u/32372051?v=4",
21 | "profile": "https://github.com/JulianOtten",
22 | "contributions": [
23 | "code"
24 | ]
25 | }
26 | ],
27 | "contributorsPerLine": 7,
28 | "projectName": "readable-url",
29 | "projectOwner": "HyungJu",
30 | "repoType": "github",
31 | "repoHost": "https://github.com",
32 | "skipCi": true
33 | }
34 |
--------------------------------------------------------------------------------
/.github/workflows/php.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 |
3 | on:
4 | push:
5 | branches: [ master ]
6 | pull_request:
7 | branches: [ master ]
8 |
9 | jobs:
10 | build:
11 |
12 | runs-on: ubuntu-latest
13 |
14 | steps:
15 | - uses: actions/checkout@v2
16 |
17 | - name: Validate composer.json and composer.lock
18 | run: composer validate
19 |
20 | - name: Cache Composer packages
21 | id: composer-cache
22 | uses: actions/cache@v2
23 | with:
24 | path: vendor
25 | key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
26 | restore-keys: |
27 | ${{ runner.os }}-php-
28 |
29 | - name: Install dependencies
30 | if: steps.composer-cache.outputs.cache-hit != 'true'
31 | run: composer install --prefer-dist --no-progress --no-suggest
32 |
33 | - name: Run test suite
34 | run: composer test
35 | - name: Codecov
36 | uses: codecov/codecov-action@v1.0.13
37 | with:
38 | # User defined upload name. Visible in Codecov UI
39 | name: ReadableURL
40 |
41 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /vendor/
2 | .idea/
3 | composer.lock
4 | .phpunit.result.cache
5 | coverage.xml
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 HyungJu Sung
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | [](#contributors-)
4 |
5 | Generate readable random phrases for URLs
6 |
7 | 
8 | 
9 | 
10 | 
11 | 
12 | 
13 | 
14 | 
15 |
16 | -----
17 |
18 | ## How To Use
19 | This library is available on packagist.
20 | To install,
21 | ```shell script
22 | composer require hyungju/readable-url
23 | ```
24 |
25 | Then create ``ReadableURL`` Class
26 | ```php
27 | $readableURL = new HyungJu\ReadableURL();
28 | ```
29 |
30 | You can pass four parameters to the class.
31 | ```php
32 | use HyungJu\ReadableURL;
33 | // Takes 4 parameters.
34 | // 1. A boolean value - If true, returns string in CamelCase, else lowercase.
35 | // 2. An integer value - The number of words to be generated in the string. (Between 2 and 10).
36 | // 3. A string - The seperator between the words.
37 | // 4. Language Class - Currently Supported : HyungJu\Language\En, HyungJu\Language\Ko. pass language instance! the default is HyungJu\Language\En
38 | $readableURL = new ReadableURL();
39 | //$readableURL = new HyungJu\ReadableURL(false, 5, '-', new HyungJu\Language\Ko()); // Other options.
40 | ```
41 |
42 | To generate `ReadableURL`, call the `generate()` function.
43 | ```php
44 | use HyungJu\ReadableURL;
45 |
46 | ...
47 |
48 | $readableURL = new ReadableURL();
49 | $readableURL->generate();
50 | // > QuickScrawnyCamp
51 | ```
52 |
53 | In addition, the following are simple to:
54 | ```php
55 | use HyungJu\ReadableURL;
56 |
57 | ...
58 |
59 | $str = ReadableURL::gen();
60 | // > FierceSaltyComparison
61 | ```
62 |
63 | This can be used to add to the end of a URL.
64 |
65 | Example: `https://example.com/photos/ForgetfulHarshEgg`
66 |
67 | For best results, use an integer value of 3, 4, or 5.
68 |
69 | ## Test
70 | `composer test`
71 |
72 | ## Adding new language
73 | 1. Add wordsets to `src/words/[language code]`.
74 | adjectives.txt and nouns.txt are needed.
75 |
76 | 2. Create your language class `src/Language/[language code].php`. the class name must be started with Uppercase.
77 |
78 | 3. Implement the class based on other languages already implemented (korean and english)
79 |
80 | 4. Register your language in `src/Language/LanguageHelper.php`.
81 |
82 | 5. (optional) Add test for your language.
83 |
84 | ## Versioning
85 | We use [SemVer](https://semver.org/) for versioning this project.
86 |
87 | ## License
88 | MIT License
89 |
90 | * This library is a PHP port of [readable-url](https://www.npmjs.com/package/readable-url)
91 |
92 | ## Contributors ✨
93 |
94 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
95 |
96 |
97 |
98 |
99 |
105 |
106 |
107 |
108 |
109 |
110 |
111 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "hyungju/readable-url",
3 | "description": "Generate readable random phrases for URLs",
4 | "keywords": ["php"],
5 | "license": "MIT",
6 | "authors": [
7 | {
8 | "name": "HyungJu Sung",
9 | "email": "sungkisa@naver.com"
10 | }
11 | ],
12 | "type": "library",
13 | "require": {
14 | "php": ">=7.3"
15 | },
16 | "require-dev": {
17 | "phpunit/phpunit": "9.*"
18 | },
19 | "autoload": {
20 | "psr-4": {
21 | "HyungJu\\": "src/"
22 | }
23 | },
24 | "autoload-dev": {
25 | "psr-4": {
26 | "HyungJu\\Tests\\": "test"
27 | }
28 | },
29 | "scripts": {
30 | "test": "./vendor/bin/phpunit --colors=always --configuration phpunit.xml.dist --coverage-clover coverage.xml"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/phpunit.xml.dist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | ./src
6 |
7 |
8 |
9 |
10 | ./tests/
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/readable.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HyungJu/readable-url/98eaf86396ecabbbea6775a59d86565d0df6b201/readable.png
--------------------------------------------------------------------------------
/src/ReadableURL.php:
--------------------------------------------------------------------------------
1 | 10) {
34 | throw new \UnexpectedValueException('Maximum value expected: 10');
35 | }
36 |
37 | $this->capitalize = $capitalize;
38 | $this->wordCount = $wordCount;
39 | $this->separator = $separator;
40 |
41 | $this->language = LanguageHelper::getLanguage($language);
42 | }
43 |
44 | /**
45 | * Convert words to be capitalized.
46 | *
47 | * @param $wordsList
48 | *
49 | * @return mixed
50 | */
51 | private static function convertToTitleCase(array $wordsList)
52 | {
53 | for ($i = 0; $i < count($wordsList); $i++) {
54 | $wordsList[$i] = strtoupper($wordsList[$i][0]).strtolower(substr($wordsList[$i], 1));
55 | }
56 |
57 | return $wordsList;
58 | }
59 |
60 | /**
61 | * Generate readable-url.
62 | *
63 | * @return string
64 | */
65 | public function generate()
66 | {
67 | $wordList = [];
68 |
69 | array_push($wordList, $this->language->pickOneAdjective());
70 | array_push($wordList, $this->language->pickOneNoun());
71 |
72 | if ($this->wordCount > 5) {
73 | array_map(function ($e) {
74 | array_unshift($wordList, $e);
75 | }, $this->language->pickMultipleAdjectives($this->wordCount - 1));
76 | } else {
77 | if ($this->wordCount > 2) {
78 | array_unshift($wordList, $this->language->pickOneAdjective());
79 | }
80 | if ($this->wordCount > 3) {
81 | array_unshift($wordList, $this->language->pickOneGlueFor($wordList[0]));
82 | }
83 | }
84 |
85 | if ($this->capitalize) {
86 | $wordList = $this->convertToTitleCase($wordList);
87 | }
88 |
89 | return implode($this->separator, $wordList);
90 | }
91 |
92 | /**
93 | * Generate readable-url (shortcut).
94 | *
95 | * @param bool $capitalize If true, returns string in CamelCase, else lowercase. (default: true)
96 | * @param int $wordCount The number of words to be generated in the string. (Between 2 and 10). (default: 3)
97 | * @param string $separator The separator between the words. (default: '')
98 | * @param string $language Language Setting (default: 'en')
99 | *
100 | * @throws \Exception
101 | *
102 | * @return string
103 | */
104 | public static function gen(bool $capitalize = true, int $wordCount = 3, string $separator = '', string $language = 'en'): string
105 | {
106 | $class = new ReadableURL($capitalize, $wordCount, $separator, $language);
107 |
108 | return $class->generate();
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/lang/Language.php:
--------------------------------------------------------------------------------
1 | getLangCode().'/words/adjectives.txt'));
20 |
21 | return $adjectives[rand(0, count($adjectives) - 1)];
22 | }
23 |
24 | public function pickOneNoun(): string
25 | {
26 | $nouns = explode(' ', file_get_contents(__DIR__.'/'.$this->getLangCode().'/words/nouns.txt'));
27 |
28 | return $nouns[rand(0, count($nouns) - 1)];
29 | }
30 |
31 | public function pickOneGlueForVowel(): string
32 | {
33 | $gluesForVowel = $this->getGluesForVowel();
34 |
35 | return $gluesForVowel[rand(0, count($gluesForVowel) - 1)];
36 | }
37 |
38 | public function pickOneGlueForNonVowel(): string
39 | {
40 | $gluesForNonVowel = $this->getGluesForNonVowel();
41 |
42 | return $gluesForNonVowel[rand(0, count($gluesForNonVowel) - 1)];
43 | }
44 |
45 | public function pickOneGlueFor(string $word): string
46 | {
47 | if ($this->isVowel($word)) {
48 | return $this->pickOneGlueForVowel();
49 | } else {
50 | return $this->pickOneGlueForNonVowel();
51 | }
52 | }
53 |
54 | public function pickMultipleAdjectives(int $numbers): array
55 | {
56 | $res = [];
57 | for ($i = 0; $i < $numbers; $i++) {
58 | $res[] = $this->pickOneAdjective();
59 | }
60 |
61 | return $res;
62 | }
63 |
64 | public function pickMultipleNouns(int $numbers): array
65 | {
66 | $res = [];
67 | for ($i = 0; $i < $numbers; $i++) {
68 | $res[] = $this->pickOneAdjective();
69 | }
70 |
71 | return $res;
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/lang/LanguageHelper.php:
--------------------------------------------------------------------------------
1 | En::class,
12 | 'ko' => Ko::class,
13 | ];
14 |
15 | private static $defaultLang = 'en';
16 |
17 | public static function getLanguage($code)
18 | {
19 | if (!array_key_exists($code, self::$lang)) {
20 | $code = self::$defaultLang;
21 | }
22 |
23 | $ref = new \ReflectionClass(self::$lang[$code]);
24 |
25 | return $ref->newInstance();
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/lang/en/En.php:
--------------------------------------------------------------------------------
1 | getVowels()[$i] === $word[0]) {
35 | $isVowel = true;
36 | break;
37 | }
38 | }
39 |
40 | return $isVowel;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/lang/en/words/adjectives.txt:
--------------------------------------------------------------------------------
1 | aback abaft abandoned abashed aberrant abhorrent abiding abject ablaze able abnormal aboard aboriginal abortive abounding abrasive abrupt absent absorbed absorbing abstracted absurd abundant abusive acceptable accessible accidental accurate acid acidic acoustic acrid actually ad ad hoc adamant adaptable addicted adhesive adjoining adorable adventurous afraid aggressive agonizing agreeable ahead ajar alcoholic alert alike alive alleged alluring aloof amazing ambiguous ambitious amuck amused amusing ancient angry animated annoyed annoying anxious apathetic aquatic aromatic arrogant ashamed aspiring assorted astonishing attractive auspicious automatic available average awake aware awesome awful axiomatic bad barbarous bashful bawdy beautiful belligerent erserk better bewildered big billowy bitter bizarre black bloody blue blushing boiling boorish bored boring boundless brainy brash brave brawny breakable breeze breezy brief bright broad broken bumpy burly busy cagey callous calm capable capricious careful cautious ceaseless changeable charming cheerful childlike chilly chivalrous chubby chunky clammy classy clean clear clever cloistered cloudy clumsy coherent cold colorful colossal combative comfortable concerned condemned confused cooing cool cooperative courageous cowardly crabby craven crazy credible creepy crooked crowded cruel cuddly cultured curious curly curved cute cynical daffy daily damaged damaging damp dangerous dapper dark dashing dazzling dead deadpan deafening debonair decisive decorous deep deeply defeated defective defiant delicious delightful demonic depressed deranged deserted detailed determined devilish didactic different difficult diligent direful dirty disagreeable discreet disgusted disillusioned dispensable distinct disturbed divergent dizzy domineering doubtful drab draconian dramatic drunk dry dull dusty dynamic dysfunctional eager early earsplitting earthy easy eatable economic educated efficacious efficient elated elderly elegant elfin elite embarrassed eminent empty enchanting encouraging endurable energetic entertaining enthusiastic envious equable erect erratic ethereal evanescent evasive evil excellent excited exclusive exotic expensive exuberant exultant fabulous faded faint fair faithful fallacious famous fanatical fancy fantastic fascinated fast fat faulty fearless feigned fertile festive few fierce filthy fine finicky flagrant flaky flashy flat flawless flippant flowery fluffy fluttering foamy foolish foregoing forgetful fortunate fragile frail frantic freezing fresh fretful friendly frightened full functional funny furtive futuristic fuzzy gabby gainful gamy gaping garrulous gaudy gentle giant giddy gifted gigantic glamorous gleaming glib glorious glossy godly good goofy gorgeous graceful grandiose gray greasy great greedy green grieving groovy grotesque grouchy grubby gruesome grumpy guarded guiltless gullible gusty guttural habitual half hallowed halting handsome handsomely hapless happy hard harmonious harsh heady healthy heartbreaking heavenly heavy hellish helpful helpless hesitant high highfalutin hilarious hissing historical hoc holistic hollow homeless homely honorable horrible hospitable hot huge hulking humdrum humorous hungry hurried hurt hushed husky hypnotic hysterical icky icy idiotic ignorant ill illegal illustrious imaginary immense imminent impartial imperfect important imported impossible incandescent incompetent inconclusive industrious inexpensive innate innocent inquisitive instinctive internal invincible irate itchy jaded jagged jazzy jealous jittery jobless jolly joyous judicious juicy jumbled jumpy juvenile kaput kind kindhearted knotty knowing knowledgeable known labored lackadaisical lacking lamentable languid large late laughable lavish lazy lean learned legal lethal level lewd light likeable literate little lively lonely long longing loose lopsided loud loutish lovely loving low lowly lucky ludicrous lush luxuriant lying lyrical macabre macho maddening madly magenta magical magnificent majestic makeshift malicious mammoth maniacal many marked massive materialistic mature measly meek melodic melted merciful mere mighty mindless miniature minor miscreant misty moaning modern moldy momentous motionless muddled muddy mundane murky mushy mute mysterious naive nappy narrow nasty naughty nauseating nebulous needless needy neighborly nervous new nice nifty noiseless noisy nonchalant nondescript nonstop nostalgic nosy noxious null numberless numerous nutritious nutty oafish obedient obeisant obnoxious obscene obsequious observant obsolete obtainable oceanic odd offbeat old omniscient onerous open optimal orange ordinary organic ossified outrageous outstanding oval overconfident overjoyed overrated overt overwrought painful painstaking panicky panoramic parched parsimonious pastoral pathetic peaceful penitent perfect periodic permissible perpetual petite phobic picayune piquant placid plain plastic plausible pleasant plucky pointless poised political poor possessive powerful precious premium pretty prickly productive profuse protective proud psychedelic psychotic puffy pumped puny purple purring puzzled quack quaint quarrelsome questionable quick quickest quiet quixotic quizzical rabid racial ragged rainy rambunctious rampant rapid rare raspy ratty real rebellious receptive recondite red redundant reflective relieved reminiscent repulsive resolute resonant rhetorical rich righteous rightful ripe ritzy roasted robust romantic roomy rotten rough round royal ruddy rural rustic ruthless sable sad salty sassy satisfying scandalous scarce scary scattered scientific scintillating scrawny screeching secretive sedate seemly selective selfish shaggy shaky shallow sharp shiny shivering shocking short shrill shy silent silky silly sincere skillful skinny sleepy slimy slippery sloppy slow small smelly smiling smoggy smooth sneaky snobbish snotty soft soggy solid somber sordid sore sour sparkling sparse spectacular spicy spiffy spiritual splendid spooky spotless spurious squalid square squealing squeamish staking stale standing statuesque steadfast steady steep stereotyped sticky stimulating stingy stormy straight strange strong stupid subdued subsequent substantial successful succinct sulky super supreme swanky sweet sweltering swift symptomatic synonymous taboo tacit tacky talented tall tame tan tangible tangy tart tasteful tasteless tasty tawdry tearful teeny telling temporary tender tense tenuous terrible tested testy thankful therapeutic thinkable thirsty thoughtful thoughtless threatening thundering tight tightfisted tiny tired tiresome toothsome torpid tough towering tranquil trashy tricky trite troubled truculent typical ubiquitous ugliest ugly ultra unable unaccountable unadvised unarmed unbecoming unbiased uncovered understood undesirable unequaled uneven uninterested unsightly unsuitable unusual upbeat uppity upset uptight used utopian utter uttermost vacuous vague various vast vengeful venomous verdant versed victorious vigorous vivacious voiceless volatile voracious vulgar wacky waggish wakeful wandering wanting warlike warm wary wasteful watchful watery weak wealthy weary wee wet whimsical whispering white wholesale wicked wide wild willing wiry wise wistful witty woebegone womanly wonderful wooden woozy workable worried worthless wrathful wretched wrong wry yellow yielding young youthful yummy zany zealous zippy
2 |
--------------------------------------------------------------------------------
/src/lang/en/words/nouns.txt:
--------------------------------------------------------------------------------
1 | able account achieve achiever acoustics act action activity actor addition adjustment advertisement advice aftermath afternoon afterthought agreement air airplane airport alarm alley amount amusement anger angle animal answer ant ants apparatus apparel apple apples appliance approval arch argument arithmetic arm army art attack attempt attention attraction aunt authority babies baby back badge bag bait balance ball balloon balls banana band base baseball basin basket basketball bat bath battle bead beam bean bear bears beast bed bedroom beds bee beef beetle beggar beginner behavior belief believe bell bells berry bike bikes bird birds birth birthday bit bite blade blood blow board boat boats body bomb bone book books boot border bottle boundary box bo boys brain brake branch brass bread breakfast breath brick bridge brother brothers brush bubble bucket building bulb bun burn burst bushes business butter button cabbage cable cactus cake cakes calculator calendar camera camp can cannon canvas cap caption car card care carpenter carriage cars cart cast cat cats cattle cause cave celery cellar cemetery cent chain chair chairs chalk chance change channel cheese cherries cherry chess chicken chickens children chin church circle clam class clock clocks cloth cloud clouds clover club coach coal coast coat cobweb coil collar color comb comfort committee company comparison competition condition connection control cook copper copy cord cork corn cough country cover cow cows crack cracker crate crayon cream creator creature credit crib crime crook crow crowd crown crush cry cub cup current curtain curve cushion dad daughter day death debt decision deer degree design desire desk destruction detail development digestion dime dinner dinosaurs direction dirt discovery discussion disease disgust distance distribution division dock doctor dog dogs doll dolls donkey door downtown drain drawer dress drink driving drop drug drum duck ducks dust ear earth earthquake edge education effect egg eggnog eggs elbow end engine error event example exchange existence expansion experience expert eye eyes face fact fairies fall family fan fang farm farmer father faucet fear feast feather feeling feet fiction field fifth fight finger fire fireman fish flag flame flavor flesh flight flock floor flower flowers fly fog fold food foot force fork form fowl frame friction friend friends frog frogs front fruit fuel furniture galley game garden gate geese ghost giants giraffe girl girls glass glove glue goat gold goldfish goodbye goose government governor grade grain grandfather grandmother grape grass grip ground group growth guide guitar gun hair haircut hall hammer hand hands harbor harmony hat hate head health hearing heart heat help hen hill history hobbies hole holiday home honey hook hope horn horse horses hose hospital hot hour house houses humor hydrant ice icicle idea impulse income increase industry ink insect instrument insurance interest invention iron island jail jam jar jeans jelly jellyfish jewel join joke journey judge juice jump kettle key kick kiss kite kitten kittens kitty knee knife knot knowledge laborer lace ladybug lake lamp land language laugh lawyer lead leaf learning leather leg legs letter letters lettuce level library lift light limit line linen lip liquid list lizards loaf lock locket look loss love low lumber lunch lunchroom machine magic maid mailbox man manager map marble mark market mask mass match meal measure meat meeting memory men metal mice middle milk mind mine minister mint minute mist mitten mom money monkey month moon morning mother motion mountain mouth move muscle music nail name nation neck need needle nerve nest net news night noise north nose note notebook number nut oatmeal observation ocean offer office oil operation opinion orange oranges order organization ornament oven owl owner page pail pain paint pan pancake paper parcel parent park part partner party passenger paste patch payment peace pear pen pencil person pest pet pets pickle picture pie pies pig pigs pin pipe pizzas place plane planes plant plantation plants plastic plate play playground pleasure plot plough pocket point poison police polish pollution popcorn porter position pot potato powder power price print prison process produce profit property prose protest pull pump punishment purpose push quarter quartz queen question quicksand quiet quill quilt quince quiver rabbit rabbits rail railway rain rainstorm rake range rat rate ray reaction reading reason receipt recess record regret relation religion representative request respect rest reward rhythm rice riddle rifle ring rings river road robin rock rod roll roof room root rose route rub rule run sack sail salt sand scale scarecrow scarf scene scent school science scissors screw sea seashore seat secretary seed selection self sense servant shade shake shame shape sheep sheet shelf ship shirt shock shoe shoes shop show side sidewalk sign silk silver sink sister sisters size skate skin skirt sky slave sleep sleet slip slope smash smell smile smoke snail snails snake snakes sneeze snow soap society sock soda sofa son song songs sort sound soup space spade spark spiders sponge spoon spot spring spy square squirrel stage stamp star start statement station steam steel stem step stew stick sticks stitch stocking stomach stone stop store story stove stranger straw stream street stretch string structure substance sugar suggestion suit summer sun support surprise sweater swim swing system table tail talk tank taste tax teaching team teeth temper tendency tent territory test texture theory thing things thought thread thrill throat throne thumb thunder ticket tiger time tin title toad toe toes tomatoes tongue tooth toothbrush toothpaste top touch town toy toys trade trail train trains tramp transport tray treatment tree trees trick trip trouble trousers truck trucks tub turkey turn twig twist umbrella uncle underwear unit use vacation value van vase vegetable veil vein verse vessel vest view visitor voice volcano volleyball voyage walk wall war wash waste watch water wave waves wax way wealth weather week weight wheel whip whistle wilderness wind window wine wing winter wire wish woman women wood wool word work worm wound wren wrench wrist writer writing yak yam yard yarn year yoke zebra zephyr zinc zippery
2 |
--------------------------------------------------------------------------------
/src/lang/ko/Ko.php:
--------------------------------------------------------------------------------
1 | readableUrl = new ReadableURL();
17 | }
18 |
19 | public function testConvertToTitleCase()
20 | {
21 | $class = new ReflectionClass('HyungJu\ReadableURL');
22 | $method = $class->getMethod('convertToTitleCase');
23 | $method->setAccessible(true);
24 |
25 | $converted = $method->invoke(null, ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'a', 'lazy', 'dog']);
26 | $this->assertSame(['The', 'Quick', 'Brown', 'Fox', 'Jumps', 'Over', 'A', 'Lazy', 'Dog'], $converted);
27 | }
28 |
29 | public function testWordCountMinLimit()
30 | {
31 | try {
32 | new ReadableURL(true, 1, '');
33 | } catch (\UnexpectedValueException $exception) {
34 | assertEquals(0, $exception->getCode());
35 | assertEquals('Minimum value expected: 2', $exception->getMessage());
36 | }
37 | }
38 |
39 | public function testWordCountMaxLimit()
40 | {
41 | try {
42 | new ReadableURL(true, 11, '');
43 | } catch (\UnexpectedValueException $exception) {
44 | assertEquals(0, $exception->getCode());
45 | assertEquals('Maximum value expected: 10', $exception->getMessage());
46 | }
47 | }
48 |
49 | public function testGenerate()
50 | {
51 | $generated = $this->readableUrl->generate(); // Capitalize, 3Words, No Separator
52 |
53 | $capitalWordsCount = 0;
54 | for ($i = 0; $i < strlen($generated); $i++) {
55 | if (ctype_upper($generated[$i])) {
56 | $capitalWordsCount++;
57 | }
58 | }
59 |
60 | $this->assertSame(3, $capitalWordsCount);
61 | }
62 |
63 | public function testGenerateKorean()
64 | {
65 | $readableUrl = new ReadableURL(false, 3, '', 'ko');
66 | $generated = $readableUrl->generate(); // Capitalize, 3Words, No Separator
67 |
68 | $this->assertNotNull($generated);
69 | }
70 |
71 | public function testGenerateStatic()
72 | {
73 | $generated = ReadableURL::gen(); // Capitalize, 3Words, No Separator
74 |
75 | $capitalWordsCount = 0;
76 | for ($i = 0; $i < strlen($generated); $i++) {
77 | if (ctype_upper($generated[$i])) {
78 | $capitalWordsCount++;
79 | }
80 | }
81 |
82 | $this->assertSame(3, $capitalWordsCount);
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/tests/lang/EnTest.php:
--------------------------------------------------------------------------------
1 | assertTrue($en->isVowel('apple'));
12 | $this->assertTrue($en->isVowel('elephant'));
13 | $this->assertTrue($en->isVowel('internet'));
14 | $this->assertTrue($en->isVowel('orange'));
15 | $this->assertTrue($en->isVowel('unittest'));
16 | $this->assertFalse($en->isVowel('php'));
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/tests/lang/KoTest.php:
--------------------------------------------------------------------------------
1 | assertTrue($ko->isVowel('안녕하세요'));
12 | }
13 | }
14 |
--------------------------------------------------------------------------------