clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
config:
- log.type.birth
id: log.birth.asset
field_name: asset
entity_type: log
bundle: birth
label: Children
description: 'Which child assets were born?'
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
handler: views
handler_settings:
view:
view_name: farm_asset_reference
display_name: entity_reference
field_type: entity_reference
@@ -0,0 +1,14 @@
langcode: en
status: true
dependencies:
module:
- farm_log
enforced:
module:
- farm_birth
id: birth
label: Birth
description: ''
name_pattern: 'Birth log [log:id]'
workflow: farm_log_workflow
new_revision: true
@@ -0,0 +1,9 @@
name: Birth log
description: Adds a Birth log type for Animal assets.
type: module
package: farmOS Logs
core_version_requirement: ^10
dependencies:
- farm:farm_animal
- farm:farm_entity
- log:log
@@ -0,0 +1,64 @@
<?php
/**
* @file
* Contains farm_birth.module.
*/
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\Entity\BaseFieldOverride;
use Drupal\Core\Url;
/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function farm_birth_asset_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
// Only alter animal assets.
if ($entity->bundle() != 'animal') {
return;
}
// Add a link to the asset's birth log.
if (!empty($build['birthdate'][0])) {
/** @var \Drupal\Core\Entity\EntityStorageInterface $log_storage */
$log_storage = \Drupal::service('entity_type.manager')->getStorage('log');
$log_ids = $log_storage->getQuery()
->accessCheck(TRUE)
->condition('type', 'birth')
->condition('asset', $entity->id())
->execute();
// Render a link to the log with a title of the timestamp field value.
if (!empty($log_ids)) {
$title = $build['birthdate'][0];
$build['birthdate'][0] = [
'#type' => 'link',
'#title' => $title,
'#url' => Url::fromRoute('entity.log.canonical', ['log' => reset($log_ids)]),
];
}
}
}
/**
* Implements hook_entity_bundle_field_info().
*/
function farm_birth_entity_bundle_field_info(EntityTypeInterface $entity_type, $bundle, array $base_field_definitions) {
$fields = [];
// Add the UniqueBirthLog validation constraint to the asset field of birth
// logs. We need to do this via hook_entity_bundle_field_info() instead of
// hook_entity_field_info_alter() because this module also provides a
// BaseFieldOverride for the asset field, and there is a Drupal core issue
// that prevents these from working together normally.
// @see https://www.drupal.org/project/drupal/issues/3193351
if ($entity_type->id() == 'log' && $bundle == 'birth') {
$fields['asset'] = BaseFieldOverride::loadByName($entity_type->id(), $bundle, 'asset') ?: clone $base_field_definitions['asset'];
$fields['asset']->addConstraint('UniqueBirthLog');
}
return $fields;
}
@@ -0,0 +1,23 @@
<?php
/**
* @file
* Post update hooks for the farm_birth module.
*/
/**
* Override the birth log asset label and description.
*/
function farm_birth_post_update_override_birth_asset_label_description(&$sandbox) {
// Override the asset field label and description on birth logs to make it
// clear that it should be used to reference the child assets that were born.
// This also checks to make sure they haven't been overridden already first.
/** @var \Drupal\Core\Field\Entity\BaseFieldOverride $config */
$config = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('log')['asset']->getConfig('birth');
if ($config->isNew()) {
$config->set('label', 'Children');
$config->set('description', 'Which child assets were born?');
$config->save();
}
}
@@ -0,0 +1,6 @@
services:
farm_birth.log_event_subscriber:
class: Drupal\farm_birth\EventSubscriber\LogEventSubscriber
arguments: [ '@messenger' ]
tags:
- { name: 'event_subscriber' }
@@ -0,0 +1,124 @@
<?php
namespace Drupal\farm_birth\EventSubscriber;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\log\Event\LogEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Sync child asset fields to reflect those saved in a birth log.
*/
class LogEventSubscriber implements EventSubscriberInterface {
use StringTranslationTrait;
/**
* The Messenger service.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* MyModuleService constructor.
*
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger service.
*/
public function __construct(MessengerInterface $messenger) {
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*
* @return array
* The event names to listen for, and the methods that should be executed.
*/
public static function getSubscribedEvents() {
return [
LogEvent::INSERT => 'syncBirthChildren',
LogEvent::UPDATE => 'syncBirthChildren',
];
}
/**
* Sync child asset fields to reflect those saved in a birth log.
*
* @param \Drupal\log\Event\LogEvent $event
* The log event.
*/
public function syncBirthChildren(LogEvent $event): void {
// Get the log entity from the event.
$log = $event->log;
// If this is not a birth log, bail.
if ($log->bundle() != 'birth') {
return;
}
// Load mother asset.
/** @var \Drupal\asset\Entity\AssetInterface $mother */
$mothers = $log->get('mother')->referencedEntities();
$mother = reset($mothers);
// Load children assets.
/** @var \Drupal\asset\Entity\AssetInterface[] $children */
$children = $log->get('asset')->referencedEntities();
// If the log doesn't reference any children, bail.
if (empty($children)) {
return;
}
// Iterate through the children.
foreach ($children as $child) {
$save = FALSE;
$revision_log = [];
// If the child is an animal, and their date of birth does not match the
// timestamp of the birth log, sync it.
if ($child->bundle() == 'animal' && $child->get('birthdate')->value != $log->get('timestamp')->value) {
$args = [
':child_url' => $child->toUrl()->toString(),
'%child_name' => $child->label(),
];
$message = $this->t('<a href=":child_url">%child_name</a> date of birth was updated to match their birth log.', $args);
$this->messenger->addMessage($message);
$revision_log[] = $message;
$child->birthdate = $log->get('timestamp')->value;
$save = TRUE;
}
// If a mother is specified, and the child does not have any parents,
// add the mother to the child's parent reference field.
if (!empty($mother)) {
$parents = $child->get('parent')->referencedEntities();
if (empty($parents)) {
$args = [
':mother_url' => $mother->toUrl()->toString(),
'%mother_name' => $mother->label(),
':child_url' => $child->toUrl()->toString(),
'%child_name' => $child->label(),
];
$message = $this->t('<a href=":mother_url">%mother_name</a> added as a parent of <a href=":child_url">%child_name</a>.', $args);
$this->messenger->addMessage($message);
$revision_log[] = $message;
$child->parent[] = ['target_id' => $mother->id()];
$save = TRUE;
}
}
// Save the child, if necessary.
if ($save) {
$revision_log[] = $this->t('Birth log saved: <a href=":birth_url">%birth_label</a>', [':birth_url' => $log->toUrl()->toString(), '%birth_label' => $log->label()]);
$child->setRevisionLogMessage(implode(" ", $revision_log));
$child->save();
}
}
}
}
@@ -0,0 +1,51 @@
<?php
namespace Drupal\farm_birth\Plugin\Log\LogType;
use Drupal\farm_entity\Plugin\Log\LogType\FarmLogType;
/**
* Provides the birth log type.
*
* @LogType(
* id = "birth",
* label = @Translation("Birth"),
* )
*/
class Birth extends FarmLogType {
/**
* {@inheritdoc}
*/
public function buildFieldDefinitions() {
$fields = parent::buildFieldDefinitions();
// Mother.
$options = [
'type' => 'entity_reference',
'label' => $this->t('Mother'),
'target_type' => 'asset',
'target_bundle' => 'animal',
'weight' => [
'form' => 45,
'view' => -15,
],
];
$fields['mother'] = $this->farmFieldFactory->bundleFieldDefinition($options);
// Veterinarian.
$options = [
'type' => 'string',
'label' => $this->t('Veterinarian'),
'description' => $this->t('If a veterinarian was involved, enter their name here.'),
'weight' => [
'form' => -40,
'view' => -40,
],
];
$fields['vet'] = $this->farmFieldFactory->bundleFieldDefinition($options);
return $fields;
}
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\farm_birth\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* Checks that only one birth log references an asset.
*
* @Constraint(
* id = "UniqueBirthLog",
* label = @Translation("Unique birth log", context = "Validation"),
* )
*/
class UniqueBirthLogConstraint extends Constraint {
/**
* The default violation message.
*
* @var string
*/
public $message = '%child already has a birth log. More than one birth log cannot reference the same child.';
}
@@ -0,0 +1,86 @@
<?php
namespace Drupal\farm_birth\Plugin\Validation\Constraint;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the UniqueBirthLog constraint.
*/
class UniqueBirthLogConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a UniqueBirthLogConstraintValidator object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint) {
/** @var \Drupal\Core\Field\EntityReferenceFieldItemList $value */
/** @var \Drupal\farm_birth\Plugin\Validation\Constraint\UniqueBirthLogConstraint $constraint */
// Only continue if this is a birth log.
/** @var \Drupal\log\Entity\LogInterface $log */
$log = $value->getParent()->getValue();
if (!is_null($log) && $log->bundle() != 'birth') {
return;
}
// Iterate through referenced entities.
foreach ($value->referencedEntities() as $delta => $asset) {
// If the log is not new, skip validation.
// A birth log exits so there is no need to check if one can be created.
/** @var \Drupal\log\Entity\LogInterface $log */
$log = $value->getParent()->getValue();
if (!$log->isNew()) {
return;
}
// Query the number of birth logs that reference the asset.
// We do not check access to ensure that all matching logs are found.
$count = $this->entityTypeManager->getStorage('log')->getAggregateQuery()
->accessCheck(FALSE)
->condition('type', 'birth')
->condition('asset', $asset->id())
->count()
->execute();
// If more than 0 birth logs reference the asset, add a violation.
if ($count > 0) {
$this->context->buildViolation($constraint->message, ['%child' => $asset->label()])
->atPath((string) $delta . '.target_id')
->setInvalidValue($asset->id())
->addViolation();
}
}
}
}
@@ -0,0 +1,233 @@
<?php
namespace Drupal\Tests\farm_birth\Kernel;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\KernelTests\KernelTestBase;
use Drupal\asset\Entity\Asset;
use Drupal\log\Entity\Log;
use Drupal\taxonomy\Entity\Term;
/**
* Tests for farmOS birth log logic.
*
* @group farm
*/
class BirthTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'asset',
'log',
'entity',
'farm_animal',
'farm_animal_type',
'farm_birth',
'farm_entity',
'farm_entity_fields',
'farm_entity_views',
'farm_field',
'farm_id_tag',
'farm_log',
'farm_log_asset',
'farm_parent',
'file',
'geofield',
'image',
'options',
'state_machine',
'system',
'user',
'taxonomy',
'text',
'views',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('asset');
$this->installEntitySchema('log');
$this->installEntitySchema('taxonomy_term');
$this->installEntitySchema('user');
$this->installConfig([
'farm_entity_views',
'farm_animal',
'farm_animal_type',
'farm_birth',
]);
}
/**
* Test that saving a birth log syncs data to children assets.
*/
public function testBirthLogChildrenSync() {
// Create a Cow animal type term.
/** @var \Drupal\taxonomy\TermInterface $cow */
$cow = Term::create([
'name' => 'Cow',
'vid' => 'animal_type',
]);
$cow->save();
// Create a mother animal asset.
/** @var \Drupal\asset\Entity\AssetInterface $mother */
$mother = Asset::create([
'name' => $this->randomMachineName(),
'type' => 'animal',
'animal_type' => ['tid' => $cow->id()],
'status' => 'active',
]);
$mother->save();
// Create 2 children animal assets.
/** @var \Drupal\asset\Entity\AssetInterface $child1 */
$child1 = Asset::create([
'name' => $this->randomMachineName(),
'type' => 'animal',
'animal_type' => ['tid' => $cow->id()],
'status' => 'active',
]);
$child1->save();
/** @var \Drupal\asset\Entity\AssetInterface $child2 */
$child2 = Asset::create([
'name' => $this->randomMachineName(),
'type' => 'animal',
'animal_type' => ['tid' => $cow->id()],
'status' => 'active',
]);
$child2->save();
// Confirm that the children do not have parents or dates of birth.
$this->assertEmpty($child1->get('parent')->referencedEntities());
$this->assertEmpty($child2->get('parent')->referencedEntities());
$this->assertEmpty($child1->get('birthdate')->value);
$this->assertEmpty($child2->get('birthdate')->value);
// Get the current timestamp.
$timestamp = \Drupal::time()->getRequestTime();
// Create a birth log that references the mother and children.
$log = Log::create([
'name' => $this->randomMachineName(),
'type' => 'birth',
'timestamp' => $timestamp,
'mother' => ['target_id' => $mother->id()],
'asset' => [
['target_id' => $child1->id()],
['target_id' => $child2->id()],
],
]);
$log->save();
// Reload children assets.
$child1 = Asset::load($child1->id());
$child2 = Asset::load($child2->id());
// Confirm that the children list the mother as their parent and have dates
// of birth equal to the birth log.
$this->assertNotEmpty($child1->get('parent')->referencedEntities());
$this->assertNotEmpty($child2->get('parent')->referencedEntities());
$this->assertEquals($mother->id(), $child1->get('parent')->referencedEntities()[0]->id());
$this->assertEquals($mother->id(), $child2->get('parent')->referencedEntities()[0]->id());
$this->assertEquals($timestamp, $child1->get('birthdate')->value);
$this->assertEquals($timestamp, $child2->get('birthdate')->value);
// Create another mother animal asset.
/** @var \Drupal\asset\Entity\AssetInterface $mother2 */
$mother2 = Asset::create([
'name' => $this->randomMachineName(),
'type' => 'animal',
'animal_type' => ['tid' => $cow->id()],
'status' => 'active',
]);
$mother2->save();
// Create a birth log that references the second mother and one of the
// original children.
$log = Log::create([
'name' => $this->randomMachineName(),
'type' => 'birth',
'timestamp' => $timestamp,
'mother' => ['target_id' => $mother2->id()],
'asset' => [
['target_id' => $child1->id()],
],
]);
$log->save();
// Reload the first child asset.
$child1 = Asset::load($child1->id());
// Confirm that the child's parent has NOT changed to the new mother. If a
// child already has parents they should not be changed.
$this->assertNotEmpty($child1->get('parent')->referencedEntities());
$this->assertNotEquals($mother2->id(), $child1->get('parent')->referencedEntities()[0]->id());
}
/**
* Test that only one birth log can reference an asset.
*/
public function testUniqueBirthLogConstraint() {
// Create a Cow animal type term.
/** @var \Drupal\taxonomy\TermInterface $cow */
$cow = Term::create([
'name' => 'Cow',
'vid' => 'animal_type',
]);
$cow->save();
// Create an asset.
/** @var \Drupal\asset\Entity\AssetInterface $asset */
$asset = Asset::create([
'name' => $this->randomMachineName(),
'type' => 'animal',
'animal_type' => ['tid' => $cow->id()],
'status' => 'active',
]);
$asset->save();
// Create a birth log that references the asset.
$log1 = Log::create([
'name' => $this->randomMachineName(),
'type' => 'birth',
'timestamp' => \Drupal::time()->getRequestTime(),
'asset' => [['target_id' => $asset->id()]],
]);
// Confirm that there are no validation errors.
$errors = $log1->validate();
$this->assertCount(0, $errors);
$log1->save();
// Create a second birth log that references the asset.
$log2 = Log::create([
'name' => $this->randomMachineName(),
'type' => 'birth',
'timestamp' => \Drupal::time()->getRequestTime(),
'asset' => [['target_id' => $asset->id()]],
]);
// Confirm that validation fails.
$errors = $log2->validate();
$this->assertCount(1, $errors);
$this->assertEquals(new FormattableMarkup('%child already has a birth log. More than one birth log cannot reference the same child.', ['%child' => $asset->label()]), $errors[0]->getMessage());
$this->assertEquals('asset.0.target_id', $errors[0]->getPropertyPath());
// Try updating the original birth log.
$log1->set('name', $this->randomMachineName());
// Confirm there are no validation errors.
$errors = $log1->validate();
$this->assertCount(0, $errors);
$log1->save();
}
}