This repository has been archived on 2022-07-12. You can view files and clone it, but cannot push or open issues or pull requests.
opencase/src/Utils.php

54 lines
1.5 KiB
PHP

<?php declare(strict_types =1);
namespace Drupal\opencase;
use \Drupal;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use RuntimeException;
class Utils {
public function __construct(
EntityTypeManagerInterface $entityTypeManager = null
) {
if ($entityTypeManager == null) {
$entityTypeManager = Drupal::entityTypeManager();
}
$this->entityTypeManager = $entityTypeManager;
}
public function addConditionsToQuery(QueryInterface $query, array $conditions): void {
foreach($conditions as $condition) {
$field = $condition[0];
$value = $condition[1];
$operator = isset($condition[2]) ? $condition[2] : "=";
$query->condition($field, $value, $operator);
}
}
/**
* Utility: find term by name and vid.
*
* @param string $name
* Term name.
* @param string $vid
* Term vid.
* @return int
* Term id, or 0 if none.
*/
public function getTidByName(string $name, string $vid):int {
if (empty($name) || empty($vid)) {
return 0;
}
$properties = [
'name' => $name,
'vid' => $vid,
];
$terms = $this->entityTypeManager->getStorage('taxonomy_term')->loadByProperties($properties);
$term = reset($terms);
return (int)(!empty($term) ? $term->id() : 0);
}
}