sports_league-8.x-1.x-dev/modules/sl_default_content/src/SLDefaultContentGenerator.php
modules/sl_default_content/src/SLDefaultContentGenerator.php
<?php
namespace Drupal\sl_default_content;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
use Drupal\sl_base\SlBaseHelper;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\TermInterface;
/**
* Service to generate default content.
*/
class SLDefaultContentGenerator {
/**
* The final categories.
*
* @var array
*/
protected $finalCategories = [];
/**
* Categories.
*
* @var array[]
*/
protected $categories = [
'footbal' => [
'title' => 'Football',
'subcategories' => [
'england' => [
'title' => 'England',
'subcategories' => [
'england_league' => ['title' => 'England league'],
'england_cup' => ['title' => 'England Cup'],
],
],
'spain' => [
'title' => 'Spain',
'subcategories' => [
'spain_league' => ['title' => 'Spain league'],
'spain_cup' => ['title' => 'Spain cup'],
],
],
'italy' => [
'title' => 'Italy',
'subcategories' => [
'italy_league' => ['title' => 'Italy league'],
'italy_cup' => ['title' => 'Italy cup'],
],
],
'europe' => [
'title' => 'Europe',
'subcategories' => [
'european_league' => ['title' => 'European league'],
'south_cup' => ['title' => 'South cup'],
],
],
],
],
];
/**
* First names.
*
* @var string[]
*/
protected static $firstNames = [
'Christopher',
'Ryan',
'Ethan',
'John',
'Zoey',
'Sarah',
'Michelle',
'Samantha',
'Joao',
'Francesco',
'Juan',
'Aitor',
'Pedro',
'Jordi',
'Ruslan',
];
/**
* Surnames.
*
* @var string[]
*/
protected static $lastNames = [
'Walker',
'Thompson',
'Anderson',
'Johnson',
'Tremblay',
'Peltier',
'Cunningham',
'Simpson',
'Mercado',
'Sellers',
'Garcia',
'Navarro',
'Silva',
'Gomez',
];
/**
* Teams.
*
* @var array[]
*/
protected $teams = [
'madrid' => ['title' => 'Madrid', 'category' => 'spain'],
'barcelona' => ['title' => 'Barcelona', 'category' => 'spain'],
'manchester' => ['title' => 'Manchester', 'category' => 'england'],
'london' => ['title' => 'London', 'category' => 'england'],
'munich' => ['title' => 'Oxford', 'category' => 'england'],
'milano' => ['title' => 'Milano', 'category' => 'italy'],
'torino' => ['title' => 'Torino', 'category' => 'italy'],
'roma' => ['title' => 'Roma', 'category' => 'italy'],
];
/**
* Competitions.
*
* @var array[]
*/
protected $competitions = [
'england_league' => ['title' => 'England league', 'category' => 'england'],
'super_league' => ['title' => 'Super league', 'category' => 'spain'],
'european_league' => ['title' => 'European league', 'category' => 'europe'],
'south_cup' => ['title' => 'South Cup', 'category' => 'south_cup'],
];
/**
* Competition instances.
*
* @var array
*/
protected $competitionsInstances = [];
/**
* Countries.
*
* @var array[]
*/
protected $stadiums = [
'wood_venue' => ['title' => 'Wood Venue'],
'metal_stadium' => ['title' => 'Metal stadium'],
'hall_city' => ['title' => 'Hall city'],
'woodstock_stadium' => ['title' => 'Woodstock stadium'],
'la_palmera_stadium' => ['title' => 'La Palmera stadium'],
];
/***
* Referees.
*
* @var array
*/
protected $referees = [];
/**
* Positions.
*
* @var array[]
*/
protected $positions = [
'keeper' => ['title' => 'Keeper'],
'defense' => ['title' => 'Defense'],
'midfield' => ['title' => 'Midfield'],
'forward' => ['title' => 'Forward'],
'coach' => ['title' => 'Coach'],
];
/**
* Seasons.
*
* @var string[]
*/
protected $seasons = [
'2016/2017',
'2017/2018',
];
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The base helper.
*
* @var \Drupal\sl_base\SlBaseHelper
*/
protected $slBaseHelper;
/**
* Constructs a SLDefaultContentGenerator service.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\sl_base\SlBaseHelper $sl_base_helper
* The base helper.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, SlBaseHelper $sl_base_helper) {
$this->entityTypeManager = $entity_type_manager;
$this->slBaseHelper = $sl_base_helper;
}
/**
* Used to generate names for athletes, coaches, referees.
*
* @return string
* The full name.
*/
public static function generateRandomName(): string {
$random_first = rand(0, count(self::$firstNames) - 1);
$random_last = rand(0, count(self::$lastNames) - 1);
return self::$firstNames[$random_first] . ' ' . self::$lastNames[$random_last];
}
/**
* Used to generate names for athletes, coaches, referees.
*
* @return string
* The full name.
*/
public static function generateName(int $i): string {
$random_first = $i % count(self::$firstNames);
$random_last = $i % count(self::$lastNames);
return self::$firstNames[$random_first] . ' ' . self::$lastNames[$random_last];
}
/**
* Private function to generate taxonomy term.
*
* @param string $title
* The title.
* @param string $type
* The type.
* @param array $params
* The params.
*
* @return \Drupal\taxonomy\TermInterface
* The created term.
*/
private function createTerm(string $title, string $type, array $params): TermInterface {
$term = Term::create(['vid' => $type]);
$term->set('name', $title);
foreach ($params as $key => $value) {
$term->set($key, $value);
}
$term->enforceIsNew();
$term->save();
return $term;
}
/**
* Private auxiliary function to generate nodes.
*
* @param string $title
* The title.
* @param string $type
* The type.
* @param array $params
* The params.
*
* @return \Drupal\node\NodeInterface
* The created node.
*/
private function createNode(string $title, string $type, array $params): NodeInterface {
$node = Node::create(['type' => $type]);
$node->set('title', $title);
foreach ($params as $key => $value) {
$node->set($key, $value);
}
$node->enforceIsNew();
$node->save();
return $node;
}
/**
* Generate statiums and referees.
*/
protected function generateOthers(): void {
$args = [];
foreach ($this->stadiums as $stadium_id => $stadium) {
$term = $this->createTerm($stadium['title'], 'sl_venues', $args);
$this->stadiums[$stadium_id]['id'] = $term->id();
}
for ($i = 0; $i < 10; $i++) {
$term_name = self::generateRandomName();
$term = $this->createTerm($term_name, 'sl_referees', $args);
$this->referees[$term->id()]['id'] = $term->id();
$this->referees[$term->id()]['name'] = $term->label();
}
}
/**
* Generate categories in an hierarchy.
*/
protected function generateCategories($categories = NULL, $parent_id = NULL): void {
if (!isset($categories)) {
$categories = $this->categories;
}
foreach ($categories as $cat_id => $category) {
$args['parent'] = $parent_id;
$term = $this->createTerm($category['title'], 'sl_categories', $args);
$this->finalCategories[$cat_id] = $term->id();
if (!empty($category['subcategories'])) {
$subcategories =& $category['subcategories'];
$this->generateCategories($subcategories, $term->id());
}
}
}
/**
* Find category id.
*
* @param string $category_id
* The category id.
*
* @return mixed
* The category.
*/
private function findCategory(string $category_id) {
return $this->finalCategories[$category_id];
}
/**
* Generate dates.
*
* @param int $year_start
* Start year.
* @param int $year_end
* End year.
*
* @return int
* The time.
*/
private function generateDate(int $year_start = 1982, int $year_end = 1998): int {
$year = rand($year_start, $year_end);
$month = rand(1, 12);
$day = rand(1, 28);
return mktime(0, 0, 0, $month, $day, $year);
}
/**
* Generate random number except the one already generated.
*
* @param int $min
* The minimum.
* @param int $max
* The maximum.
* @param array $except
* The exceptions.
*
* @return int
* The random number.
*/
private function generateRandomExcept(int $min, int $max, array $except = []) {
$number = rand($min, $max);
if (!in_array($number, $except)) {
return $number;
}
else {
return $this->generateRandomExcept($min, $max, $except);
}
}
/**
* Generate players.
*/
protected function generatePlayers(): void {
foreach ($this->teams as $team_id => $team) {
for ($i = 0; $i < 19; $i++) {
$name = self::generateRandomName();
$args['field_sl_teams'] = $team['id'];
$args['field_sl_person_number'] = $i + 1;
$rand_position = rand(0, count($this->positions) - 2);
$positions_values = array_keys($this->positions);
$rand_position = $positions_values[$rand_position];
// Last player is the coach.
if ($i == 18) {
$rand_position = 'coach';
unset($args['field_sl_person_number']);
}
$args['field_sl_person_position'] = $this->positions[$rand_position]['id'];
$args['field_sl_detailed_position'] = $this->positions[$rand_position]['title'];
$args['field_sl_person_date_of_birth'] = $this->generateDate(1982, 1988);
$args['field_sl_stats_disabled'] = FALSE;
$this->createNode($name, 'sl_person', $args);
}
}
}
/**
* Generate clubs.
*/
protected function generateClubs(): void {
$args = [];
foreach ($this->teams as $team_id => $team) {
$args['field_sl_archived'] = 0;
$node = $this->createNode($team['title'], 'sl_club', $args);
$this->teams[$team_id]['id'] = $node->id();
}
}
/**
* Generate positions.
*/
protected function generatePositions(): void {
foreach ($this->positions as $position_id => $position) {
$args = [];
if ($position_id == 'coach') {
$args['field_sl_is_coach_position'] = 1;
}
$term = $this->createTerm($position['title'], 'sl_person_positions', $args);
$this->positions[$position_id]['id'] = $term->id();
}
}
/**
* Generate teams.
*/
protected function generateTeams(): void {
foreach ($this->teams as $team_id => $team) {
$args = [];
$args['field_sl_categories'] = $this->findCategory($team['category']);
// Generate stats only for two teams.
if (in_array($team_id, ['barcelona', 'roma'])) {
$args['field_sl_stats_type'] = 'sl_stats_player';
}
$node = $this->createNode($team['title'], 'sl_team', $args);
$this->teams[$team_id]['id'] = $node->id();
}
}
/**
* Generate competitions.
*/
protected function generateCompetitions(): void {
$args = [];
foreach ($this->competitions as $competition_id => $competition) {
$args['field_sl_categories'] = $this->findCategory($competition['category']);
$node = $this->createNode($competition['title'], 'sl_competition', $args);
$this->competitions[$competition_id]['id'] = $node->id();
}
}
/**
* Generate competition instances.
*/
protected function generateCompetitionsInstances(): void {
$args = [];
foreach ($this->seasons as $season) {
foreach ($this->competitions as $competition_id => $competition) {
$args['field_sl_archived'] = FALSE;
$args['field_sl_categories'] = $this->findCategory($competition['category']);
$args['field_sl_competition'] = $competition['id'];
$title = $competition['title'] . ' ' . $season;
$node = $this->createNode($title, 'sl_competition_edition', $args);
$this->competitionsInstances[$competition_id]['id'] = $node->id();
$this->competitionsInstances[$competition_id]['category'] = $competition['category'];
}
}
}
/**
* Generate matches.
*/
protected function generateMatches(): void {
$matches = [
[0, 1, 2, 0],
[2, 3, 3, 2],
[4, 1, 2, 3],
[5, 2, 1, 1],
[2, 6, 0, 0],
[7, 1, 5, 0],
[3, 2, 2, 4],
[1, 6, 3, 4],
[1, 0, 0, 3],
[4, 3, 2, 4],
[1, 3, 3, 4],
[7, 6, 4, 3],
[3, 4, 2, 4],
[1, 4, 3, 4],
[1, 5, 0, 3],
];
$i = 0;
foreach ($matches as $match) {
// We need to seelect a random team.
$team_1_id = $match[0];
$team_2_id = $match[1];
$teams_ids = array_keys($this->teams);
$team_1 = $this->teams[$teams_ids[$team_1_id]];
$team_2 = $this->teams[$teams_ids[$team_2_id]];
// How many matches we have with more than 5 goals.
$goals_1 = $match[2];
$goals_2 = $match[3];
$args = [];
// Every matches, create a friendly.
if (($i % 4) === 0) {
$args['field_sl_stats_disabled'] = 1;
}
$args['field_sl_match_team_home'] = $team_1['id'];
$args['field_sl_match_team_away'] = $team_2['id'];
$args['field_sl_match_score_home'] = $goals_1;
$args['field_sl_match_score_away'] = $goals_2;
$args['field_sl_teams'] = [$team_1, $team_2];
$args['field_sl_match_status'] = 'played';
$referee_id = rand(0, count($this->referees) - 1);
$stadium_id = rand(0, count($this->stadiums) - 1);
$competition_id = $i % count($this->competitionsInstances);
$referees_keys = array_keys($this->referees);
$stadium_keys = array_keys($this->stadiums);
$competitions_instances_keys = array_keys($this->competitionsInstances);
// Random referee and stadium.
$args['field_sl_referee'] = $this->referees[$referees_keys[$referee_id]]['id'];
$args['field_sl_venue'] = $this->stadiums[$stadium_keys[$stadium_id]]['id'];
$args['field_sl_categories'] = $this->findCategory($this->competitionsInstances[$competitions_instances_keys[$competition_id]]['category']);
$args['field_sl_competition'] = $this->competitionsInstances[$competitions_instances_keys[$competition_id]]['id'];
$title = $team_1['title'] . ' ' . $goals_1 . ' x ' . $goals_2 . ' ' . $team_2['title'];
$args['field_sl_administrative_title'] = $title;
$args['field_sl_match_date'] = $this->generateDate(1982, 1988);
$node = $this->createNode($title, 'sl_match', $args);
// Time to generate rosters and substitutes.
$home_rosters = $this->generateRosters($team_1['id'], 11, 0, 90, $node->id());
$home_coach = $this->generateRosters($team_1['id'], 1, 0, 90, $node->id(), 18);
$away_rosters = $this->generateRosters($team_2['id'], 11, 0, 90, $node->id());
$away_coach = $this->generateRosters($team_2['id'], 1, 0, 90, $node->id(), 18);
$node->set('field_sl_match_home_inirosters', $home_rosters);
$node->set('field_sl_match_away_inirosters', $away_rosters);
$node->set('field_sl_match_home_coach', $home_coach);
$node->set('field_sl_match_away_coach', $away_coach);
$home_subs = $this->generateRosters($team_1['id'], 7, 0, 90, $node->id(), 11);
$away_subs = $this->generateRosters($team_2['id'], 7, 0, 90, $node->id(), 11);
$home_moments = $this->generateMoments($team_1['id'], $goals_1, 3, $node->id());
$away_moments = $this->generateMoments($team_2['id'], $goals_2, 3, $node->id());
$node->set('field_sl_match_home_inisubs', $home_subs);
$node->set('field_sl_match_away_inisubs', $away_subs);
// Time to generate moments.
$node->set('field_sl_match_home_moments', $home_moments);
$node->set('field_sl_match_away_moments', $away_moments);
$node->save();
$i++;
}
}
/**
* Auxiliary function to generate the rosters().
*
* @param int $team
* The team.
* @param int $number
* The number.
* @param int $in
* Enter time.
* @param int|null $out
* Exit time.
* @param int $match_id
* Match id.
* @param int $start
* The starting point.
*
* @return array
* The rosters ids.
*/
protected function generateRosters(int $team, int $number, int $in, ?int $out, int $match_id, int $start = 0): array {
$players = $this->slBaseHelper->findTeamPlayers($team);
if (empty($players)) {
return [];
}
$players_picked = $rosters_ids = [];
for ($i = 0; $i < $number; $i++) {
$players_id = $i + $start;
$players_entity_ids = array_keys($players);
$data = [
'type' => 'sl_rosters',
'field_sl_roster_in' => $in,
'field_sl_roster_out' => $out,
'field_sl_match' => $match_id,
'field_sl_roster_player' => $players_entity_ids[$players_id],
'field_sl_roster_num' => $players[$players_entity_ids[$players_id]]['number'],
'field_sl_count' => TRUE,
];
$entity = $this->entityTypeManager
->getStorage('sl_rosters')
->create($data);
$entity->save();
$rosters_ids[] = $entity->id();
}
return $rosters_ids;
}
/**
* Generate moments.
*
* @param int $team
* The team id.
* @param int $goals_num
* The number of goals.
* @param int $subs_num
* The number of substitutions.
* @param int $match_id
* The match id.
*
* @return array
* The ids of the moments.
*/
protected function generateMoments(int $team, int $goals_num, int $subs_num, int $match_id) {
$players = $this->slBaseHelper->findTeamPlayers($team);
if (empty($players)) {
return [];
}
$players_picked = $moments_ids = [];
for ($i = 0; $i < $goals_num; $i++) {
$players_id = 10 - $i;
$players_picked[] = $players_id;
$players_entity_ids = array_keys($players);
$data = [
'type' => 'sl_match_moments_goal',
'field_sl_match_moments_time' => rand(0, 90),
'field_sl_match' => $match_id,
'field_sl_match_moments_player' => $players_entity_ids[$players_id],
];
$entity = $this->entityTypeManager
->getStorage('sl_match_moments')
->create($data);
$entity->save();
$moments_ids[] = $entity->id();
}
for ($i = 0; $i < $subs_num; $i++) {
$players_id = $this->generateRandomExcept(0, count($players) - 1, $players_picked);
$players_picked[] = $players_id;
$players_entity_ids = array_keys($players);
$data = [
'type' => 'sl_match_moments_substitution',
'field_sl_match_moments_time' => rand(0, 90),
'field_sl_match' => $match_id,
'field_sl_match_moments_player' => $players_entity_ids[$players_id],
'field_sl_match_moments_player_in' => $players_entity_ids[$players_id],
];
$entity = $this->entityTypeManager
->getStorage('sl_match_moments')
->create($data);
$entity->save();
$moments_ids[] = $entity->id();
}
return $moments_ids;
}
/**
* Main generator function used to generate all the needed content.
*/
public function mainGenerator() {
$this->generateCategories();
$this->generateOthers();
$this->generateClubs();
$this->generateTeams();
$this->generateCompetitions();
$this->generateCompetitionsInstances();
$this->generatePositions();
$this->generatePlayers();
$this->generateMatches();
}
}
