<?php

namespace Application\Service\Extension;

use Swoole\Coroutine;

class BaseExtension
{
    protected static $instance;

    protected static array $properties = [];

    public static function app()
    {
        if (!self::isInstance()) {
            self::setInstance(new static());
        }
        // 返回全局实例
        return self::getInstance();
    }

    protected static function isInstance()
    {
        $coroutineId = class_exists(Coroutine::class) ? \Swoole\Coroutine::getuid() : -1;
        $calledClass = get_called_class();
        return isset(self::$instance[$calledClass][$coroutineId]);
    }

    protected static function setInstance(BaseExtension $object)
    {
        $coroutineId = class_exists(Coroutine::class) ? \Swoole\Coroutine::getuid() : -1;
        $calledClass = get_called_class();
        if (!isset(self::$instance[$calledClass][$coroutineId])) {
            self::$instance[$calledClass][$coroutineId] = $object;
        }
    }

    protected static function getInstance()
    {
        $coroutineId = class_exists(Coroutine::class) ? \Swoole\Coroutine::getuid() : -1;
        $calledClass = get_called_class();
        return self::$instance[$calledClass][$coroutineId];
    }

    protected function getProperty($name)
    {
        $cid = class_exists(Coroutine::class) ? Coroutine::getCid() : -1;
        if ($cid > -1) {
            return self::$properties[$cid][$name];
        }

        return self::$properties[$name];
    }

    protected function setProperty($name, $value)
    {
        $cid = class_exists(Coroutine::class) ? Coroutine::getCid() : -1;
        if ($cid > -1) {
            self::$properties[$cid][$name] = $value;
        }

        self::$properties[$name] = $value;
    }
}