Skip to content

Commit

Permalink
Merge pull request #1549 from tripal/tv4g0-issue1522-dependencyInjection
Browse files Browse the repository at this point in the history
Dependency injection for Chado Storage + Storage Property Types/Values
  • Loading branch information
laceysanderson committed Jun 14, 2023
2 parents 34e9b5d + a54bc71 commit 27433f6
Show file tree
Hide file tree
Showing 2 changed files with 121 additions and 59 deletions.
27 changes: 23 additions & 4 deletions tripal/src/TripalStorage/StoragePropertyBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,20 @@

namespace Drupal\tripal\TripalStorage;


/**
* Base class for a Tripal storage property type or value.
*/
class StoragePropertyBase {

/**
* The ID Space Plugin manager service.
* Note: Used to confirm the term passed in exists and to retrieve it.
*
* @var Drupal\tripal\TripalVocabTerms\PluginManagers\TripalIdSpaceManager
*/
protected $idSpaceService;

/**
* Constructs a new Tripal storage property base object.
*
Expand All @@ -27,13 +36,24 @@ public function __construct($entityType, $fieldType, $key, $term_id) {
$this->entityType = $entityType;
$this->fieldType = $fieldType;

// Ideally we would use dependency injection to retrieve the idspace service
// but that is not available in a custom class like this one. Alternatively,
// we could pass the service into the constructor but as this class is inherited
// by many other classes and the constructor is used directly in fields,
// that would be a lot of work.
// Our approach: Manage the drupal container ourselves in this constructor.
// Try to get the current container... It should exist within a bootstrapped
// site (test or otherwise) and kernel tests.
// If it doesn't an exception is thrown here.
$container = \Drupal::getContainer();
$this->idSpaceService = $container->get('tripal.collection_plugin_manager.idspace');

$matches = [];
if (preg_match('/^(.+?):(.+)$/', $term_id, $matches)) {
$this->termIdSpace = $matches[1];
$this->termAccession = $matches[2];

$idsmanager = \Drupal::service('tripal.collection_plugin_manager.idspace');
$idspace = $idsmanager->loadCollection($this->termIdSpace);
$idspace = $this->idSpaceService->loadCollection($this->termIdSpace);
if (!$idspace) {
throw new \Exception('Cannot create a StorageProperty object as IdSpace for the property term is not recognized: ' . $term_id);
}
Expand Down Expand Up @@ -110,8 +130,7 @@ public function getTermAccession() {
* The Tripal Controlled Vocabulary Term Object.
*/
public function getTerm() {
$manager = \Drupal::service('tripal.collection_plugin_manager.idspace');
$idspace = $manager->loadCollection($this->termIdSpace);
$idspace = $this->idSpaceService->loadCollection($this->termIdSpace);
return $idspace->getTerm($this->termAccession);
}

Expand Down

0 comments on commit 27433f6

Please sign in to comment.