1:  2:  3:  4:  5:  6:  7:  8:  9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 
<?php

declare(strict_types=1);

namespace Wtf\ORM;

use Pimple\Container;
use Pimple\ServiceProviderInterface;

class Provider implements ServiceProviderInterface
{
    /**
     * {@inheritdoc}
     */
    public function register(Container $container): void
    {
        $container['medoo'] = $this->setMedoo($container);
        $container['entity'] = $this->setEntityLoader($container);
    }

    /**
     * Set Medoo into container.
     *
     * @param Container $container
     *
     * @return callable
     */
    protected function setMedoo(Container $container): callable
    {
        return function ($container) {
            $config = $container['config']('medoo');

            return new \Medoo\Medoo($config);
        };
    }

    /**
     * Set entity() function into container.
     *
     * @param Container $container
     *
     * @return callable
     */
    protected function setEntityLoader(Container $container): callable
    {
        return $container->protect(function (string $name) use ($container) {
            $parts = \explode('_', $name);
            $class = $container['config']('medoo.namespace');
            foreach ($parts as $part) {
                $class .= \ucfirst($part);
            }
            if (!$container->has('entity_'.$class)) {
                $container['entity_'.$class] = $container->factory(function ($container) use ($class) {
                    return new $class($container);
                });
            }

            return $container['entity_'.$class];
        });
    }
}