api = $api; $this->options = []; $this->type = $data['type']; if ($data['type'] === Poll::$notice_type) { $val = $data['value']; $this->closed_at = new \DateTime($val['closed_at']); foreach ($val['options'] as $option) { $this->options[] = new PollOption($option); } $this->id = (int)$val['poll_id']; $this->token = $val['poll_token']; $this->prompt = $val['prompt']; } elseif (in_array($data['type'], Poll::$poll_types)) { $this->parsePoll($data); } elseif (strpos($data['type'], '.poll') !== false) { // Try parsing unknown types if they *might* be a poll try { $this->parsePoll($data); } catch (\Exception $e) { throw new NotSupportedPollException($data['type']); } } else { throw new NotSupportedPollException($data['type']); } } private function parsePoll(array $data) { $this->created_at = new \DateTime($data['created_at']); $this->closed_at = new \DateTime($data['closed_at']); $this->id = (int)$data['id']; $this->is_anonymous = (bool)$data['is_anonymous']; $this->is_public = (bool)$data['is_public']; foreach ($data['options'] as $option) { $this->options[] = new PollOption($option); } if (!empty($data['poll_token'])) { $this->token = $data['poll_token']; } $this->prompt = $data['prompt']; if (!empty($data['user'])) { $this->user = new User($data['user'], $this->api); } if (!empty($data['source'])) { $this->source = new Source($data['source']); } } /** * Returns the most voted option. If multiple options have the same amount * of voted, return all of them. Always returns an array! */ public function getMostVotedOption(): array { if (count($this->options) === 0) { return []; } $optns = []; //$most_voted_option = $this->options[0]; $most_voted_option = null; foreach ($this->options as $option) { if ($option->greaterThan($most_voted_option)) { $optns = []; $most_voted_option = $option; $optns[] = $option; } elseif ($option->greaterThanOrSame($most_voted_option)) { $optns[] = $option; } } return $optns; } public static function isValidPoll(string $type): bool { return $type === Poll::$notice_type || in_array($type, Poll::$poll_types); } public function __toString(): string { if (!empty($this->user)) { $str = $this->user->username; #$str = 'Unknown user'; } else { $str = 'Unknown user'; } return $str . " asked: '" . $this->prompt . "', closed at " . $this->closed_at->format('Y-m-d H:i:s T'); } }