crm_core-8.x-3.x-dev/modules/crm_core_contact/tests/src/Traits/IndividualCreationTrait.php
modules/crm_core_contact/tests/src/Traits/IndividualCreationTrait.php
<?php
namespace Drupal\Tests\crm_core_contact\Traits;
use Drupal\crm_core_contact\Entity\Individual;
use Drupal\user\Entity\User;
/**
* Provides methods to create node based on default settings.
*
* This trait is meant to be used only by test classes.
*/
trait IndividualCreationTrait {
/**
* Get a node from the database based on its label.
*
* @param string|\Drupal\Component\Render\MarkupInterface $label
* An individual label, usually generated by $this->randomMachineName().
* @param bool $reset
* (optional) Whether to reset the entity cache.
*
* @return \Drupal\crm_core_contact\IndividualInterface
* A node entity matching $label.
*/
public function getIndividualByLabel($label, $reset = FALSE) {
if ($reset) {
\Drupal::entityTypeManager()->getStorage('crm_core_individual')->resetCache();
}
// Cast MarkupInterface objects to string.
$label = (string) $label;
$individuals = \Drupal::entityTypeManager()
->getStorage('crm_core_individual')
->loadByProperties(['label' => $label]);
// Load the first individual returned from the database.
$returned_individual = reset($individuals);
return $returned_individual;
}
/**
* Creates an individual based on default settings.
*
* @param array $values
* (optional) An associative array of values for the individual, as used in
* creation of entity. Override the defaults by specifying the key and value
* in the array, for example:
*
* @code
* $this->drupalCreateIndividual([
* 'label' => t('Hello, world!'),
* 'type' => 'person',
* ]);
* @endcode
* The following defaults are provided:
* - body: Random string using the default filter format:
* @code
* $values['body'][0] = [
* 'value' => $this->randomMachineName(32),
* 'format' => filter_default_format(),
* ];
* @endcode
* - title: Random string.
* - type: 'person'.
* - uid: The currently logged in user, or anonymous.
*
* @return \Drupal\crm_core_contact\IndividualInterface
* The created individual entity.
*/
protected function createIndividual(array $values = []) {
// Populate defaults array.
$values += [
'title' => $this->randomMachineName(8),
'type' => 'person',
];
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;
}
}
$individual = Individual::create($values);
$individual->save();
return $individual;
}
}
