/** * Vote for a particular post * * @param DataObject $post */ public function vote(DataObject $post, $dir = 1) { $member = $this->securityContext->getMember(); if ($member->VotesToGive <= 0) { $post->RemainingVotes = 0; return $post; } // we allow multiple votes - as many as the user has to give! unless // configured not to... $currentVote = null; if ($this->singleVotes) { $votes = $post->currentVotesByUser(); if (count($votes)) { $currentVote = $votes[0]; } } if (!$currentVote) { $currentVote = MicroPostVote::create(); $currentVote->UserID = $member->ID; $currentVote->PostID = $post->ID; } $currentVote->Direction = $dir > 0 ? 1 : -1; $currentVote->write(); $list = DataList::create('MicroPostVote'); $upList = $list->filter(array('PostID' => $post->ID, 'Direction' => 1)); $post->Up = $upList->count(); $downList = $list->filter(array('PostID' => $post->ID, 'Direction' => -1)); $post->Down = $downList->count(); $owner = $post->Owner(); if (!$post->OwnerID || !$owner || !$owner->exists()) { $owner = Security::findAnAdministrator(); } // write the post as the owner, and calculate some changes for the author $this->transactionManager->run(function () use($post, $currentVote, $member) { $author = $post->Owner(); if ($author && $author->exists() && $author->ID != $member->ID) { if ($currentVote->Direction > 0) { $author->Up += 1; } else { $author->Down += 1; } $author->write(); } $post->write(); }, $owner); $this->rewardMember($member, -1); $post->RemainingVotes = $member->VotesToGive; return $post; }