AbstractProvider.php 2.2 KB
<?php

namespace Lackoxygen\TiktokOpen\Base;

use Lackoxygen\TiktokOpen\Application;
use GuzzleHttp\Client;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

abstract class AbstractProvider implements ServiceProviderInterface
{
    /**
     * @var string $alias
     */
    protected string $alias;

    /**
     * @var array
     */
    private array $preServices = [];

    /**
     * @var array
     */
    protected array $services = [];

    /**
     * @var Container $application
     */
    protected Container $application;

    /**
     * @param string $alias
     */
    public function __construct(string $alias)
    {
        $this->alias = $alias;

        $this->addPreService('guzzleHttp', function (Application $app) {
            return new Client(
                [
                    'base_uri' => $app['config']->getUrl(),
                    'timeout' => $app['config']->getTimeout()
                ]
            );
        });
    }

    /**
     * @param Container $pimple
     * @return void
     */
    public function register(Container $pimple)
    {
        $this->application = $pimple;

        $this->registerServices($this->preServices, function (string $key) {
            return $key;
        });
        $this->registerServices($this->services, function (string $key) {
            return $this->alias . '.' . $key;
        });
        $this->application[$this->alias] = $this;
    }

    /**
     * @return array
     */
    protected function getServices(): array
    {
        return array_merge(
            $this->preServices,
            $this->services
        );
    }

    protected function addPreService($name, $service)
    {
        $this->preServices[$name] = $service;
    }

    /**
     * @param $services
     * @param \Closure $callback
     * @return void
     */
    protected function registerServices($services, \Closure $callback)
    {
        foreach ($services as $key => $value) {
            if ($value instanceof \Closure) {
                $service = call_user_func($value, $this->application);
            } else {
                $service = new $value($this->application);
            }
            $this->application[$callback($key)] = $service;
        }
    }
}