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: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 
<?php
/**
 * Copyright (C) Apis Networks, Inc - All Rights Reserved.
 *
 * Unauthorized copying of this file, via any medium, is
 * strictly prohibited without consent. Any dissemination of
 * material herein is prohibited.
 *
 * For licensing inquiries email <licensing@apisnetworks.com>
 *
 * Written by Matt Saladna <matt@apisnetworks.com>, December 2017
 */

declare(strict_types=1);

/**
 * Session-less fixation of secondary accounts
 *
 * Mix with apnscpFunctionInterceptor trait for afi invocation
 * Mix with \Preferences::factory() for pref manipulation
 */
trait ContextableTrait {
    /**
     * @var \Auth_Info_User
     */
    private $authContext;

    /**
     * Set context for afi or Preference invocation
     *
     * @param Auth_Info_User $context
     */
    public function setContext(\Auth_Info_User $context): void {
        $this->authContext = $context;
        if (method_exists($this, 'setApnscpFunctionInterceptor')) {
            $this->setApnscpFunctionInterceptor(\apnscpFunctionInterceptor::factory($context));
        }
    }

    /**
     * Substitute apnscpFunctionInterceptor then build class
     *
     * @param Auth_Info_User $context
     * @param array          $constructorArgs arguments to provide to constructor
     * @return self
     */
    public static function instantiateContexted(\Auth_Info_User $context, array $constructorArgs = []): self {
        $rfxn = (new \ReflectionClass(static::class))->newInstanceWithoutConstructor();
        $rfxn->setContext($context);
        if (method_exists($rfxn, '__construct')) {
            $rfxn->__construct(...$constructorArgs);
        }
        return $rfxn;
    }

    /**
     * Module calls in authenticiation context
     *
     * @return bool
     */
    protected function inContext(): bool
    {
        return $this->authContext !== null;
    }

    /**
     * Get user authentication instance
     *
     * @return \Auth_Info_User
     */
    protected function getAuthContext(): \Auth_Info_User
    {
        return $this->authContext ?? \Auth::autoload()->getProfile();
    }
}