Source of file Listener.php

Size: 7,335 Bytes - Last Modified: 2020-10-24T02:46:31+00:00

/home/travis/build/NextDom/nextdom-core/src/Model/Entity/Listener.php

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
<?php
/* This file is part of NextDom Software.
 *
 * NextDom is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * NextDom Software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with NextDom Software. If not, see <http://www.gnu.org/licenses/>.
 */

namespace NextDom\Model\Entity;

use NextDom\Enums\LogTarget;
use NextDom\Enums\NextDomObj;
use NextDom\Exceptions\CoreException;
use NextDom\Helpers\DBHelper;
use NextDom\Helpers\LogHelper;
use NextDom\Helpers\SystemHelper;
use NextDom\Helpers\Utils;
use NextDom\Managers\ListenerManager;
use NextDom\Model\Entity\Parents\BaseEntity;

/**
 * Listener
 *
 * @ORM\Table(name="listener", indexes={@ORM\Index(name="event", columns={"event"})})
 * @ORM\Entity
 */
class Listener extends BaseEntity
{
    const TABLE_NAME = NextDomObj::LISTENER;

    /**
     * @var string
     *
     * @ORM\Column(name="class", type="string", length=127, nullable=true)
     */
    protected $class;

    /**
     * @var string
     *
     * @ORM\Column(name="function", type="string", length=127, nullable=true)
     */
    protected $function;

    /**
     * @var string
     *
     * @ORM\Column(name="event", type="string", length=255, nullable=true)
     */
    protected $event;

    /**
     * @var string
     *
     * @ORM\Column(name="option", type="text", length=65535, nullable=true)
     */
    protected $option;

    /**
     * @param $_event
     * @param $_value
     * @param null $_datetime
     * @throws \Exception
     */
    public function run($_event, $_value, $_datetime = null)
    {
        $option = [];
        if (count($this->getOption()) > 0) {
            $option = $this->getOption();
        }
        if (isset($option['background']) && $option['background'] == false) {
            $this->execute($_event, $_value, $_datetime);
        } else {
            $cmd = NEXTDOM_ROOT . '/src/Api/start_listener.php';
            $cmd .= ' listener_id=' . $this->getId() . ' event_id=' . $_event . ' "value=' . escapeshellarg($_value) . '"';
            if ($_datetime !== null) {
                $cmd .= ' "datetime=' . escapeshellarg($_datetime) . '"';
            }
            SystemHelper::php($cmd . ' >> ' . LogHelper::getPathToLog('listener_execution') . ' 2>&1 &');
        }
    }

    /**
     * @param string $_key
     * @param string $_default
     * @return array|bool|mixed|null|string
     */
    public function getOption($_key = '', $_default = '')
    {
        return Utils::getJsonAttr($this->option, $_key, $_default);
    }

    /**
     * @param $_key
     * @param string $_value
     * @return $this
     */
    public function setOption($_key, $_value = '')
    {
        $option = Utils::setJsonAttr($this->option, $_key, $_value);
        $this->updateChangeState($this->option, $option);
        $this->option = $option;
        return $this;
    }

    /**
     * @param $_event
     * @param $_value
     * @param string $_datetime
     * @throws \Exception
     */
    public function execute($_event, $_value, $_datetime = '')
    {
        try {
            $option = [];
            if (count($this->getOption()) > 0) {
                $option = $this->getOption();
            }
            $option['event_id'] = $_event;
            $option['value'] = $_value;
            $option['datetime'] = $_datetime;
            $option['listener_id'] = $this->getId();
            if ($this->getClass() != '') {
                $targetClass = $this->getClass();
                $function = $this->getFunction();
                if (class_exists($targetClass) && method_exists($targetClass, $function)) {
                    $targetClass::$function($option);
                } else {
                    LogHelper::addDebug(LogTarget::LISTENER, __('[Erreur] Classe ou fonction non trouvée ') . $this->getName());
                    $this->remove();
                    return;
                }
            } else {
                $function = $this->getFunction();
                if (function_exists($function)) {
                    $function($option);
                } else {
                    LogHelper::addError(LogTarget::LISTENER, __('[Erreur] Non trouvée ') . $this->getName());
                    return;
                }
            }
        } catch (\Exception $e) {
            LogHelper::addError(Utils::init('plugin_id', 'plugin'), $e->getMessage());
        }
    }

    /**
     * @return string
     */
    public function getClass()
    {
        return $this->class;
    }

    /**
     * @param $_class
     * @return $this
     */
    public function setClass($_class)
    {
        $this->updateChangeState($this->class, $_class);
        $this->class = $_class;
        return $this;
    }

    /**
     * @return string
     */
    public function getFunction()
    {
        return $this->function;
    }

    /**
     * @param $_function
     * @return $this
     */
    public function setFunction($_function)
    {
        $this->updateChangeState($this->function, $_function);
        $this->function = $_function;
        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        if ($this->getClass() != '') {
            return $this->getClass() . '::' . $this->getFunction() . '()';
        }
        return $this->getFunction() . '()';
    }

    public function preSave()
    {
        if ($this->getFunction() == '') {
            throw new CoreException(__('La fonction ne peut pas être vide'));
        }
    }

    /**
     * @param bool $_once
     * @return bool
     * @throws \NextDom\Exceptions\CoreException
     * @throws \ReflectionException
     */
    public function save($_once = false)
    {
        if ($_once) {
            ListenerManager::removeByClassFunctionAndEvent($this->getClass(), $this->getFunction(), $this->event, $this->getOption());
        }
        DBHelper::save($this);
        return true;
    }

    public function emptyEvent()
    {
        $this->event = [];
    }

    /**
     * @param $_id
     * @param string $_type
     */
    public function addEvent($_id, $_type = 'cmd')
    {
        $event = $this->getEvent();
        if (!is_array($event)) {
            $event = [];
        }
        $id = '';
        if ($_type == 'cmd') {
            $id = str_replace('#', '', $_id);
        }
        if (!in_array('#' . $id . '#', $event)) {
            $event[] = '#' . $id . '#';
        }
        $this->setEvent($event);
    }

    /**
     * @return bool|mixed|null
     */
    public function getEvent()
    {
        return Utils::isJson($this->event, []);
    }

    /**
     * @param $_event
     * @return $this
     */
    public function setEvent($_event)
    {
        $event = json_encode($_event, JSON_UNESCAPED_UNICODE);
        $this->updateChangeState($this->event, $_event);
        $this->event = $event;
        return $this;
    }
}