Exemplo n.º 1
0
    def getRootDir(self):
        if self._rootDir is None:
            r = ReflectionObject(self)
            self._rootDir = os.path.dirname(r.getFileName()).replace(
                '\\', '/')

        return self._rootDir
Exemplo n.º 2
0
class TestReflextion(unittest.TestCase, Object):
    def setUp(self):
        self.subject = ReflectionObject(self)

    def testConstructor(self):
        self.assertEqual(self.subject._class, self.__class__)

    def testGetFileName(self):
        self.assertEqual(inspect.getabsfile(self.__class__),
                         self.subject.getFileName())

    def testGetmro(self):
        self.assertEqual(self.__class__.__mro__, self.subject.getmro())
Exemplo n.º 3
0
    def getServiceIds(self):
        """Gets all service ids.

        @return: list An array of all defined service ids

        """

        ids = list()
        r = ReflectionObject(self)
        for method in r.getMethods():
            match = re.search('^get(.+)Service$', method.getName())
            if match:
                ids.append(self.underscore(match.group(1)))

        return Array.uniq(ids + list(self._services.keys()))
Exemplo n.º 4
0
    def addObjectResource(self, objectResource):
        """Adds the object class hierarchy as resources.

        @param: object object An object instance

        @return RouteCollection The current instance

        """
        assert isinstance(objectResource, Object)

        parent = ReflectionObject(objectResource)
        while parent:
            self.addResource(FileResource(parent.getFileName()))
            parent = parent.getParentClass()

        return self
Exemplo n.º 5
0
    def showAction(self, request, exception):
        assert isinstance(request, Request)

        if isinstance(exception, NotFoundConsoleException):
            title = 'Sorry, the command you are executing for could not be found.'
        else:
            title = 'Whoops, looks like something went wrong.'

        debug = self._container.getParameter('kernel.debug')

        verbose = False
        if request.hasOption('verbose'):
            verbose = request.getOption('verbose')

        content = ""
        nl = "\n"

        if debug:
            try:
                content += self._renderException(exception, nl, verbose)
            except Exception as e:
                message = e.getMessage() if isinstance(
                    e, StandardException) else str(e)

                title = 'Exception thrown when handling an exception ({0}: {1})'.format(
                    ReflectionObject(e).getName(), message)

        return Response("<error>{0}</error>{nl}{1}".format(title,
                                                           content,
                                                           nl=nl))
Exemplo n.º 6
0
    def getArguments(self, request, controller, response=None):
        """Returns the arguments to pass to the controller.

        @param Request request    A Request instance
        @param mixed   controller A PYTHON callable
        @param Response response  A Response instance

        @return list

        @raise RuntimeException When value for argument given is not provided

        @api

        """
        assert isinstance(request, Request)
        if None is response:
            response = Response()
        else:
            assert isinstance(response, Response)

        if inspect.ismethod(controller):
            r = ReflectionMethod(controller)
        elif inspect.isfunction(controller) or isinstance(controller, String):
            r = ReflectionFunction(controller)
        else:
            r = ReflectionObject(controller)
            r = r.getMethod('__call__')

        return self._doGetArguments(request, controller, r.getParameters(),
                                    response)
Exemplo n.º 7
0
    def getConfiguration(self, configs, container):
        assert isinstance(configs, list)
        assert isinstance(container, ContainerBuilder)

        className = ReflectionObject(
            self).getNamespaceName() + '.' + 'Configuration'

        r = ReflectionClass(className)

        if r.exists():
            configuration = r.newInstance()
            path = ReflectionObject(configuration).getFileName()
            container.addResource(FileResource(path))
            return configuration

        return None
Exemplo n.º 8
0
    def addObjectResource(self, objectResource):
        """Adds the object class hierarchy(, as resources.):

        @param: object object An object instance

        @return ContainerBuilder The current instance

        @api

        """
        assert isinstance(objectResource, Object)
        if not self.__trackResources:
            return self

        parent = ReflectionObject(objectResource)
        while parent:
            self.addResource(FileResource(parent.getFileName()))
            parent = parent.getParentClass()

        return self
Exemplo n.º 9
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]
Exemplo n.º 10
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)
Exemplo n.º 11
0
    def _getKernelParameters(self):
        bundles = dict()
        for name, bundle in self._bundles.items():
            bundles[name] = ReflectionObject(bundle).getName()

        parameters = {
            'kernel.root_dir': self._rootDir,
            'kernel.environment': self._environment,
            'kernel.debug': self._debug,
            'kernel.name': self._name,
            'kernel.cache_dir': self.getCacheDir(),
            'kernel.logs_dir': self.getLogDir(),
            'kernel.bundles': bundles,
            'kernel.charset': self.getCharset(),
            'kernel.container_class': self._getContainerClass(),
            'kernel.version': self.getVersion(),
        }
        parameters.update(self._getEnvParameters())
        return parameters
Exemplo n.º 12
0
    def __init__(self, argument):
        ReflectionObject.__init__(self, argument);

        self.bla = None;
Exemplo n.º 13
0
    def __init__(self, argument):
        ReflectionObject.__init__(self, argument)

        self.bla = None
Exemplo n.º 14
0
    def getRootDir(self):
        if self._rootDir is None:
            r = ReflectionObject(self);
            self._rootDir = os.path.dirname(r.getFileName()).replace('\\', '/');

        return self._rootDir;
Exemplo n.º 15
0
class Bundle(ContainerAware, BundleInterface):
    """An implementation of BundleInterface that adds a few conventions

    for DependencyInjection extensions.
    """
    def __init__(self):
        self._name = None
        self._reflected = None
        self._extension = None

    def boot(self):
        pass

    def shutdown(self):
        pass

    def build(self, container):
        assert isinstance(container, ContainerBuilder)

    def getContainerExtension(self):
        """Returns the bundle's container extension.

        @return: ExtensionInterface|null The container extension

        @raise LogicException: When alias not respect the naming convention
        """
        if self._extension is None:
            basename = re.sub(r"Bundle$", "", self.getName())

            moduleName = "{0}.dependency".format(self.getNamespace())
            className = "{0}.{1}Extension".format(moduleName, basename)

            r = ReflectionClass(className)

            if r.exists():
                extension = r.newInstance()
                # check naming convention
                expectedAlias = ContainerBuilder.underscore(basename)
                if expectedAlias != extension.getAlias():
                    raise LogicException(
                        'The extension alias for the default extension of a '
                        'bundle must be the underscored version of the '
                        'bundle name ("{0}" instead of "{1}")'
                        ''.format(expectedAlias, extension.getAlias()))

                self._extension = extension
            else:
                self._extension = False

        if self._extension:
            return self._extension

    def getNamespace(self):
        if self._reflected is None:
            self._reflected = ReflectionObject(self)
        return self._reflected.getNamespaceName()

    def getPath(self):
        if self._reflected is None:
            self._reflected = ReflectionObject(self)
        return dirname(self._reflected.getFileName())

    @final
    def getName(self):
        if self._name is None:
            self._name = str(type(self).__name__)
        return self._name

    def getParent(self):
        return None

    def registerCommands(self, collection):
        """Registers Commands.
Exemplo n.º 16
0
 def getPath(self):
     if self._reflected is None:
         self._reflected = ReflectionObject(self)
     return dirname(self._reflected.getFileName())
Exemplo n.º 17
0
 def getNamespace(self):
     if self._reflected is None:
         self._reflected = ReflectionObject(self)
     return self._reflected.getNamespaceName()
Exemplo n.º 18
0
 def setUp(self):
     self.subject = ReflectionObject(self)
Exemplo n.º 19
0
    def _renderException(self, e, nl="\n", verbose=False):
        content = ""
        while e:
            title = '  [{0}]  '.format(ReflectionObject(e).getName())
            lenght = len(title)
            width = 80
            # TODO: console width - 1
            lines = list()
            message = e.getMessage() if isinstance(
                e, StandardException) else str(e)
            for line in list(re.split('\r?\n', message)):
                for line in filter(
                        None,
                        re.split('(.{{1,{0}}})'.format(str(width - 4)), line)):
                    lines.append('  {0}  '.format(line))
                    lenght = max(len(line) + 4, lenght)

            messages = [
                ' ' * lenght, title + (' ' * max(0, lenght - len(title)))
            ]

            for line in lines:
                messages.append(line + (' ' * (lenght - len(line))))

            messages.append(' ' * lenght)

            content += nl
            content += nl
            for message in messages:
                content += '<error>' + message + '</error>' + nl

            content += nl
            content += nl

            if verbose and isinstance(e, StandardException):
                content += '<comment>Exception trace:</comment>' + nl

                # exception related properties
                trace = e.getTrace()

                for stack in trace:

                    className = ReflectionObject(
                        stack['locals']['self']).getName(
                        ) if 'self' in stack['locals'] else ''
                    function = stack['name']
                    file = stack['filename'] if 'filename' in stack else 'n/a'
                    line = stack['lineno'] if 'lineno' in stack else 'n/a'

                    content += ' {0}.{1}() at <info>{2}:{3}</info>{4}'.format(
                        className,
                        function,
                        file,
                        line,
                        nl,
                    )

                content += nl
                content += nl

            if isinstance(e, StandardException):
                e = e.getPrevious()
            else:
                e = False

        return content
Exemplo n.º 20
0
    def format(self, cpass, message):
        assert isinstance(cpass, CompilerPassInterface)

        return '{0}: {1}'.format(ReflectionObject(cpass).getName(), message)