public function toDeathReasons(Battle $battle) { if (is_array($this->death_reasons) || $this->death_reasons instanceof \stdClass) { $unknownCount = 0; foreach ($this->death_reasons as $key => $count) { $reason = DeathReason::findOne(['key' => $key]); if ($key === 'unknown' || !$reason) { $unknownCount += (int) $count; } else { $o = new BattleDeathReason(); $o->battle_id = $battle->id; $o->reason_id = $reason->id; $o->count = (int) $count; (yield $o); } } if ($unknownCount > 0) { $reason = DeathReason::findOne(['key' => 'unknown']); if ($reason) { $o = new BattleDeathReason(); $o->battle_id = $battle->id; $o->reason_id = $reason->id; $o->count = (int) $unknownCount; (yield $o); } } } }