<?php
/**
 * Dependency injection container
 *
 * @package NemtlyBooking
 */

namespace NemtlyBooking\Core;

class Container {

    /**
     * Services container
     *
     * @var array
     */
    private $services = [];

    /**
     * Service instances
     *
     * @var array
     */
    private $instances = [];

    /**
     * Register a service
     *
     * @param string          $id      Service identifier.
     * @param callable|object $service Service definition.
     */
    public function register( $id, $service ) {
        $this->services[ $id ] = $service;
    }

    /**
     * Get a service
     *
     * @param string $id Service identifier.
     *
     * @return mixed
     * @throws \Exception When the requested service is not found.
     */
    public function get( $id ) {
        if ( isset( $this->instances[ $id ] ) ) {
            return $this->instances[ $id ];
        }

        if ( ! isset( $this->services[ $id ] ) ) {
            throw new \Exception( esc_html( "Service {$id} not found" ) );
        }

        $service = $this->services[ $id ];
        if ( is_callable( $service ) ) {
            $this->instances[ $id ] = $service( $this );
        } else {
            $this->instances[ $id ] = $service;
        }

        return $this->instances[ $id ];
    }

    /**
     * Check if service exists
     *
     * @param string $id Service identifier.
     *
     * @return bool
     */
    public function has( $id ) {
        return isset( $this->services[ $id ] );
    }
}
