<?php


namespace CMSMSExt\core;

/**
 * A base class for static API classes.
 *
 * This class provides a foundation for creating static API classes.
 * It provides common functionality for initializing the class,
 * extending the options, and handling method calls.
 *
 * @package CMSMSExt\core
 */
class static_api_base
{
  protected static $_initialized = FALSE;
  private static $_options = [];
  
  /**
   * Initializes the class.
   */
  protected static function init()
  {
    if( !self::$_initialized )
    {
      self::$_initialized = TRUE;
    }
  }
  
  /**
   * Checks if an array is associative or not.
   *
   * @param array $arr The array to be checked.
   * @return bool Returns TRUE if the array is associative, FALSE otherwise.
   */
  protected static function _isAssoc(array $arr) : bool
  {
    if([] === $arr) { return FALSE; }
    
    return \array_keys($arr) !== \range(0, \count($arr) - 1);
  }
  
  public static function __callStatic($name, $arguments)
  {
    if( !\startswith($name,  '_') && \method_exists(__CLASS__, $name) )
    {
      self::init();
      
      if( \count($arguments) && self::_isAssoc($arguments) )
      {
        self::extend($arguments);
        
        return \call_user_func_array([__CLASS__, $name], self::$_options);
      }
      
      return \call_user_func_array([__CLASS__, $name], $arguments);
    }
    
    throw new \BadMethodCallException($name);
  }
  
  public static function extend(array  $options) : void
  {
    self::init();
    
    if( self::_isAssoc($options) )
    {
      self::$_options = \array_merge(self::$_options, $options);
    }
  }
  
  
  private static function _callback($name, $arguments)
  {
    if( \is_callable($name) )
    {
      return \call_user_func_array($name, $arguments);
    }
    
    throw new \BadFunctionCallException($name);
  }
  
}

?>