Art-of-WiFi / UniFi-API-client

A PHP API client class to interact with Ubiquiti's UniFi Controller API
MIT License
1.09k stars 217 forks source link

Added traffic rule functions #216

Open nelis249 opened 4 months ago

nelis249 commented 4 months ago

I'm new to github pull/request stuff and couldn't figure out how to do it. Here's some functions I added to the class to support getting traffic rules with enabling and disabling. Feel free to add.

/**
     * Fetch traffic rules
     *
     * @returns array of traffic rule objects
     */
    public function list_trafficrules()
    {
        return $this->fetch_results('/v2/api/site/' . $this->site . '/trafficrules');
    }

    /**
     * Enable a specific traffic rule
     *
     * @param string $ruleDesc - specify the rule 'note' text to identify the rule
     *
     * @return bool true on success
     */
    public function enable_trafficrule(string $ruleDesc)
    {
        $rules = $this->list_trafficrules();
        foreach($rules as $rule) {
            if(strtoupper($rule->description) != strtoupper($ruleDesc)) { continue; }

            $rule->enabled = true;
            $this->set_trafficrule($rule);
            return true;
        }
        return false;
    }

    /**
     * Disable a specific traffic rule
     *
     * @param string $ruleDesc - specify the rule 'note' text to identify the rule
     *
     * @return bool true on success
     */
    public function disable_trafficrule($ruleDesc)
    {
        $rules = $this->list_trafficrules();
        foreach($rules as $rule) {
            if(strtoupper($rule->description) != strtoupper($ruleDesc)) { continue; }

            $rule->enabled = false;
            $this->set_trafficrule($rule);
            return true;
        }
        return false;
    }

    /**
     * Set a traffic rule configuration.
     *
     * In order for this to work the PUT literally has to put the entire rule object as pulled from
     * list_trafficrules with modified properties Other wrapper functions should modify the rule then send
     * it to this function to 'commit'
     *
     * @return array|bool returns results
     */
    private function set_trafficrule($ruleObj)
    {
        $this->curl_method = 'PUT';

        $payload = $ruleObj;

        return $this->fetch_results('/v2/api/site/' . $this->site . '/trafficrules/' . trim($ruleObj->_id), $payload);
    }
malle-pietje commented 4 months ago

Thanks, will look into this shortly. Slightly changed the formatting of the code to improve readability.