-2

I am working on Rest api end points for different content types. I am using normalizers for the same, but when i'm trying to make use of same normalizer for all content type, conditions in the functions are increasing. How can we reduce the Cyclomatic and NPath complexities. Below is example code snippet:

  $appealData['description'] = !empty($entity->body->getValue()[0]['value']) ? $entity->body->getValue()[0]['value'] : '';
    $appealData['image'] = !empty($imageFile) ? $imageFile->url() : '';
    $appealData['pulloutQuote']['text'] = !empty($entity->field_quote_content->getValue()[0]['value']) ? $entity->field_quote_content->getValue()[0]['value'] : '';
    $appealData['pulloutQuote']['author'] = !empty($entity->field_quote_citation->getValue()[0]['value']) ? $entity->field_quote_citation->getValue()[0]['value'] : '';

Any alternative to check emptiness of field value? I am just trying to replace NULL with ''. Please help me in this regard.

2 Answers 2

0

When you are trying to replace NULL with '', don't use empty(), because empty does a boolean evaluation and would also replace 0 with ''

The shortest null-detecting PHP7 code for single-value fields with a primitive data value (text, number,...) is the null-coalescing operator ??

$foo = $entity->field_foo->value ?? '';
1
  • This is what I would do.
    – Kevin
    Commented May 7, 2020 at 11:37
-1

Some unwanted code can be removed and can be optimised as below:

$appealData['description'] = $entity->body->value ? $entity->body->processed : '';
$appealData['image'] = !empty($imageFile) ? $imageFile->url() : '';
$appealData['pulloutQuote']['text'] = $entity->field_quote_content->value ? $entity->field_quote_content->value : '';
$appealData['pulloutQuote']['author'] = $entity->field_quote_citation->value ? $entity->field_quote_citation->value : '';

Not the answer you're looking for? Browse other questions tagged or ask your own question.