-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRadTools.php
73 lines (66 loc) · 2.24 KB
/
RadTools.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
namespace Drupal\rad_tools;
use Drupal\Core\Entity\EntityInterface;
/**
* A collection of utility functions for Rad developers.
*/
class RadTools {
/**
* A shortcut for entity queries.
*
* @param string $bundle
* A string representing the name of a bundle. A node type if
* $entity_type is omitted.
* @param string $entity_type
* A string representing the type of entity to be queried. Defaults to
* 'node'.
*
* @return \Drupal\Core\Entity\Query\QueryInterface
* The query object that can query the given entity type, prepared with a
* bundle condition.
*/
public static function entityQuery(string $bundle, string $entity_type = 'node') {
return \Drupal::entityQuery($entity_type)->condition('type', $bundle);
}
/**
* Return TRUE if an entity has any values for a field.
*
* @param Drupal\Core\Entity\EntityInterface $entity
* The entity to check for values.
* @param string $field_name
* The machine name of the field to check for values.
*
* @return bool
* TRUE if the entity has values for the field, FALSE if the entity lacks
* that field, or has no values.
*/
public static function hasFieldValue(EntityInterface $entity, string $field_name) {
return $entity->hasField($field_name) && $entity->get($field_name)->count();
}
/**
* Return the first value of a field on an entity.
*
* @param Drupal\Core\Entity\EntityInterface $entity
* The entity containing the field value.
* @param string $field_name
* The name of the field to get the value of.
* @param string|bool $column
* The name of the column containing the field's value. Defaults to 'value',
* pass FALSE to return the item.
*
* @return string|array
* The first value of the field for the entity, or if $column is FALSE, the
* first item for the field.
*/
public static function getFirstValue(EntityInterface $entity, string $field_name, string $column = 'value') {
$value = NULL;
if (self::hasFieldValue($entity, $field_name)) {
$value = $entity->get($field_name)->first()->getValue();
// Set column to FALSE to return the array.
if ($column) {
return $value[$column];
}
}
return $value;
}
}