/** * @param array $fields * Additional data for user account. * * @throws \Exception * * @return \stdClass */ public function createTestUser(array $fields = []) { $random = $this->getRandom(); $username = $random->name(8); $user = ['name' => $username, 'pass' => $random->name(16), 'mail' => "{$username}@example.com", 'roles' => [DRUPAL_AUTHENTICATED_RID => 'authenticated user']]; $user = (object) $user; if (!empty($fields)) { $entity = new EntityDrupalWrapper('user'); $required = $entity->getRequiredFields(); // Fill fields. Field can be found by name or label. foreach ($fields as $field_name => $value) { $field_info = $entity->getFieldInfo($field_name); if (!empty($field_info)) { $field_name = $field_info['field_name']; } $user->{$field_name} = $value; // Remove field from $required if it was there and filled. unset($required[$field_name]); } // Throw an exception when one of required fields was not filled. if (!empty($required)) { throw new \Exception(sprintf('The following fields "%s" are required and has not filled.', implode('", "', $required))); } } if (isset($user->name)) { $existing_user = user_load_by_name($user->name); if (!empty($existing_user)) { user_delete($existing_user->uid); } } // $this->user always exist but when no user created it has "false" as a value. // Variable stored to another because RawDrupalContext::userCreate() will modify // it and this will affect for future actions. if (!empty($this->user)) { $tmp = $this->user; } $this->userCreate($user); if (isset($tmp)) { $this->user = $tmp; } return $user; }
/** * Use the current user data for filling fields. * * @example * Then I fill "First name" with value of field "First name" of current user * And fill "field_last_name[und][0]" with value of field "field_user_last_name" of current user * * @param string $field * The name of field to fill in. HTML Label, name or ID can be user as selector. * @param string $user_field * The name of field from which the data will taken. Drupal label or machine name can be used as selector. * * @throws \InvalidArgumentException * @throws \UnexpectedValueException * @throws \Exception * @throws NoSuchElement * When field cannot be found. * * @Then /^(?:I )fill "([^"]*)" with value of field "([^"]*)" of current user$/ */ public function fillInWithValueOfFieldOfCurrentUser($field, $user_field) { if (!empty($this->user) && !$this->user->uid) { throw new \Exception('Anonymous user have no fields'); } $entity = new EntityDrupalWrapper('user'); $wrapper = $entity->wrapper($this->user->uid); $user_field = $entity->getFieldNameByLocator($user_field); if (empty($wrapper->{$user_field})) { throw new \InvalidArgumentException(sprintf('User entity has no "%s" field.', $user_field)); } $value = $wrapper->{$user_field}->value(); if (empty($value)) { throw new \UnexpectedValueException('The value of "%s" field is empty.', $user_field); } $this->fillField($field, $value); }