Skip to content

Instantly share code, notes, and snippets.

@hersan
Created October 22, 2022 17:29
Show Gist options
  • Select an option

  • Save hersan/9ca43266f6854affeb05940f61c8617d to your computer and use it in GitHub Desktop.

Select an option

Save hersan/9ca43266f6854affeb05940f61c8617d to your computer and use it in GitHub Desktop.
<?php
class RandomUserRequest
{
private array $options = [];
public function __construct(array $options)
{
if (!empty($options)) {
foreach ($options as $key => $value) {
$this->options[$key] = $value;
}
}
}
public static function make(array $options = []): RandomUserRequest
{
return new static($options);
}
public function withResults(int $number): RandomUserRequest
{
$this->options['results'] = $number;
return $this;
}
public function withGender(string $gender): RandomUserRequest
{
if (!in_array($gender, ['female', 'male'])) {
throw new Exception("The {$gender} gender is not supported");
}
$this->options['gender'] = $gender;
return $this;
}
public function withNationality($nationality): RandomUserRequest
{
if (!is_array($nationality)) {
$nationality = \Illuminate\Support\Arr::wrap($nationality);
}
if (!$this->isValidNationality($nationality)) {
throw new Exception('Invalid nationality');
}
$this->options['nat'] = implode(',', $nationality);
return $this;
}
public function includeFields(array $fields): RandomUserRequest
{
if (!isset($this->options['exc'])) {
$this->options['inc'] = implode(',', $fields);
}
return $this;
}
public function excludeFields(array $fields): RandomUserRequest
{
if (isset($this->options['inc'])) {
$this->options['exc'] = implode(',', $fields);
}
return $this;
}
public function withPasswords(array $passwords): RandomUserRequest
{
$this->options['password'] = implode(',', $passwords);
return $this;
}
/**
* @return string[]
*/
private function nationalities(): array
{
return [
'AU',
'BR',
'CA',
'CH',
'DE',
'DK',
'ES',
'FI',
'FR',
'GB',
'IE',
'IN',
'IR',
'MX',
'NL',
'NO',
'NZ',
'RS',
'TR',
'UA',
'US',
];
}
/**
* @param $nationality
* @return bool|false
*/
private function isValidNationality($nationality): bool
{
foreach ($nationality as $item) {
if (!in_array(strtoupper($item), $this->nationalities())) {
return false;
}
}
return true;
}
public function get(): \Illuminate\Support\Collection
{
$this->options['noinfo'] = '';
$response = Http::get(
'https://randomuser.me/api/',
$this->options
)
->json() ?? [];
return collect($response['results'])
->mapInto(\Illuminate\Support\Fluent::class)
;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment