Exemple #1
0
    def __init__(self, key, sourceId=None, sourceKey=None):
        InvalidArgumentException.__init__(self);
        self.__key = key;
        self.__sourceKey = sourceKey;
        self.__sourceId = sourceId;

        self.updateRepr();
Exemple #2
0
    def process(self, container):
        assert isinstance(container, ContainerBuilder)

        if not container.hasDefinition('event_dispatcher'):
            return

        definition = container.getDefinition('event_dispatcher')

        listeners = container.findTaggedServiceIds('kernel.event_listener')
        for identifier, events in listeners.items():
            for event in events:
                if 'priority' in event:
                    priority = event['priority']
                else:
                    priority = 0

                if 'event' not in event:
                    raise InvalidArgumentException(
                        'Service "{0}" must define the "event" attribute on'
                        '"kernel.event_listener" tags.'.format(identifier))

                if 'method' not in event:
                    parts = event['event'].split(".")
                    method = ""
                    for part in parts:
                        method += part.title().replace('_', '')
                    event['method'] = 'on' + method

                definition.addMethodCall(
                    'addListenerService',
                    [event['event'], [identifier, event['method']], priority])

        subscribers = container.findTaggedServiceIds('kernel.event_subscriber')
        for identifier, events in subscribers.items():
            # We must assume that the class value has been correctly filled,
            # even if the service is created by a factory
            qualClassName = container.getDefinition(identifier).getClass()

            classType = ClassLoader.load(qualClassName)

            if not issubclass(classType, EventSubscriberInterface):
                raise InvalidArgumentException(
                    'Service "{0}" must implement interface "{1}".'
                    ''.format(identifier, repr(EventSubscriberInterface)))

            definition.addMethodCall('addSubscriberService',
                                     [identifier, qualClassName])
Exemple #3
0
    def __sanitizeRequirement(self, key, regex):

        if not isinstance(regex, String):
            raise InvalidArgumentException(
                'Routing requirement for "{0}" must be a string.'.format(key))

        if regex and regex.startswith('^'):
            regex = regex[1:]
            # returns False for a single character

        if regex.endswith('$'):
            regex = regex[:-1]

        if not regex:
            raise InvalidArgumentException(
                'Routing requirement for "{0}" cannot be empty.'.format(key))

        return regex
Exemple #4
0
    def parse(self, controller):
        """Converts a short notation a:b:c to a class.method.

        @param: string controller A short notation controller (a:b:c)

        @return: string A string with class.method

        @raise InvalidArgumentException: when the specified bundle is not enabled
                                         or the controller cannot be found
        """
        parts = controller.split(':')
        if (3 != len(parts)):
            raise InvalidArgumentException(
                'The "{0}" controller is not a valid a:b:c controller string.'
                ''.format(controller))

        bundle, controller, action = parts
        controller = controller.replace('/', '.')
        bundles = list()

        # this raise an exception if there is no such bundle:
        for b in self._kernel.getBundle(bundle, False):
            test = b.getNamespace(
            ) + '.controller.' + controller + 'Controller'
            if ReflectionClass(test).exists():
                return test + '::' + action + 'Action'

            bundles.append(b.getName())
            msg = (
                'Unable to find controller "{0}:{1}" - class "{2}" does not '
                'exist.'.format(
                    bundle,
                    controller,
                    test,
                ))

        if (len(bundles) > 1):
            msg = ('Unable to find controller "{0}:{1}" in bundles {2}.'
                   ''.format(bundle, controller, ', '.join(bundles)))

        raise InvalidArgumentException(msg)
Exemple #5
0
    def values(self, values):
        assert isinstance(values, list);

        values = Array.uniq(values);

        if (len(values) <= 1) :
            raise InvalidArgumentException('.values() must be called with at least two distinct values.');


        self.__values = values;

        return self;
Exemple #6
0
    def getBundle(self, name, first=True):
        if name not in self._bundleMap:
            raise InvalidArgumentException(
                'Bundle "{0}" does not exist or it is not enabled. Maybe you '
                'forgot to add it in the registerBundles() method of your {1} '
                'file?'.format(name,
                               ReflectionObject(self).getFileName()))

        if first is True:
            return self._bundleMap[name][0]

        return self._bundleMap[name]
Exemple #7
0
    def addChild(self, node):
        """Adds a child node.

        @param child: NodeInterface The child node to add

        @raise InvalidArgumentException: when the child node has no name
        @raise InvalidArgumentException: when the child node's name
            is not unique
        """
        assert isinstance(node, NodeInterface)

        name = node.getName()

        if not name:
            raise InvalidArgumentException('Child nodes must be named.')

        if name in self._children:
            raise InvalidArgumentException(
                'A child node named "{0}" already exists.'
                ''.format(name))

        self._children[name] = node
Exemple #8
0
    def locate(self, name, currentPath=None, first=True):
        """Returns a full path for a given file name.

        @param name: mixed The file name to locate
        @param currentPath: string The current path
        @param first: boolean Whether to return the first occurrence 
                      or an array of filenames

        @return: string|list The full path to the file|A list of file paths

        @raise InvalidArgumentException: When file is not found

        """
        if self.__isAbsolutePath(name):
            if not os.path.exists(name):
                raise InvalidArgumentException(
                    'The file "{0}" does not exist.'.format(name))
            return name

        filepaths = list()

        paths = []
        if currentPath:
            paths.append(currentPath)
        paths.extend(self._paths)

        for path in paths:
            filename = os.path.join(path, name)
            if os.path.exists(filename):
                if first:
                    return filename
                filepaths.append(filename)

        if not filepaths:
            raise InvalidArgumentException(
                'The file "{0}" does not exist (in: {1}).'
                ''.format(name, ", ".join(paths)))

        return Array.uniq(filepaths)
Exemple #9
0
    def getArgument(self, key):
        """Get argument by key.

        @param key: string Key

        @return: mixed Contents of array key.

        @raise InvalidArgumentException: If key is not found.
        """
        if self.hasArgument(key):
            return self._arguments[key]

        raise InvalidArgumentException('{0} not found in {1}'.format(
            key, self.getName()))
Exemple #10
0
    def _createController(self, controller):
        """Returns a callable for the given controller.

        @param string controller A Controller string

        @return callable A PYTHON callable

        @raise InvalidArgumentException

        """

        if '::' not in controller:
            raise InvalidArgumentException(
                'Unable to find controller "{0}".'.format(controller))

        className, method = controller.split('::', 2)

        r = ReflectionClass(className)

        if (not r.exists()):
            raise InvalidArgumentException(
                'Class "{0}" does not exist.'.format(className))

        return (r.newInstance(), method)
Exemple #11
0
    def setDefaultValue(self, value):
        """Sets the default value of this node.

        @param value: dict

        @raise InvalidArgumentException: if the default value is not an array
        """
        if isinstance(value, list):
            value = Array.toDict(value)
        if not isinstance(value, dict):
            raise InvalidArgumentException(
                '{0}: the default value of an array node has to be an array.'
                ''.format(self.getPath()))

        self._defaultValue = value
Exemple #12
0
    def setOption(self, key, value):
        """Sets an option.

        @param: string key   The key
        @param mixed  value The value

        @raise InvalidArgumentException

        """

        if key not in self._options:
            raise InvalidArgumentException(
                'The Router does not support the "{0}" option.'.format(key))

        self._options[key] = value
Exemple #13
0
    def getOption(self, key):
        """Gets an option value.

        @param: string key The key

        @return mixed The value

        @raise InvalidArgumentException

        """

        if key not in self._options:
            raise InvalidArgumentException(
                'The Router does not support the "{0}" option.'.format(key))

        return self._options[key]
Exemple #14
0
    def __init__(self, name, parent=None, values=None):
        if values is None:
            values = list()
        assert isinstance(values, list)
        if parent:
            assert isinstance(parent, NodeInterface)

        self.__values = None

        values = Array.uniq(values)
        if (len(values) <= 1):
            raise InvalidArgumentException(
                'values must contain at least two distinct elements.')

        ScalarNode.__init__(self, name, parent)
        self.__values = values
Exemple #15
0
    def getController(self, request):
        """Returns the Controller instance associated with a Request.

        As several resolvers can exist for a single application, a resolver must
        return False when it is not able to determine the controller.

        The resolver must only raise an exception when it should be able to load
        controller but cannot because of some errors made by the developer.

        @param Request request A ArgvInput instance

        @return mixed|Boolean A PYTHON callable representing the Controller,
                              or False if this resolver is not able to determine
                             the controller:

        @raise InvalidArgumentException|\LogicException If the controller can't be found

        @api

        """
        assert isinstance(request, Request)

        controller = request.attributes.get('_controller')
        if (not controller):
            return False

        if Tool.isCallable(controller):
            return controller

        if not isinstance(controller, String):
            return False

        if ':' not in controller:
            r = ReflectionClass(controller)
            if r.exists():
                instance = r.newInstance()
                if Tool.isCallable(instance):
                    return instance

        controller, method = self._createController(controller)

        if not hasattr(controller, method):
            raise InvalidArgumentException(
                'Method "{0}.{1}" does not exist.'.format(
                    ReflectionObject(controller).getName(), method))

        return getattr(controller, method)
Exemple #16
0
    def getStyle(self, name):
        """Gets style options from style with specified name.:

        @param string name

        @return OutputFormatterStyleInterface

        @raise InvalidArgumentException When style isn't defined

        @api

        """

        if (not self.hasStyle(name)):
            raise InvalidArgumentException('Undefined style: ' + name)

        return self.__styles[str(name).lower()]
Exemple #17
0
    def setStatusCode(self, code, text = None):
        """Sets the response status code.

        @param integer code CLI status code
        @param mixed   text CLI status text

        If the status text is None it will be automatically populated for the
        known status codes and left empty otherwise.

        @return Response

        @raise InvalidArgumentException When the CLI status code is not valid

        @api

        """
        code = int(code);
        self._statusCode = code;
        if self.isInvalid() :
            self._statusCode = 255;
            raise InvalidArgumentException(
                'The CLI status code "{0}" is not valid.'.format(code)
            );


        if (None is text) :
            if code in self.statusTexts:
                self.statusText = self.statusTexts[code];
            else:
                self.statusText = '';

            return self;


        if (False is text) :
            self.statusText = '';

            return self;


        self.statusText = text;

        return self;
Exemple #18
0
    def setOption(self, option):
        """Sets some specific style option.:

        @param string option The option name

        @raise InvalidArgumentException When the option name isn't defined

        @api

        """

        option = str(option)

        if option not in self.__availableOptions:
            raise InvalidArgumentException(
                'Invalid option specified: "{0}". Expected one of ({1})'
                ''.format(option, ', '.join(self.__availableOptions.keys())))

        if self.__availableOptions[option] not in self.__options:
            self.__options.append(self.__availableOptions[option])
Exemple #19
0
    def min(self, minValue):
        """Ensures that the value is bigger than the given reference.

        @param mixed minValue

        @return NumericNodeDefinition

        @raise InvalidArgumentException when the constraint is inconsistent

        """

        if (self._max and self._max < minValue) :
            raise InvalidArgumentException(
                'You cannot define a min({0}) as you already have a max({1})'
                ''.format(minValue, self._max)
            );

        self._min = minValue;

        return self;
Exemple #20
0
    def unsetOption(self, option):
        """Unsets some specific style option.:

        @param string option The option name

        @raise InvalidArgumentException When the option name isn't defined


        """

        if option not in self.__availableOptions:
            raise InvalidArgumentException(
                'Invalid option specified: "{0}". Expected one of ({1})'
                ''.format(option, ', '.join(self.__availableOptions.keys())))

        try:
            pos = self.__options.index(self.__availableOptions[option])
        except ValueError:
            pass
        else:
            del self.__options[pos]
Exemple #21
0
    def load(self, filename, resource_type=None):
        """Loads a Yaml file.

        @param: string      file A Yaml file path
        @param string|None resource_type The resource type

        @return RouteCollection A RouteCollection instance

        @raise InvalidArgumentException When a route can't be parsed because YAML is invalid

        @api

        """

        path = self._locator.locate(filename)

        configs = self._parseFile(path)

        collection = RouteCollection()
        collection.addResource(FileResource(path))

        # empty file
        if (None is configs):
            return collection

        # not a OrderedDict
        if not isinstance(configs, OrderedDict):
            raise InvalidArgumentException(
                'The file "{0}" must contain a Json object.'.format(path))

        for name, config in configs.items():

            self._validate(config, name, path)

            if 'resource' in config:
                self._parseImport(collection, config, path, filename)
            else:
                self._parseRoute(collection, name, config, path)

        return collection
Exemple #22
0
    def _createController(self, controller):
        """Returns a callable for the given controller.

        @param: string controller A Controller string

        @return: mixed A PHP callable

        @raise LogicException:           When the name could not be parsed
        @raise InvalidArgumentException: When the controller class does(, not exist):
        """

        if '::' not in controller:
            count = controller.count(':')
            if (2 == count):
                # controller in the a:b:c notation then
                controller = self._parser.parse(controller)
            elif (1 == count):
                # controller in the service:method notation
                (service, method) = controller.split(':', 2)

                return [self._container.get(service), method]
            else:
                raise LogicException(
                    'Unable to parse the controller name "{0}".'
                    ''.format(controller))

        (className, method) = controller.split('::', 2)

        r = ReflectionClass(className)
        if not r.exists():
            raise InvalidArgumentException(
                'Class "{0}" does not exist.'.format(className))

        controller = r.newInstance()
        if (isinstance(controller, ContainerAwareInterface)):
            controller.setContainer(self._container)

        return [controller, method]
Exemple #23
0
    def _parseFile(self, filename):
        """Parses a JSON file.

        @param filename: string The path file

        @return: dict The file content

        @raise InvalidArgumentException: When JSON file is not valid
        """
        f = open(filename)
        s = f.read().strip()
        f.close()
        del f

        if not s:
            return None

        try:
            result = JSONDecoderOrderedDict().decode(s)
        except ValueError as e:
            raise InvalidArgumentException(e)

        return result
Exemple #24
0
    def setOptions(self, options):
        """Sets options.

        Available options:

             cache_dir:     The cache directory (or None to disable caching)
             debug:         Whether to enable debugging or not (False by default)
             resource_type: Type hint for the main resource (optional)

        @param: array options An array of options

        @raise InvalidArgumentException When unsupported option is provided

        """
        assert isinstance(options, dict)

        self._options = {
            'cache_dir': None,
            'debug': False,
            'resource_type': None,
            'request_matcher_class':
            "pymfony.component.console_routing.matcher.RequestMatcher",
            'routes_cache_class': "ProjectRouteCollection",
        }

        # check option names and live merge, if errors are encountered Exception will be thrown:
        invalid = list()
        for key, value in options.items():
            if key in self._options:
                self._options[key] = value
            else:
                invalid.append(key)

        if (invalid):
            raise InvalidArgumentException(
                'The Router does not support the following options: "{0}".'
                ''.format('\', \''.join(invalid)))
Exemple #25
0
    def addListenerService(self, eventName, callback, priority=0):
        """Adds a service as event listener

        @param eventName: string Event for which the listener is added.
        @param callback: list The service ID of the listener service &
                         the method name that has to be called
        @param priority: integer The higher this value, the earlier an event
                         listener will be triggered in the chain.
                         Defaults to 0.

        @raise InvalidArgumentException: When the callback is not valid.
        """
        if not isinstance(callback, list) or len(callback) != 2:
            raise InvalidArgumentException(
                'Expected an array("service", "method") argument')

        if eventName not in self.__listenerIds:
            self.__listenerIds[eventName] = list()

        self.__listenerIds[eventName].append([
            callback[0],
            callback[1],
            priority,
        ])
Exemple #26
0
    def __init__(self, name, parent=None):
        """Constructor.

        @param name: string The name of the node
        @param parent: NodeInterface The parent of this node

        @raise InvalidArgumentException: if the name contains a period.
        """
        assert isinstance(name, String)
        if parent is not None:
            assert isinstance(parent, NodeInterface)

        self._attributes = OrderedDict()

        self._name = name
        self._parent = parent
        self._normalizationClosures = list()
        self._finalValidationClosures = list()
        self._allowOverwrite = True
        self._required = False
        self._equivalentValues = list()

        if '.' in name:
            raise InvalidArgumentException('The name must not contain ".".')
Exemple #27
0
    def __init__(self, identifier, sourceId=None):
        InvalidArgumentException.__init__(self);
        self.__id = identifier;
        self.__sourceId = sourceId;

        self.updateRepr();
Exemple #28
0
    def _validate(self, config, name, path):
        """Validates the route configuration.

        @param: dict  config A resource config
        @param string name   The config key
        @param string path   The loaded file path

        @raise InvalidArgumentException If one of the provided config keys is not supported,
                                          something is missing or the combination is nonsense

        """

        if not isinstance(config, dict):
            raise InvalidArgumentException(
                'The definition of "{0}" in "{1}" must be a Json object.'
                ''.format(name, path))

        extraKeys = Array.diff(config.keys(), self.__availableKeys)
        if (extraKeys):
            raise InvalidArgumentException(
                'The routing file "{0}" contains unsupported keys for "{1}": '
                '"{2}". Expected one of: "{3}".'.format(
                    path,
                    name,
                    '", "'.join(extraKeys),
                    '", "'.join(self.__availableKeys),
                ))

        if 'resource' in config and 'path' in config:
            raise InvalidArgumentException(
                'The routing file "{0}" must not specify both the "resource" '
                'key and the "path" key for "{1}". Choose between an import '
                'and a route definition.'.format(path, name))

        if 'resource' in config and 'description' in config:
            raise InvalidArgumentException(
                'The routing file "{0}" must not specify both the "resource" '
                'key and the "description" key for "{1}". Choose between an '
                'import and a route definition.'.format(path, name))

        if 'resource' not in config and 'type' in config:
            raise InvalidArgumentException(
                'The "type" key for the route definition "{0}" in "{1}" is '
                'unsupported. It is only available for imports in combination '
                'with the "resource" key.'.format(name, path))

        if 'resource' not in config and 'path' not in config:
            raise InvalidArgumentException(
                'You must define a "path" for the route "{0}" in file "{1}".'
                ''.format(name, path))

        if 'path' in config and not config['path']:
            raise InvalidArgumentException(
                'The "path" for the route "{0}" in file "{1}" cannot be empty.'
                ''.format(name, path))

        if 'definition' in config:
            if 'arguments' in config['definition']:
                if not isinstance(config['definition']['arguments'],
                                  OrderedDict):
                    raise InvalidArgumentException(
                        'The definition.arguments key should be a JSON object '
                        'in route "{0}" in file "{1}".'
                        ''.format(name, path))
            if 'options' in config['definition']:
                if not isinstance(config['definition']['options'], dict):
                    raise InvalidArgumentException(
                        'The definition.options key should be a JSON object '
                        'in route "{0}" in file "{1}".'
                        ''.format(name, path))
Exemple #29
0
 def closure(v):
     raise InvalidArgumentException(message.format(v));
Exemple #30
0
    def __init__(self, identifier, sourceId=None):
        InvalidArgumentException.__init__(self)
        self.__id = identifier
        self.__sourceId = sourceId

        self.updateRepr()
Exemple #31
0
    def get(self, path, default = None, deep = False):
        """Returns a parameter by name.

        @param string  path    The key
        @param mixed   default The default value if the parameter key does not exist
        @param boolean deep    If True, a path like foo[bar] will find deeper items

        @return mixed

        @raise InvalidArgumentException

        @api

        """

        try:
            pos = str(path).index('[');
        except ValueError:
            pos = False;
        if ( not deep or False is pos) :
            if path in self._parameters:
                return self._parameters[path];
            else:
                return default;


        root = str(path)[0:pos];
        if not root in self._parameters :
            return default;


        value = self._parameters[root];
        currentKey = None;
        i = pos - 1;
        for char in range(len(path)):
            i += 1;
            if ('[' == char) :
                if (None is not currentKey) :
                    raise InvalidArgumentException(
                        'Malformed path. Unexpected "[" at position {0}.'
                        ''.format(str(i))
                    );


                currentKey = '';
            elif (']' == char) :
                if (None is currentKey) :
                    raise InvalidArgumentException(
                        'Malformed path. Unexpected "]" at position {0}.'
                        ''.format(str(i))
                    );

                if isinstance(value, list):
                    value = Array.toDict(value, True);
                if not isinstance(value, dict) or currentKey not in value :
                    return default;


                value = value[currentKey];
                currentKey = None;
            else :
                if (None is currentKey) :
                    raise InvalidArgumentException(
                        'Malformed path. Unexpected "{0}" at position {1}.'
                        ''.format(char, str(i))
                    );


                currentKey += char;



        if (None is not currentKey) :
            raise InvalidArgumentException(
                'Malformed path. Path must end with "]".'
            );


        return value;
Exemple #32
0
    def locateResource(self, name, directory=None, first=True):
        """Returns the file path for a given resource.

        A Resource can be a file or a directory.
        The resource name must follow the following pattern:
            @BundleName/path/to/a/file.something
        where package is the name of the package
        and the remaining part is the relative path in the package.

        If directory is passed, and the first segment of the path is Resources,
        this method will look for a file named:
            directory/BundleName/path/without/Resources

        If BundleName is empty the application root directory is use.
            %kernel.root_dir%/path/to/a/file.something

        @param name: string A resource name to locate
        @param path: string A directory where to look for the resource first
        @param first: Boolean Whether to return the first path
            or paths for all matching bundles

        @return: string|array The absolute path of the resource
            or an array if $first is false

        @raise InvalidArgumentException: if the file cannot be found or
            the name is not valid
        @raise RuntimeException: if the name contains invalid/unsafe characters
        """
        name = str(name)
        isResource = False

        if not name.startswith("@"):
            raise InvalidArgumentException(
                'A resource name must start with @ ("{0}" given).'
                "".format(name))

        if ".." in name:
            raise RuntimeException(
                'File name "{0}" contains invalid characters (..).'
                "".format(name))

        bundleName = name[1:]
        if "/" in bundleName:
            bundleName, path = bundleName.split("/", 1)

        if path.startswith("Resources") and directory:
            isResource = True
        overridePath = path[10:]
        resourceBundle = None
        files = []

        if bundleName:
            bundles = self.getBundle(bundleName, False)
            for bundle in bundles:
                if isResource:
                    filename = os.path.join(directory, bundle.getName(),
                                            overridePath)
                    if os.path.exists(filename):
                        if resourceBundle:
                            raise RuntimeException(
                                '"{0}" resource is hidden by a resource from '
                                'the "{1}" derived bundle. Create a "{2}" '
                                'file to override the bundle resource.'
                                ''.format(
                                    filename, resourceBundle, directory + '/' +
                                    bundles[0].getName() + '/' + overridePath))
                        if first:
                            return filename
                        files.append(filename)

                filename = os.path.join(bundle.getPath(), path)
                if os.path.exists(filename):
                    if first and not isResource:
                        return filename
                    files.append(filename)
                    resourceBundle = bundle.getName()

        else:
            # check in root_dir when bundle name is empty
            if isResource:
                filename = os.path.join(directory, overridePath)
            else:
                filename = os.path.join(self._rootDir, path)
            if os.path.exists(filename):
                if first and not isResource:
                    return filename
                files.append(filename)

        if files:
            if first and isResource:
                return files[0]
            else:
                return files

        raise InvalidArgumentException(
            'Unable to find file "{0}".'.format(name))