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.


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

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

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)

$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";

$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;

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).


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.