1
\$\begingroup\$

I am creating an online voting platform where users could vote on publicly-held polls. It uses Kreait Firebase library (as Google didn't create a PHP library for Firebase Admin).

I am very new to PHP and am not sure about how I should format my PHP code. It is messy. Please help me improve the code.

<?php

$request = json_decode(file_get_contents("php://input"));

if (!isset($request->pollPath) || !isset($request->votes)) {
  print_r($request);
  echo "pollPath and/or votes have not been sent!";
  exit;
}

require __DIR__.'/../vendor/autoload.php';

use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;

$pollPath = $request->pollPath;
$votes = $request->votes;

$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/../service.credentials.json');
$firebase = (new Factory)
  ->withServiceAccount($serviceAccount)
  ->asUser('brokerServer')
  ->create();

$pollsDatabase = $firebase->getDatabase();
$electionRef = $pollsDatabase->getReference('publicPolls/' . $request->pollPath);

$postsRef = $electionRef->getChild('posts');
$postsCount = $postsRef->getSnapshot()->numChildren();

if ($postsCount != count($request->votes)) {
  echo "Array of votes doesn't match the election's position count";
  exit;
}

$votesRef = $electionRef->getChild('votes');
$electionVotes = $votesRef->getValue();

if (!isset($electionVotes))
  $electionVotes = [];

$postsValue = $postsRef->getValue();
for ($i = 0; $i  < $postsCount; $i++) {
  $postValue = &$postsValue[$i];
  $postVotes = &$electionVotes[$i];

  if (!isset($postVotes)) {
    $postVotes = [];
    $postCands = count($postValue['candidates']);

    for ($j = 0; $j < $postCands; $j++)
      $postVotes[$postValue['candidates'][$j]] = 0;
  }

  if (isset($request->votes[$i]))
    $postVotes[$request->votes[$i]] += 1;
}

$votesRef->set($electionVotes);
print_r($electionVotes);
echo "done";

The code basically gets a JSON fetch request from the client with the path of the election (in Firebase) and an array of votes (mapping index of positions in election to the candidates chosen).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.