CounterRepository.php 670 Bytes
<?php

namespace FootyRoom\Repositories;

use FootyRoom\Support\MongoClient;

class CounterRepository
{
    /** @var \FootyRoom\Support\MongoClient */
    protected $mongo;

    public function __construct(MongoClient $mongo)
    {
        $this->mongo = $mongo->footyroom;
    }

    public function getNextId(string $name): int
    {
        $counter = $this->mongo->counters->findOneAndUpdate(
            ['_id' => $name],
            ['$inc' => ['id' => 1]],
            [
                'upsert' => true,
                'returnDocument' => \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER
            ]
        );

        return $counter->id;
    }
}