BaseModel.php 14.9 KB
Newer Older
1
<?php
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
/**
*    Copyright (C) 2015 Deciso B.V.
*
*    All rights reserved.
*
*    Redistribution and use in source and binary forms, with or without
*    modification, are permitted provided that the following conditions are met:
*
*    1. Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*    2. Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in the
*       documentation and/or other materials provided with the distribution.
*
*    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
*    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
*    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
*    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
*    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
*    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
*    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
*    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*    POSSIBILITY OF SUCH DAMAGE.
*
28 29 30 31 32
*/

namespace OPNsense\Base;

use OPNsense\Base\FieldTypes\ArrayField;
33
use OPNsense\Base\FieldTypes\ContainerField;
34 35
use OPNsense\Core\Config;

36 37 38 39 40 41 42 43 44
/**
 * Class BaseModel implements base model to bind config and definition to object.
 * Derive from this class to create usable models.
 * Every model definition should include a class (derived from this) and a xml model to define the data (model.xml)
 *
 * See the Sample model for a full implementation.
 *
 * @package OPNsense\Base
 */
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
abstract class BaseModel
{
    /**
     * @var null|BaseField internal model data structure, should contain Field type objects
     */
    private $internalData = null;

    /**
     * place where the real data in the config.xml should live
     * @var string
     */
    private $internal_mountpoint = '';


    /**
     * If the model needs a custom initializer, override this init() method
     * Default behaviour is to do nothing in this init.
     */
    protected function init()
    {
        return ;
    }

    /**
69 70 71 72
     * parse model and config xml to object model using types in FieldTypes
     * @param SimpleXMLElement $xml model xml data (from items section)
     * @param SimpleXMLElement $config_data (current) config data
     * @param BaseField $internal_data output structure using FieldTypes,rootnode is internalData
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
     * @throws ModelException parse error
     */
    private function parseXml($xml, &$config_data, &$internal_data)
    {
        foreach ($xml->children() as $xmlNode) {
            $tagName = $xmlNode->getName();
            // every item results in a Field type object, the first step is to determine which object to create
            // based on the input model spec
            $fieldObject = null ;
            $classname = "OPNsense\\Base\\FieldTypes\\".$xmlNode->attributes()["type"];
            if (class_exists($classname)) {
                // construct field type object
                $field_rfcls = new \ReflectionClass($classname);
                if (!$field_rfcls->getParentClass()->name == 'OPNsense\Base\FieldTypes\BaseField') {
                    // class found, but of wrong type. raise an exception.
                    throw new ModelException("class ".$field_rfcls->name." of wrong type in model definition");
                }
            } else {
                // no type defined, so this must be a standard container (without content)
                $field_rfcls = new \ReflectionClass('OPNsense\Base\FieldTypes\ContainerField');
            }

            // generate full object name ( section.section.field syntax ) and create new Field
            if ($internal_data->__reference == "") {
                $new_ref = $tagName;
            } else {
                $new_ref = $internal_data->__reference . "." . $tagName;
            }
101
            $fieldObject = $field_rfcls->newInstance($new_ref, $tagName);
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

            // now add content to this model (recursive)
            if ($fieldObject->isContainer() == false) {
                $internal_data->addChildNode($tagName, $fieldObject);
                if ($xmlNode->count() > 0) {
                    // if fieldtype contains properties, try to call the setters
                    foreach ($xmlNode->children() as $fieldMethod) {
                        $param_value = $fieldMethod->__toString() ;
                        $method_name = "set".$fieldMethod->getName();
                        if ($field_rfcls->hasMethod($method_name)) {
                            $fieldObject->$method_name($param_value);
                        }
                    }
                }
                if ($config_data != null && isset($config_data->$tagName)) {
                    // set field content from config (if available)
                    $fieldObject->setValue($config_data->$tagName->__toString());
                }

            } else {
                // add new child node container, always try to pass config data
                if ($config_data != null && isset($config_data->$tagName)) {
                    $config_section_data = $config_data->$tagName;
                } else {
                    $config_section_data = null ;
                }

                if ($fieldObject instanceof ArrayField) {
                    // handle Array types, recurring items
                    if ($config_section_data != null) {
                        $counter = 0 ;
                        foreach ($config_section_data as $conf_section) {
134
                            // iterate array items from config data
135
                            $child_node = new ContainerField($fieldObject->__reference . "." . ($counter++), $tagName);
136 137 138 139
                            $this->parseXml($xmlNode, $conf_section, $child_node);
                            $fieldObject->addChildNode(null, $child_node);
                        }
                    } else {
140
                        // There's no content in config.xml for this array node.
141 142
                        $child_node = new ContainerField($fieldObject->__reference . ".0", $tagName);
                        $child_node->setInternalIsVirtual();
143 144 145 146
                        $this->parseXml($xmlNode, $config_section_data, $child_node);
                        $fieldObject->addChildNode(null, $child_node);
                    }
                } else {
147
                    // All other node types (Text,Email,...)
148 149 150
                    $this->parseXml($xmlNode, $config_section_data, $fieldObject);
                }

151
                // add object as child to this node
152 153 154 155 156 157 158 159 160 161 162 163 164 165
                $internal_data->addChildNode($xmlNode->getName(), $fieldObject);
            }

        }

    }

    /**
     * Construct new model type, using it's own xml template
     * @throws ModelException if the model xml is not found or invalid
     */
    public function __construct()
    {
        // setup config handle to singleton config singleton
166
        $internalConfigHandle = Config::getInstance();
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184

        // init new root node, all details are linked to this
        $this->internalData = new FieldTypes\ContainerField();

        // determine our caller's filename and try to find the model definition xml
        // throw error on failure
        $class_info = new \ReflectionClass($this);
        $model_filename = substr($class_info->getFileName(), 0, strlen($class_info->getFileName())-3) . "xml" ;
        if (!file_exists($model_filename)) {
            throw new ModelException('model xml '.$model_filename.' missing') ;
        }
        $model_xml = simplexml_load_file($model_filename);
        if ($model_xml === false) {
            throw new ModelException('model xml '.$model_filename.' not valid') ;
        }
        if ($model_xml->getName() != "model") {
            throw new ModelException('model xml '.$model_filename.' seems to be of wrong type') ;
        }
185
        $this->internal_mountpoint = $model_xml->mount;
186 187 188

        // use an xpath expression to find the root of our model in the config.xml file
        // if found, convert the data to a simple structure (or create an empty array)
189
        $tmp_config_data = $internalConfigHandle->xpath($model_xml->mount);
190 191 192 193 194 195 196 197 198
        if ($tmp_config_data->length > 0) {
            $config_array = simplexml_import_dom($tmp_config_data->item(0)) ;
        } else {
            $config_array = array();
        }

        // We've loaded the model template, now let's parse it into this object
        $this->parseXml($model_xml->items, $config_array, $this->internalData) ;

199 200
        // trigger post loading event
        $this->internalData->eventPostLoading();
201 202 203 204 205 206 207

        // call Model initializer
        $this->init();
    }

    /**
     * reflect getter to internalData (ContainerField)
208
     * @param string $name property name
209 210 211 212 213 214 215 216 217
     * @return mixed
     */
    public function __get($name)
    {
        return $this->internalData->$name;
    }

    /**
     * reflect setter to internalData (ContainerField)
218 219
     * @param string $name property name
     * @param string $value property value
220 221 222 223 224 225
     */
    public function __set($name, $value)
    {
        $this->internalData->$name = $value ;
    }

226 227 228 229 230 231 232 233 234
    /**
     * forward to root node's getFlatNodes
     * @return array all children
     */
    public function getFlatNodes()
    {
        return $this->internalData->getFlatNodes();
    }

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    /**
     * validate full model using all fields and data in a single (1 deep) array
     */
    public function performValidation()
    {
        // create a Phalcon validator and collect all model validations
        $validation = new \Phalcon\Validation();
        $validation_data = array();
        $all_nodes = $this->internalData->getFlatNodes();

        foreach ($all_nodes as $key => $node) {
            $node_validators = $node->getValidators();
            foreach ($node_validators as $item_validator) {
                $validation->add($key, $item_validator);
            }
            if (count($node_validators) > 0) {
                $validation_data[$key] = $node->__toString();
            }
        }

        if (count($validation_data) > 0) {
            $messages = $validation->validate($validation_data);
        } else {
            $messages = new \Phalcon\Validation\Message\Group();
        }

        return $messages;
    }

    /**
     * render xml document from model including all parent nodes.
     * (parent nodes are included to ease testing)
     *
     * @return \SimpleXMLElement xml representation of the model
     */
    public function toXML()
    {
        // calculate root node from mountpoint
        $xml_root_node = "";
        $str_parts = explode("/", str_replace("//", "/", $this->internal_mountpoint));
        for ($i=0; $i < count($str_parts); $i++) {
            if ($str_parts[$i] != "") {
                $xml_root_node .= "<".$str_parts[$i].">";
            }
        }
        for ($i=count($str_parts)-1; $i >= 0; $i--) {
            if ($str_parts[$i] != "") {
                $xml_root_node .= "</".$str_parts[$i].">";
            }
        }

        $xml = new \SimpleXMLElement($xml_root_node);
        $this->internalData->addToXMLNode($xml->xpath($this->internal_mountpoint)[0]);

        return $xml;

    }

    /**
     * serialize model singleton to config object
     */
    private function internalSerializeToConfig()
    {
        // setup config handle to singleton config singleton
        $internalConfigHandle = Config::getInstance();
        $config_xml = $internalConfigHandle->object();

        // serialize this model's data to xml
        $data_xml = $this->toXML();

        // Locate source node (in theory this must return a valid result, delivered by toXML).
        // Because toXML delivers the actual xml including the full path, we need to find the root of our data.
        $source_node = $data_xml->xpath($this->internal_mountpoint);

        // find parent of mountpoint (create if it doesn't exists)
        $target_node = $config_xml;
        $str_parts = explode("/", str_replace("//", "/", $this->internal_mountpoint));
        for ($i=0; $i < count($str_parts)-1; $i++) {
            if ($str_parts[$i] != "") {
                if (count($target_node->xpath($str_parts[$i])) == 0) {
                    $target_node = $target_node->addChild($str_parts[$i]);
                } else {
                    $target_node = $target_node->xpath($str_parts[$i])[0];
                }

            }
        }

        // copy model data into config
        $toDom = dom_import_simplexml($target_node);
        $fromDom = dom_import_simplexml($source_node[0]);

        // remove old model data and write new
        foreach ($toDom->getElementsByTagName($fromDom->nodeName) as $oldNode) {
            $toDom->removeChild($oldNode);
        }
        $toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));
    }

    /**
     * validate model and serialize data to config singleton object.
     *
     * @param bool $disable_validation skip validation, be careful to use this!
     * @throws \Phalcon\Validation\Exception validation errors
     */
    public function serializeToConfig($disable_validation = false)
    {
        if ($disable_validation == false) {
            // perform validation, collect all messages and raise exception
            $messages = $this->performValidation();
            if ($messages->count() > 0) {
                $exception_msg = "";
                foreach ($messages as $msg) {
                    $exception_msg .= "[".$msg-> getField()."] ".$msg->getMessage()."\n";
                }
                throw new \Phalcon\Validation\Exception($exception_msg);
            }
        }
        $this->internalSerializeToConfig();
    }
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

    /**
     * find node by reference starting at the root node
     * @param string $reference node reference (point separated "node.subnode.subsubnode")
     * @return BaseField|null field node by reference (or null if not found)
     */
    public function getNodeByReference($reference)
    {
        $parts = explode(".", $reference);

        $node = $this->internalData;
        while (count($parts)>0) {
            $childName = array_shift($parts);
            if (array_key_exists($childName, $node->getChildren())) {
                $node = $node->getChildren()[$childName];
            } else {
                return null;
            }

        }
        return $node;
    }

    /**
     * set node value by name (if reference exists)
     * @param string $reference node reference (point separated "node.subnode.subsubnode")
     * @param string $value
     * @return bool value saved yes/no
     */
    public function setNodeByReference($reference, $value)
    {
        $node =$this->getNodeByReference($reference);
        if ($node != null) {
            $node->setValue($value);
            return true;
        } else {
            return false;
        }
    }
394
}