7

I'm trying to get a property on the last element in a collection. I tried

end($collection)->getProperty()

and

$collection->last()->getProperty()

none works

(tells me I'm trying to use getProperty() on a boolean).

/**
 * Get legs
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getLegs()
{
    return $this->aLegs;
}

public function getLastlegdate()
{
    $legs = $this->aLegs;

    return $legs->last()->getStartDate();
}

Any idea why ?

Matteo
  • 37,680
  • 11
  • 100
  • 115
Pierre Olivier Tran
  • 1,669
  • 4
  • 24
  • 40

2 Answers2

16

The problem you have is due because the collection is empty. Internally the last() method use the end() php function that from the doc:

Returns the value of the last element or FALSE for empty array.

So change your code as follow:

$property = null

if (!$collection->isEmpty())
{
$property =  $collection->last()->getProperty();
}

hope this help

Matteo
  • 37,680
  • 11
  • 100
  • 115
0

This $collection->last()->getProperty() is breaking the law of Demeter. The function should have a single responsibility. Try this.

/**
 * @return Leg|null
 */
public function getLastLeg(): ?Leg
{
   $lastLeg = null;
   if (!$this->aLegs->isEmpty()) {
     $lastLeg = $this->aLegs->last();
   }
   return $lastLeg;
}

/**
 * @return \DateTime|null
 */
 public function getLastLegDate(): ?\DateTime
 {
   $lastLegDate = null;
   $lastLeg = $this->getLastLeg();
   if ($lastLeg instanceOf Leg) {
     $lastLeg->getStartDate();
   }

   return $lastLegDate;
 }
Buczek
  • 1
  • 1