0

Is there a good way to format long ternary operator line ? Let's say :

$order = new Order($this->isProfessionalChildCollaborator($this->getUser()) ? $this->getUser()->getParent() : $this->getUser());

This is too long according to 120 char per line defined in PSR. Should I do :

$order = new Order(
    $this->isProfessionalChildCollaborator($this->getUser()) ?
    $this->getUser()->getParent() :
    $this->getUser()
);

Or is there any other best practice?

nbonniot
  • 1,034
  • 16
  • 33
  • Cache `$this->getUser()` call to reduce the chars. You can also wrap `isProfessionalChildCollaborator` inside some smaller method name. – nice_dev Feb 26 '20 at 14:45
  • Is using an `if` clause instead of ternary an option? – brombeer Feb 26 '20 at 14:58
  • According to me, your proposals @vivek_23 and @kerbholz are more workarounds. Imagine the expression as not reduceable, and the question still remains. `if` usage might be the last stage, but my question is around formatting guidelines on ternary. – nbonniot Feb 26 '20 at 15:14
  • 1
    @nbonniot Well, I usually don't initialize constructors with ternary if conditions. So I never ran across these nitpicks. I pass them and decide them in the constructor itself or make use of subtype polymorphism – nice_dev Feb 26 '20 at 15:27

1 Answers1

1

No rules in PSR for that, but I am prefer this style, described in

$documentProcessingIndicatorId = $object->isProcessingDocument()
    ? $object->getDocumentProcessingIndicatorId()
    : null;
Yurii Hierasin
  • 160
  • 1
  • 11