Uncaught Error: вызов функции-члена set () для null из абстрактного класса - PullRequest
0 голосов
/ 30 сентября 2018

Я вызываю функцию из абстрактного класса, который уже расширяет Controller.

abstract class RestController extends Controller {

    public $appVersion = null;

    public function checkPlugin() {

        $this->config->set('config_error_display', 0);

        $this->response->addHeader('Content-Type: application/json; charset=utf-8');

        if (!$this->config->get('rest_api_status')) {
            $json["error"] = 'API is disabled. Enable it!';
        }

        if(isset($json["error"])){
            header("Content-Type: application/json;charset=utf-8");
            echo(json_encode($json));
            exit;
        }

        $this->validateToken();


        $token = $this->getTokenValue();

        $this->update_session($token['access_token'], json_decode($token['data'], true));

        $headers = apache_request_headers();

        //set language
        $osc_lang = "";
        if(isset($headers['X-Oc-Merchant-Language'])){
            $osc_lang = $headers['X-Oc-Merchant-Language'];
        }else if(isset($headers['X-OC-MERCHANT-LANGUAGE'])){
            $osc_lang = $headers['X-OC-MERCHANT-LANGUAGE'];
        }

        if($osc_lang != ""){
            $this->session->data['language'] = $osc_lang;
            $this->config->set('config_language', $osc_lang);
            $languages = array();
            $this->load->model('localisation/language');
            $all = $this->model_localisation_language->getLanguages();

            foreach ($all as $result) {
                $languages[$result['code']] = $result;
            }
            $this->config->set('config_language_id', $languages[$osc_lang]['language_id']);
        }

        if(isset($headers['X-Oc-Store-Id'])){
            $this->config->set('config_store_id', $headers['X-Oc-Store-Id']);
        } else if(isset($headers['X-OC-STORE-ID'])){
            $this->config->set('config_store_id', $headers['X-OC-STORE-ID']);
        }

        $currency = "";

        if(isset($headers['X-Oc-Currency'])){
            $currency = $headers['X-Oc-Currency'];
        } else if(isset($headers['X-OC-CURRENCY'])){
            $currency = $headers['X-OC-CURRENCY'];
        }

        if (!empty($currency)) {
            $this->currency->set($currency);
        }

        if(isset($headers['X-Oc-Image-Dimension'])){
            $d = $headers['X-Oc-Image-Dimension'];
            $d = explode('x', $d);
            $this->config->set('config_rest_api_image_width', $d[0]);
            $this->config->set('config_rest_api_image_height', $d[1]);
        } else if(isset($headers['X-OC-IMAGE-DIMENSION'])){
            $d = $headers['X-OC-IMAGE-DIMENSION'];
            $d = explode('x', $d);
            $this->config->set('config_rest_api_image_width', $d[0]);
            $this->config->set('config_rest_api_image_height', $d[1]);
        } else {
            $this->config->set('config_rest_api_image_width', 500);
            $this->config->set('config_rest_api_image_height', 500);
        }

        if(defined('VERSION')) {
            $version = str_replace('.', '', VERSION);
            $this->appVersion = sprintf('%-04s', $version);
        } else {
            $this->appVersion = 1234;
        }
    }

Поскольку согласно ООП вы не можете Невозможно создать экземпляр абстрактного класса , то, что я сделал, созданоновый класс контроллера, расширяющий абстрактный класс.

require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestRestApi extends RestController {

    function __construct(){
        //public $opencartVersion = null;
        parent::__construct('checkPlugin');
        $this->checkPlugin();
    }

    public function __get($json) {
      return $this->checkPlugin($json);
    }

    public function __set($json, $token) {
      $this->checkPlugin($json, $token);
    }
    //
    // public function __call($methodName, $args)
    // {
    //   call_user_func_array(array($this, $methodName), $args);
    //   call_user_func_array(array('parent', $methodName), $args);
    // }

    function parentCheckPlugin(){

      // parent::checkPlugin();
      echo "Say Hello";
    }
}

Затем я вызвал абстрактный класс из нового расширенного класса контроллера, чтобы вызвать функцию, которую я не хотел из основного абстрактного класса с использованием VQMod.

  <operation>
    <search position="before"><![CDATA[
         class ControllerProductCategory extends Controller {
     ]]></search>
     <add><![CDATA[
       require_once(DIR_APPLICATION . 'controller/rest/extrestapi.php');
     ]]></add>
  </operation>

  <operation>
    <search position="after"><![CDATA[
         public function index() {
     ]]></search>
     <add><![CDATA[
      $checkPlugin = new ControllerRestRestApi();
       $checkPlugin->parentCheckPlugin();
     ]]></add>
  </operation>

        <operation>
            <search position="replace"><![CDATA[
             $this->response->setOutput($this->render());
             ]]></search>
            <add><![CDATA[

          if ( $_SERVER['REQUEST_METHOD'] === 'GET' ){
                  $json['success']  = true;
                  $this->response->addHeader('Content-Type: application/json; charset=utf-8');
                  $this->response->setOutput(json_encode($this->data));
              }else {
                  $this->response->setOutput($this->render());
         }

            ]]></add>

    </operation>

Теперь я тестирую его с помощью Postman после того, как я позвонил по http и добавил действительный токен. Я получил ошибку.

Уведомление : неопределенное свойство:ControllerRestRestApi :: $ config в / home / user / public_html / system / engine / restcontroller.php on line 10 Неустранимая ошибка : необработанная ошибка: вызов функции-члена set () для null в /home/user/public_html/system/engine/restcontroller.php:10 Трассировка стека:

0 /home / user / public_html / каталог / controller / rest / extrestapi.php (13): RestController-> checkPlugin ('config')

1 /home/user/public_html/system/engine/restcontroller.php (10): ControllerRestRestApi -> __ get ('config')

2 /home/user/public_html/catalog/controller/rest/extrestapi.php(9): RestController-> checkPlugin ()

3 /home/user/public_html/vqmod/vqcache/vq2-catalog_controller_product_category.php(9):

ControllerRestRestApi -> __ construct ()

4 / home / user / public_mod / vvqcache / vq2-system_engine_front.php (47):

ControllerProductCategory-> index ()

5 /home/user/public_html/vqmod/vqcache/vq2-system_engine_front.php(29):

Front-> execute ('')

6 /home/user/public_html/index.php(237): Front-> dispatch (Объект (Действие), Объект (Действие))

7 {main} добавляется / home / user / public_html / system / engine / restcontroller.php on line

10

В соответствии с этой ошибкой она ссылается на эту строку и все после в основной функции абстрактного класса

public function checkPlugin() {

    $this->config->set('config_error_display', 0);

    $this->response->addHeader('Content-Type: application/json; charset=utf-8');

Эта же функция checkPlugin() отлично работает в других контроллерах как таковых

require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerFeedRestApi extends RestController {

    public function getInfo() {

        $this->checkPlugin();

Но не другой контроллер, который я использую и пытаюсь достичь.Что я сделал не так и как разрешить любую помощь, пожалуйста, спасибо заранее!

...