Beispiel #1
0
 def toFile(self, filename, config, exclusive=True):
     """
     CHANGELOG:
     objconfig v1.1: use portalocker to establish an exclusive lock if given
     
     Following is the header as given in zend-config::
     
         /**
          * toFile(): defined by Writer interface.
          *
          * @see    WriterInterface::toFile()
          * @param  string  $filename
          * @param  mixed   $config
          * @param  bool $exclusiveLock
          * @return void
          * @throws Exception\InvalidArgumentException
          * @throws Exception\RuntimeException
          */
     """
     
     if not ('toArray' in dir(config) and inspect.ismethod(config.toArray)) and not isinstance(config, dict):
         raise InvalidArgumentException("AbstractWriter: toFile() expects a dictionary or implementing toArray")
     
     if not filename:
         raise InvalidArgumentException("AbstractWriter: No Filename Specified")
     
     try:
         with open(filename, "w") as file:
             if exclusive:
                 portalocker.lock(file, portalocker.LOCK_EX)
             file.write(self.toString(config))
     except Exception as e:
         raise RuntimeException("AbstractWriter: Error Writing to \"%s\": %s" % (filename, e))
Beispiel #2
0
    def setTokens(self, tokens):
        r"""
        Following is the class documentation as given in zend-config::
        
            /**
             * Set token registry.
             *
             * @param  array|Config|Traversable  $tokens  Associative array of TOKEN => value
             *                                            to replace it with
             * @return Token
             * @throws Exception\InvalidArgumentException
             */
        """

        if tokens is not None:
            self.tokens = tokens.toArray() if 'toArray' in dir(
                tokens) and inspect.ismethod(tokens.toArray) else tokens
        else:
            self.tokens = {}

        if not isinstance(self.tokens, dict):
            self.tokens = {}
            try:
                for key, val in tokens.items():
                    self.tokens[key] = val
            except Exception:
                raise InvalidArgumentException(
                    "Token: Cannot Use %s As Token Registry" % type(tokens))

        self.map = None
        return self
Beispiel #3
0
 def toString(self, config):
     r"""
     Following is the header as given in zend-config::
     
         /**
          * fromString(): defined by Reader interface.
          *
          * @param  string $string
          * @return array|bool
          * @throws Exception\RuntimeException
          */
     """
     
     if not ('toArray' in dir(config) and inspect.ismethod(config.toArray)) and not isinstance(config, dict):
         raise InvalidArgumentException("AbstractWriter: toString() expects a dictionary or implementing toArray")
     
     return self.processConfig(config)
Beispiel #4
0
    def __delattr__(self, attribute):
        r"""
        Following is the header as given in zend-config::
        
            /**
             * unset() overloading
             *
             * @param  string $name
             * @return void
             * @throws Exception\InvalidArgumentException
             */
        """

        if self.__allowModifications:
            del self.__data[attribute]
        else:
            raise InvalidArgumentException(
                "Config: __delattr__ config is read only")
Beispiel #5
0
    def doProcess(self, value, replacements):
        r"""
        CHANGELOG:
        objconfig v1.1: edit value in place rather than return copy - 3/2/2017
        
        Following is the class documentation as given in zend-config::
        
            /**
             * Applies replacement map to the given value by modifying the value itself
             *
             * @param mixed $value
             * @param array $replacements
             *
             * @return mixed
             *
             * @throws Exception\InvalidArgumentException if the provided value is a read-only {@see Config}
             */
        """

        if isinstance(value, Config):
            if value.isReadOnly():
                raise InvalidArgumentException(
                    "Token: Cannot Process Config Because It Is Read-Only")
            for key, val in value:
                value.__dict__[key] = self.doProcess(val, replacements)
            return value
        elif isinstance(value, dict):
            for key, val in value.items():
                value[key] = self.doProcess(val, replacements)
            return value
        else:
            stringval = str(value)
            for fr, to in self.map.items():
                stringval = stringval.replace(fr, to)
            r"""
            if ($changedVal !== $stringVal) {
                return $changedVal;
            }
            """  # -- ?

            return stringval
Beispiel #6
0
    def addToken(self, token, value):
        r"""
        Following is the class documentation as given in zend-config::
        
            /**
             * Add new token.
             *
             * @param  string $token
             * @param  mixed $value
             * @return Token
             * @throws Exception\InvalidArgumentException
             */
        """

        if not isinstance(str(token), str):
            raise InvalidArgumentException(
                "Token: Cannot Use %s As Token Name" % type(token))

        self.tokens[str(token)] = value
        self.map = None
        return self
Beispiel #7
0
    def __init__(self, array, allowModifications=False):
        r"""
        Notes:
            array is expected to be instance of dict
            OR implement toArray() method
        
        Following is the header as given in zend-config::
        
            /**
             * Constructor.
             *
             * Data is read-only unless $allowModifications is set to true
             * on construction.
             *
             * @param  array   $array
             * @param  bool $allowModifications
             */
        """
        r"""
        Following is the header as given in zend-config::
        
            /**
             * Whether modifications to configuration data are allowed.
             *
             * @var bool
             */
        """
        self.__allowModifications = allowModifications

        r"""
        protected $skipNextIteration;
        
        Notes:
            Not necessary, items() is an up-to-date view
            
        Following is the header as given in zend-config::
        
            /**
             * Used when unsetting values during iteration to ensure we do not skip
             * the next element.
             *
             * @var bool
             */
        """  # -- unnecessary
        r"""
        Following is the header as given in zend-config::
        
            /**
             * Data within the configuration.
             *
             * @var array
             */
        """
        self.__data = {}

        try:
            for key, value in array.items():
                if 'items' in dir(value):
                    self.__data[key] = Config(
                        value, allowModifications=self.__allowModifications)
                elif 'toArray' in dir(value) and inspect.ismethod(
                        value.toArray):
                    self.__data[key] = Config(
                        value.toArray(),
                        allowModifications=self.__allowModifications)
                else:
                    self.__data[key] = value
        except AttributeError:
            raise InvalidArgumentException(
                "Config: __init__ passed array doesn't implement key, value : items()"
            )