1<?php
2
3namespace Elgg\Database\Seeds;
4
5/**
6 * Seed users
7 *
8 * @internal
9 */
10class Users extends Seed {
11
12	/**
13	 * {@inheritdoc}
14	 */
15	public function seed() {
16
17		$count_users = function () {
18			return elgg_count_entities([
19				'types' => 'user',
20				'metadata_names' => '__faker',
21			]);
22		};
23
24		$count_friends = function ($user) {
25			return elgg_count_entities([
26				'types' => 'user',
27				'relationship' => 'friend',
28				'relationship_guid' => $user->guid,
29				'inverse_relationship' => false,
30				'metadata_names' => '__faker',
31			]);
32		};
33
34		$exclude = [];
35
36		$this->advance($count_users());
37
38		while ($count_users() < $this->limit) {
39			$user = $this->getRandomUser($exclude);
40			if (!$user) {
41				$user = $this->createUser([], [], [
42					'profile_fields' => (array) elgg_get_config('profile_fields'),
43				]);
44				if (!$user) {
45					continue;
46				}
47			}
48
49			$this->createIcon($user);
50
51			$exclude[] = $user->guid;
52
53			// Friend the user other members
54			// Create a friend access collection and add some random friends to it
55
56			if ($count_friends($user)) {
57				continue;
58			}
59
60			$collection_id = create_access_collection('Best Fake Friends Collection', $user->guid, 'friends_collection');
61			if ($collection_id > 0) {
62				$this->log("Created new friend collection for user {$user->getDisplayName()} [collection_id: {$collection_id}]");
63			}
64
65			$friends_limit = $this->faker()->numberBetween(5, 10);
66
67			$friends_exclude = [$user->guid];
68			while ($count_friends($user) < $friends_limit) {
69				$friend = $this->getRandomUser($friends_exclude);
70				if (!$friend) {
71					$this->createUser();
72					if (!$friend) {
73						continue;
74					}
75				}
76
77				$friends_exclude[] = $friend->guid;
78
79				if ($user->addFriend($friend->guid, true)) {
80					$this->log("User {$user->getDisplayName()} [guid: {$user->guid}] friended user {$friend->getDisplayName()} [guid: {$friend->guid}]");
81					if ($this->faker()->boolean() && $collection_id > 0) {
82						add_user_to_access_collection($friend->guid, $collection_id);
83					}
84				}
85			}
86
87			$this->advance();
88		}
89
90	}
91
92	/**
93	 * {@inheritdoc}
94	 */
95	public function unseed() {
96
97		$users = elgg_get_entities([
98			'types' => 'user',
99			'metadata_names' => '__faker',
100			'limit' => 0,
101			'batch' => true,
102		]);
103
104		/* @var $users \ElggBatch */
105
106		$users->setIncrementOffset(false);
107
108		foreach ($users as $user) {
109			if ($user->delete()) {
110				$this->log("Deleted user $user->guid");
111			} else {
112				$this->log("Failed to delete user $user->guid");
113			}
114
115			$this->advance();
116		}
117	}
118
119}
120