This repository was archived by the owner on Oct 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathrandomNameGenerator.php
More file actions
63 lines (45 loc) · 1.46 KB
/
randomNameGenerator.php
File metadata and controls
63 lines (45 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
class randomNameGenerator {
private $version;
public $allowedFormats;
public $inputFormat;
public function __construct( $output = 'array' ) {
$this->version = '1.0.0';
$this->allowedFormats = array('array', 'json', 'associative_array');
$this->inputFormat = 'json';
if ( !in_array( $output, $this->allowedFormats ) ) {
throw new Exception('Unrecognized format');
}
$this->output = $output;
}
private function getList( $type ) {
$json = file_get_contents($type . '.' . $this->inputFormat, FILE_USE_INCLUDE_PATH );
$data = json_decode( $json, true );
return $data;
}
public function generateNames( $num ) {
if ( !is_numeric( $num ) ) {
throw new Exception('Not a number');
}
$first_names = $this->getList('first-names');
$last_names = $this->getList('last-names');
$count = range(1, $num );
$name_r = array();
foreach( $count as $name ) {
$count++;
$random_fname_index = array_rand( $first_names );
$random_lname_index = array_rand( $last_names );
$first_name = $first_names[$random_fname_index];
$last_name = $last_names[$random_lname_index];
if( $this->output == 'array' ) {
$name_arr[] = $first_name . ' ' . $last_name;
} elseif( $this->output == 'associative_array' || $this->output == 'json' ) {
$name_arr[] = array( 'first_name' => $first_name, 'last_name' => $last_name );
}
}
if( $this->output == 'json' ) {
$name_arr = json_encode( $name_arr );
}
return $name_arr;
}
}