Esempio n. 1
0
 def testStripcslashes(self):
     self.assertEqual(Tool.stripcslashes('\H\e\l\l\o \W\or\l\d'),
                      "Hello World")
     self.assertEqual(Tool.stripcslashes('Hello World\\r\\n'),
                      'Hello World\r\n')
     self.assertEqual(
         Tool.stripcslashes('\x48\x65\x6c\x6c\x6f \x57\x6f\x72\x6c\x64'),
         "Hello World")
     self.assertEqual(
         Tool.stripcslashes('\110\145\154\154\157 \127\157\162\154\144'),
         "Hello World")
Esempio n. 2
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);
Esempio n. 3
0
    def __init__(self, argument):
        if isinstance(argument, String):
            qualClassName = argument
            try:
                argument = ClassLoader.load(argument)
            except ImportError:
                argument = False

        if argument is not False:
            assert issubclass(argument, object)
            self.__exists = True
            self._class = argument
            self._fileName = None
            self._mro = None
            self._namespaceName = None
            self._parentClass = None
            self._name = None
        else:
            self.__exists = False
            self._name = qualClassName
            self._fileName = ''
            self._mro = tuple()
            self._namespaceName = Tool.split(qualClassName)[0]
            self._parentClass = False
            self._class = None

        self._methods = None
Esempio n. 4
0
    def __init__(self, argument):
        if isinstance(argument, String):
            qualClassName = argument;
            try:
                argument = ClassLoader.load(argument);
            except ImportError:
                argument = False;

        if argument is not False:
            assert issubclass(argument, object);
            self.__exists = True;
            self._class = argument;
            self._fileName = None;
            self._mro = None;
            self._namespaceName = None;
            self._parentClass = None;
            self._name = None;
        else:
            self.__exists = False;
            self._name = qualClassName;
            self._fileName = '';
            self._mro = tuple();
            self._namespaceName = Tool.split(qualClassName)[0];
            self._parentClass = False;
            self._class = None;

        self._methods = None;
Esempio n. 5
0
    def __init__(self, stream, verbosity = Output.VERBOSITY_NORMAL, decorated = None, formatter = None):
        """Constructor.

        @param mixed                    stream    A stream resource
        @param integer                  verbosity The verbosity level (self.VERBOSITY_QUIET, self.VERBOSITY_NORMAL,
                                                                        self.VERBOSITY_VERBOSE)
        @param Boolean                  decorated Whether to decorate messages or not (None for auto-guessing)
        @param OutputFormatterInterface formatter Output formatter instance

        @raise InvalidArgumentException When first argument is not a real stream

        @api

        """
        if formatter:
            assert isinstance(formatter, OutputFormatterInterface);

        self.__stream = None;

        for method in ['flush', 'write', 'isatty']:
            if not Tool.isCallable(getattr(stream, method, None)):
                raise InvalidArgumentException(
                    'The StreamOutput class needs a stream as its first '
                    'argument.'
                );


        self.__stream = stream;

        if (None is decorated) :
            decorated = self._hasColorSupport();


        Output.__init__(self, verbosity, decorated, formatter);
Esempio n. 6
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)
Esempio n. 7
0
    def then(self, closure):
        """Sets the closure to run if the test pass.

        @param closure: callable

        @return: ExprBuilder
        """
        assert Tool.isCallable(closure);
        self.thenPart = closure;
        return self;
Esempio n. 8
0
    def always(self, then=None):
        """Marks the expression as being always used.

        @param then: callable

        @return: ExprBuilder
        """
        self.ifPart = lambda v: True;

        if not then is None:
            assert Tool.isCallable(then);
            self.thenPart = then;
        return self;
Esempio n. 9
0
    def rule(self, closure=None):
        """Registers a closure to run as normalization
        or an expression builder to build it if null is provided.

        @param closure: callable

        @return: ExprBuilder|ValidationBuilder
        """
        if not closure is None:
            assert Tool.isCallable(closure);
            self.rules.append(closure);
            return self;
        self.rules.append(ExprBuilder(self._node));
        return self.rules[-1];
Esempio n. 10
0
    def ifTrue(self, closure=None):
        """Sets a closure to use as tests.

        The default one tests if the value is true.

        @param closure: callable

        @return: ExprBuilder
        """
        if closure is None:
            closure = lambda v: v is True;
        assert Tool.isCallable(closure);
        self.ifPart = closure;
        return self;
Esempio n. 11
0
    def setController(self, controller):
        """Sets a new controller

        @param callable controller

        @raise LogicException

        @api

        """

        # controller must be a callable
        if (not Tool.isCallable(controller)):
            raise LogicException(
                'The controller must be a callable ({0} given).'.format(
                    repr(controller)))

        self.__controller = controller
Esempio n. 12
0
    def setController(self, controller):
        """Sets a new controller

        @param callable controller

        @raise LogicException

        @api

        """

        # controller must be a callable
        if ( not Tool.isCallable(controller)) :
            raise LogicException(
                'The controller must be a callable ({0} given).'.format(
                    repr(controller)
            ));


        self.__controller = controller;
Esempio n. 13
0
    def setContent(self, content):
        """Sets the response content.

        Valid types are strings, numbers, and objects that implement a __str__() method.

        @param mixed content

        @return Response

        @raise UnexpectedValueException

        @api

        """

        if (not Tool.isCallable(getattr(content, '__str__', None))) :
            raise UnexpectedValueException(
                'The Response content must be a string or object implementing '
                '__str__(), "'+type(content)+'" given.'
            );

        self._content = str(content);

        return self;
Esempio n. 14
0
 def testRegularClass(self):
     self.assertFalse(Tool.isAbstract(RegularClass))
     RegularClass().method()
Esempio n. 15
0
 def testAbstractMethod(self):
     self.assertTrue(Tool.isAbstract(AbstractMethod))
     self.assertRaises(TypeError, lambda: AbstractMethod().method())
Esempio n. 16
0
 def testAbstractClass(self):
     self.assertTrue(Tool.isAbstract(AbstractClass))
Esempio n. 17
0
 def testAbstract(self):
     self.assertFalse(Tool.isAbstract(type(self)))
     self.assertTrue(Tool.isAbstract(OOPObject))
Esempio n. 18
0
 def testAbstract(self):
     self.assertFalse(Tool.isAbstract(type(self)));
     self.assertTrue(Tool.isAbstract(OOPObject));
Esempio n. 19
0
 def testAbstractClass(self):
     self.assertTrue(Tool.isAbstract(AbstractClass));
Esempio n. 20
0
 def getDefaultValue(self):
     if Tool.isCallable(self._defaultValue):
         return eval(self._defaultValue)();
     else:
         return self._defaultValue;
Esempio n. 21
0
 def testAbstractMethod(self):
     self.assertTrue(Tool.isAbstract(AbstractMethod));
     self.assertRaises(TypeError, lambda:AbstractMethod().method());
Esempio n. 22
0
 def testRegularClass(self):
     self.assertFalse(Tool.isAbstract(RegularClass));
     RegularClass().method();
Esempio n. 23
0
    def __createService(self, definition, identifier):
        """Creates a service for a service definition.

        @param: Definition definition A service definition instance
        @param string     id         The service identifier:

        @return object The service described by the service definition

        @raise RuntimeException When the scope is inactive
        @raise RuntimeException When the factory definition is incomplete
        @raise RuntimeException When the service is a synthetic service
        @raise InvalidArgumentException When configure callable is not callable

        """
        assert isinstance(definition, Definition)

        if definition.isSynthetic():
            raise RuntimeException(
                'You have requested a synthetic service ("{0}"). '
                'The DIC does not know how to construct this service.'
                ''.format(identifier))

        parameterBag = self.getParameterBag()

        if None is not definition.getFile():
            path = parameterBag.resolveValue(definition.getFile())
            module = SourceFileLoader.load(path)
        else:
            module = None

        value = parameterBag.resolveValue(definition.getArguments())
        value = parameterBag.unescapeValue(value)
        arguments = self.resolveServices(value)

        if not definition.getFactoryMethod() is None:
            if not definition.getFactoryClass() is None:
                factory = parameterBag.resolveValue(
                    definition.getFactoryClass())
                if module is not None:
                    factory = getattr(module, factory)
                else:
                    factory = ClassLoader.load(factory)
            elif not definition.getFactoryService() is None:
                factory = self.get(
                    parameterBag.resolveValue(definition.getFactoryService()))
            else:
                raise RuntimeException(
                    'Cannot create service "{0}" from factory method without '
                    'a factory service or factory class.'
                    ''.format(identifier))

            service = getattr(factory,
                              definition.getFactoryMethod())(*arguments)
        else:
            className = parameterBag.resolveValue(definition.getClass())
            if module is not None:
                service = getattr(module, className)(*arguments)
            else:
                service = ClassLoader.load(className)(*arguments)

        scope = definition.getScope()
        if self.SCOPE_PROTOTYPE != scope:
            if self.SCOPE_CONTAINER != scope and scope not in self._scopedServices:
                raise RuntimeException(
                    'You tried to create the "{0}" service of an inactive '
                    'scope.'.format(identifier))

            lowerId = self._formatIdentifier(identifier)
            self._services[lowerId] = service

            if (self.SCOPE_CONTAINER != scope):
                self._scopedServices[scope][lowerId] = service

        for call in definition.getMethodCalls():
            services = self.getServiceConditionals(call[1])
            ok = True
            for s in services:
                if not self.has(s):
                    ok = False
                    break
            if ok:
                args = self.resolveServices(parameterBag.resolveValue(call[1]))
                getattr(service, call[0])(*args)

        properties = self.resolveServices(
            parameterBag.resolveValue(definition.getProperties()))
        for name, value in properties.items():
            setattr(service, name, value)

        closure = definition.getConfigurator()
        if closure:
            if isinstance(closure, list):
                if isinstance(closure[0], Reference):
                    closure[0] = self.get(str(closure[0]))
                else:
                    closure[0] = parameterBag.resolveValue(closure[0])
                    closure[0] = ClassLoader.load(closure[0])

                closure = getattr(closure[0], closure[1])

            if not Tool.isCallable(closure):
                raise InvalidArgumentException(
                    'The configure callable for class "{0}" is not a callable.'
                    ''.format(type(service).__name__))

            closure(service)

        return service
Esempio n. 24
0
 def getDefaultValue(self):
     if Tool.isCallable(self._defaultValue):
         return eval(self._defaultValue)()
     else:
         return self._defaultValue