62 lines
2.0 KiB
PHP
62 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Polls;
|
|
|
|
use App\Models\Poll;
|
|
use App\Models\PollLedgerEntry;
|
|
use App\Models\PollResponse;
|
|
use App\Models\User;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
/**
|
|
* Remove the votes of a permanently deleted profile: the link to the voter is deleted
|
|
* (poll_responses + poll_answers) and the ballot is withdrawn in the ledger, so the totals
|
|
* change visibly instead of silently. The anonymous ballot itself stays in the chain.
|
|
*/
|
|
class VoteWithdrawal
|
|
{
|
|
public function __construct(private Ledger $ledger)
|
|
{
|
|
}
|
|
|
|
/**
|
|
* @return int number of withdrawn votes
|
|
*/
|
|
public function withdrawFor(Model $profile): int
|
|
{
|
|
// The profile's own votes
|
|
$responses = PollResponse::where('voter_type', get_class($profile))
|
|
->where('voter_id', $profile->getKey())
|
|
->get();
|
|
|
|
// A user's own votes on behalf of an organization / bank / admin in "one vote per linked user" polls.
|
|
// In "one vote per profile" polls the vote belongs to that profile and stays.
|
|
if ($profile instanceof User) {
|
|
$responses = $responses->merge(
|
|
PollResponse::where('user_id', $profile->getKey())
|
|
->where('voter_type', '!=', User::class)
|
|
->whereHas('poll', fn ($query) => $query->where('vote_scope', Poll::VOTE_SCOPE_PER_USER))
|
|
->get()
|
|
);
|
|
}
|
|
|
|
foreach ($responses as $response) {
|
|
DB::transaction(function () use ($response) {
|
|
if ($response->ledger_sequence) {
|
|
$this->ledger->append(
|
|
$response->poll,
|
|
PollLedgerEntry::WITHDRAW,
|
|
['reason' => 'profile_deleted'],
|
|
null,
|
|
$response->ledger_sequence
|
|
);
|
|
}
|
|
$response->delete(); // answers cascade
|
|
});
|
|
}
|
|
|
|
return $responses->count();
|
|
}
|
|
}
|