crm_core-8.x-3.x-dev/modules/crm_core_contact/tests/src/Traits/OrganizationCreationTrait.php
modules/crm_core_contact/tests/src/Traits/OrganizationCreationTrait.php
<?php namespace Drupal\Tests\crm_core_contact\Traits; use Drupal\crm_core_contact\Entity\Organization; use Drupal\user\Entity\User; /** * Provides methods to create organization based on default settings. * * This trait is meant to be used only by test classes. */ trait OrganizationCreationTrait { /** * Get a crm_core_organization from the database based on its name. * * @param string|\Drupal\Component\Render\MarkupInterface $name * An organization name, usually generated by $this->randomMachineName(). * @param bool $reset * (optional) Whether to reset the entity cache. * * @return \Drupal\crm_core_contact\OrganizationInterface * An organization entity matching $name. */ public function getOrganizationByName($name, $reset = FALSE) { if ($reset) { \Drupal::entityTypeManager()->getStorage('crm_core_organization')->resetCache(); } // Cast MarkupInterface objects to string. $name = (string) $name; $organizations = \Drupal::entityTypeManager() ->getStorage('crm_core_organization') ->loadByProperties(['name' => $name]); // Load the first organization returned from the database. $returned_organization = reset($organizations); return $returned_organization; } /** * Creates a crm_core_organization based on default settings. * * @param array $values * (optional) An associative array of values for the organization, as used * in creation of entity. Override the defaults by specifying the key and * valuein the array. * * For example: * * @code * $this->drupalCreateOrganization([ * 'name' => t('Glass Co.'), * 'type' => 'company', * ]); * @endcode * The following defaults are provided: * - title: Random string. * - type: 'company'. * - uid: The currently logged in user, or anonymous. * * @return \Drupal\crm_core_contact\OrganizationInterface * The created organization entity. */ protected function createOrganization(array $values = []) { // Populate defaults array. $values += [ 'name' => $this->randomMachineName(8), 'type' => 'company', ]; if (!array_key_exists('uid', $values)) { $user = User::load(\Drupal::currentUser()->id()); if ($user) { $values['uid'] = $user->id(); } elseif (method_exists($this, 'setUpCurrentUser')) { /** @var \Drupal\user\UserInterface $user */ $user = $this->setUpCurrentUser(); $values['uid'] = $user->id(); } else { $values['uid'] = 0; } } $organization = Organization::create($values); $organization->save(); return $organization; } }