Example #1
0
/**
 * Load classes
 * 
 * @param String Class name of class for loading
 * @param string Directory of class
 * @param boolean If class need instantiation
 * @return object
 */

function load_class($class, $directory = 'core', $instantiate = FALSE )
{
	static $_classes = array();

        $class_path = ROOT . '/' . $directory . '/' . $class;

        // return classe instance if exists (singleton pattern)
	if (isset($_classes[$class]))
	{
		return $_classes[$class];
	}

        if (file_exists($class_path . '.php'))
        {
                require $class_path . '.php';

                $reflection = new ReflectionClass("\\$directory\\$class");

                if($reflection->inNamespace())
                {
                        $class = $reflection->getNamespaceName() . '\\' . $class;
                }

                if($instantiate === TRUE)
                {
                        $_classes[$class] = new $class();
                        return $_classes[$class];
                }
        }
}
 /**
  * Returns inheritance inspection.
  *
  * The inspection result:
  *
  * must:
  *
  * * shortName
  * * name
  * * userDefined
  *
  * optional:
  *
  * * namespace
  *
  * @param \ReflectionClass $declaringClass ReflectionClass object.
  * @return array Inheritance inspection.
  */
 protected function getInheritanceInspection(\ReflectionClass $declaringClass)
 {
     $inheritanceInspection = array('shortname' => $declaringClass->getShortName(), 'name' => $declaringClass->getName(), 'filename' => $declaringClass->getFileName(), 'userDefined' => $declaringClass->isUserDefined());
     if ($declaringClass->inNamespace()) {
         $inheritanceInspection['namespace'] = $declaringClass->getNamespaceName();
     }
     return $inheritanceInspection;
 }
Example #3
0
 public function get($entity)
 {
     $function = new \ReflectionClass($entity);
     $className = $function->getShortName();
     $transformerClassName = sprintf("AppBundle\\Response\\Transformer\\%sTransformer", $className);
     if (class_exists($transformerClassName) === false) {
         throw new \Exception(sprintf("Transformer class for entity %s does not exist.", $function->inNamespace()));
     }
     $transformerClass = new $transformerClassName();
     return $transformerClass;
 }
 /**
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function getExistingClasses(array $paths) : array
 {
     $namespaceList = [];
     $classList = [];
     $list = [];
     foreach ($paths as $path) {
         if (false === $path->isSourceCode()) {
             continue;
         }
         $iter = new ClassIterator($this->getPhpFiles($path->getPathBase()));
         foreach (array_keys($iter->getClassMap()) as $classname) {
             if (in_array(substr($classname, -4), ['Test', 'Spec'])) {
                 continue;
             }
             $reflection = new \ReflectionClass($classname);
             if ($reflection->isAbstract() || $reflection->isTrait() || $reflection->isInterface()) {
                 continue;
             }
             if ($reflection->inNamespace()) {
                 $namespaces = explode('\\', $reflection->getNamespaceName());
                 $namespace = '';
                 foreach ($namespaces as $key => $namespacePart) {
                     if ($namespace !== '') {
                         $namespace .= '/';
                     }
                     $namespace .= $namespacePart;
                     if (!array_key_exists($key, $namespaceList)) {
                         $namespaceList[$key] = [];
                     }
                     $namespaceList[$key][$namespace] = $namespace;
                 }
             }
             $escapedName = str_replace('\\', '/', $classname);
             $classList[$escapedName] = $escapedName;
         }
     }
     foreach ($namespaceList as $namespaceDepthList) {
         $list = array_merge($list, $namespaceDepthList);
     }
     $list = array_merge($list, $classList);
     return $list;
 }
Example #5
0
	/**
	 * Expands class name into FQN.
	 * @param  string
	 * @return string  fully qualified class name
	 * @throws Nette\InvalidArgumentException
	 */
	public static function expandClassName($name, \ReflectionClass $reflector)
	{
		if (empty($name)) {
			throw new Nette\InvalidArgumentException('Class name must not be empty.');

		} elseif ($name === 'self') {
			return $reflector->getName();

		} elseif ($name[0] === '\\') { // already fully qualified
			return ltrim($name, '\\');
		}

		$filename = $reflector->getFileName();
		$parsed = static::getCache()->load($filename, function (& $dp) use ($filename) {
			if (AnnotationsParser::$autoRefresh) {
				$dp[Nette\Caching\Cache::FILES] = $filename;
			}
			return AnnotationsParser::parsePhp(file_get_contents($filename));
		});
		$uses = array_change_key_case((array) $tmp = & $parsed[$reflector->getName()]['use']);
		$parts = explode('\\', $name, 2);
		$parts[0] = strtolower($parts[0]);
		if (isset($uses[$parts[0]])) {
			$parts[0] = $uses[$parts[0]];
			return implode('\\', $parts);

		} elseif ($reflector->inNamespace()) {
			return $reflector->getNamespaceName() . '\\' . $name;

		} else {
			return $name;
		}
	}
    /**
     * Loads a list of classes and caches them in one big file.
     *
     * @param array   $classes    An array of classes to load
     * @param string  $cacheDir   A cache directory
     * @param string  $name       The cache name prefix
     * @param Boolean $autoReload Whether to flush the cache when the cache is stale or not
     * @param Boolean $adaptive   Whether to remove already declared classes or not
     * @param string  $extension  File extension of the resulting file
     *
     * @throws \InvalidArgumentException When class can't be loaded
     */
    static public function load($classes, $cacheDir, $name, $autoReload, $adaptive = false, $extension = '.php')
    {
        // each $name can only be loaded once per PHP process
        if (isset(self::$loaded[$name])) {
            return;
        }

        self::$loaded[$name] = true;

        if ($adaptive) {
            // don't include already declared classes
            $classes = array_diff($classes, get_declared_classes(), get_declared_interfaces());

            // the cache is different depending on which classes are already declared
            $name = $name.'-'.substr(md5(implode('|', $classes)), 0, 5);
        }

        $cache = $cacheDir.'/'.$name.$extension;

        // auto-reload
        $reload = false;
        if ($autoReload) {
            $metadata = $cacheDir.'/'.$name.$extension.'.meta';
            if (!is_file($metadata) || !is_file($cache)) {
                $reload = true;
            } else {
                $time = filemtime($cache);
                $meta = unserialize(file_get_contents($metadata));

                if ($meta[1] != $classes) {
                    $reload = true;
                } else {
                    foreach ($meta[0] as $resource) {
                        if (!is_file($resource) || filemtime($resource) > $time) {
                            $reload = true;

                            break;
                        }
                    }
                }
            }
        }

        if (!$reload && is_file($cache)) {
            require_once $cache;

            return;
        }

        $files = array();
        $content = '';
        foreach ($classes as $class) {
            if (!class_exists($class) && !interface_exists($class) && (!function_exists('trait_exists') || !trait_exists($class))) {
                throw new \InvalidArgumentException(sprintf('Unable to load class "%s"', $class));
            }

            $r = new \ReflectionClass($class);
            $files[] = $r->getFileName();

            $c = preg_replace(array('/^\s*<\?php/', '/\?>\s*$/'), '', file_get_contents($r->getFileName()));

            // add namespace declaration for global code
            if (!$r->inNamespace()) {
                $c = "\nnamespace\n{\n".self::stripComments($c)."\n}\n";
            } else {
                $c = self::fixNamespaceDeclarations('<?php '.$c);
                $c = preg_replace('/^\s*<\?php/', '', $c);
            }

            $content .= $c;
        }

        // cache the core classes
        if (!is_dir(dirname($cache))) {
            mkdir(dirname($cache), 0777, true);
        }
        self::writeCacheFile($cache, '<?php '.$content);

        if ($autoReload) {
            // save the resources
            self::writeCacheFile($metadata, serialize(array($files, $classes)));
        }
    }
    /**
     * Returns array of magic methods defined by annotation @method.
     * @return array
     */
    public static function getMagicMethods($class)
    {
        $rc = new \ReflectionClass($class);
        preg_match_all('~^
			[ \\t*]*  @method  [ \\t]+
			(?: [^\\s(]+  [ \\t]+ )?
			(set|get|is|add)  ([A-Z]\\w*)  [ \\t]*
			(?: \\(  [ \\t]* ([^)$\\s]+)  )?
		()~mx', $rc->getDocComment(), $matches, PREG_SET_ORDER);
        $methods = array();
        foreach ($matches as $m) {
            list(, $op, $prop, $type) = $m;
            $name = $op . $prop;
            $prop = strtolower($prop[0]) . substr($prop, 1) . ($op === 'add' ? 's' : '');
            if ($rc->hasProperty($prop) && ($rp = $rc->getProperty($prop)) && !$rp->isStatic()) {
                $rp->setAccessible(TRUE);
                if ($op === 'get' || $op === 'is') {
                    $type = NULL;
                    $op = 'get';
                } elseif (!$type && preg_match('#@var[ \\t]+(\\S+)' . ($op === 'add' ? '\\[\\]#' : '#'), $rp->getDocComment(), $m)) {
                    $type = $m[1];
                }
                if ($rc->inNamespace() && preg_match('#^[A-Z]\\w+(\\[|\\||\\z)#', $type)) {
                    $type = $rc->getNamespaceName() . '\\' . $type;
                }
                $methods[$name] = array($op, $rp, $type);
            }
        }
        return $methods;
    }
Example #8
0
    /**
     * Returns array of magic methods defined by annotation @method.
     * @return array
     */
    public static function getMagicMethods(string $class) : array
    {
        $rc = new \ReflectionClass($class);
        preg_match_all('~^
			[ \\t*]*  @method  [ \\t]+
			(?: [^\\s(]+  [ \\t]+ )?
			(set|get|is|add)  ([A-Z]\\w*)
			(?: ([ \\t]* \\()  [ \\t]* ([^)$\\s]*)  )?
		()~mx', (string) $rc->getDocComment(), $matches, PREG_SET_ORDER);
        $methods = [];
        foreach ($matches as list(, $op, $prop, $bracket, $type)) {
            if ($bracket !== '(') {
                trigger_error("Bracket must be immediately after @method {$op}{$prop}() in class {$class}.", E_USER_WARNING);
            }
            $name = $op . $prop;
            $prop = strtolower($prop[0]) . substr($prop, 1) . ($op === 'add' ? 's' : '');
            if ($rc->hasProperty($prop) && ($rp = $rc->getProperty($prop)) && !$rp->isStatic()) {
                $rp->setAccessible(TRUE);
                if ($op === 'get' || $op === 'is') {
                    $type = NULL;
                    $op = 'get';
                } elseif (!$type && preg_match('#@var[ \\t]+(\\S+)' . ($op === 'add' ? '\\[\\]#' : '#'), (string) $rp->getDocComment(), $m)) {
                    $type = $m[1];
                }
                if ($rc->inNamespace() && preg_match('#^[A-Z]\\w+(\\[|\\||\\z)#', (string) $type)) {
                    $type = $rc->getNamespaceName() . '\\' . $type;
                }
                $methods[$name] = [$op, $rp, $type];
            }
        }
        return $methods;
    }
 /**
  * Expands class name into FQN.
  * @param  string
  * @return string  fully qualified class name
  * @throws Nette\InvalidArgumentException
  */
 public static function expandClassName($name, \ReflectionClass $reflector)
 {
     if (empty($name)) {
         throw new Nette\InvalidArgumentException('Class name must not be empty.');
     }
     if ($name[0] === '\\') {
         // already fully qualified
         return ltrim($name, '\\');
     }
     $parsed = static::parsePhp(file_get_contents($reflector->getFileName()));
     $uses = array_change_key_case((array) ($tmp =& $parsed[$reflector->getName()]['use']));
     $parts = explode('\\', $name, 2);
     $parts[0] = strtolower($parts[0]);
     if (isset($uses[$parts[0]])) {
         $parts[0] = $uses[$parts[0]];
         return implode('\\', $parts);
     } elseif ($reflector->inNamespace()) {
         return $reflector->getNamespaceName() . '\\' . $name;
     } else {
         return $name;
     }
 }
 /**
  * @group DDC-3231
  */
 public function testGeneratedEntityRepositoryClassCustomDefaultRepository()
 {
     $em = $this->_getTestEntityManager();
     $ns = $this->_namespace;
     require_once __DIR__ . '/../../Models/DDC3231/DDC3231User2.php';
     $className = $ns . '\\DDC3231User2Tmp';
     $this->writeEntityClass('Doctrine\\Tests\\Models\\DDC3231\\DDC3231User2', $className);
     $rpath = $this->writeRepositoryClass($className, 'Doctrine\\Tests\\Models\\DDC3231\\DDC3231EntityRepository');
     $this->assertNotNull($rpath);
     $this->assertFileExists($rpath);
     require $rpath;
     $repo = new \ReflectionClass($em->getRepository($className));
     $this->assertTrue($repo->inNamespace());
     $this->assertSame($className . 'Repository', $repo->getName());
     $this->assertSame('Doctrine\\Tests\\Models\\DDC3231\\DDC3231EntityRepository', $repo->getParentClass()->getName());
     require_once __DIR__ . '/../../Models/DDC3231/DDC3231User2NoNamespace.php';
     $className2 = 'DDC3231User2NoNamespaceTmp';
     $this->writeEntityClass('DDC3231User2NoNamespace', $className2);
     $rpath2 = $this->writeRepositoryClass($className2, 'Doctrine\\Tests\\Models\\DDC3231\\DDC3231EntityRepository');
     $this->assertNotNull($rpath2);
     $this->assertFileExists($rpath2);
     require $rpath2;
     $repo2 = new \ReflectionClass($em->getRepository($className2));
     $this->assertFalse($repo2->inNamespace());
     $this->assertSame($className2 . 'Repository', $repo2->getName());
     $this->assertSame('Doctrine\\Tests\\Models\\DDC3231\\DDC3231EntityRepository', $repo2->getParentClass()->getName());
 }
Example #11
0
 public static function load($classes, $cacheDir, $name, $autoReload, $adaptive = false)
 {
     if (isset(self::$loaded[$name])) {
         return;
     }
     self::$loaded[$name] = true;
     $classes = array_unique($classes);
     if ($adaptive) {
         $classes = array_diff($classes, get_declared_classes(), get_declared_interfaces());
         $name = $name . '-' . substr(md5(implode('|', $classes)), 0, 5);
     }
     $cache = $cacheDir . '/' . $name . '.php';
     $reload = false;
     if ($autoReload) {
         $metadata = $cacheDir . '/' . $name . '.meta';
         if (!file_exists($metadata) || !file_exists($cache)) {
             $reload = true;
         } else {
             $time = filemtime($cache);
             $meta = unserialize(file_get_contents($metadata));
             if ($meta[1] != $classes) {
                 $reload = true;
             } else {
                 foreach ($meta[0] as $resource) {
                     if (!file_exists($resource) || filemtime($resource) > $time) {
                         $reload = true;
                         break;
                     }
                 }
             }
         }
     }
     if (!$reload && file_exists($cache)) {
         require_once $cache;
         return;
     }
     $files = array();
     $content = '';
     foreach ($classes as $class) {
         if (!class_exists($class) && !interface_exists($class)) {
             throw new \InvalidArgumentException(sprintf('Unable to load class "%s"', $class));
         }
         $r = new \ReflectionClass($class);
         $files[] = $r->getFileName();
         $c = preg_replace(array('/^\\s*<\\?php/', '/\\?>\\s*$/'), '', file_get_contents($r->getFileName()));
         if (!$r->inNamespace()) {
             $c = "\nnamespace\n{\n{$c}\n}\n";
         } else {
             $c = self::fixNamespaceDeclarations('<?php ' . $c);
             $c = preg_replace('/^\\s*<\\?php/', '', $c);
         }
         $content .= $c;
     }
     if (!is_dir(dirname($cache))) {
         mkdir(dirname($cache), 0777, true);
     }
     self::writeCacheFile($cache, Kernel::stripComments('<?php ' . $content));
     if ($autoReload) {
         self::writeCacheFile($metadata, serialize(array($files, $classes)));
     }
 }
Example #12
0
 /**
  * Return the local class for an object or a class that can be loaded.
  *
  * @param object|string $object
  *
  * @return string
  */
 static function get_local_class($object)
 {
     $class_name = is_object($object) ? get_class($object) : $object;
     try {
         $reflector = new \ReflectionClass($class_name);
         if ($reflector->inNamespace()) {
             $base_class = $reflector->getShortName();
         } else {
             $base_class = $class_name;
         }
     } catch (\Exception $e) {
         $base_class = $class_name;
     }
     return $base_class;
 }
 /**
  * {@inheritdoc}
  */
 public function inNamespace()
 {
     return $this->reflectionClass->inNamespace();
 }
 /**
  * Inspect namespace.
  *
  * @return void
  */
 protected function inspectNamespace()
 {
     if ($this->class->inNamespace()) {
         $this->inspection['namespace'] = $this->class->getNamespaceName();
     }
 }
Example #15
0
 /**
  * Expands class name into full name.
  * @param  string
  * @return string  full name
  * @throws Nette\InvalidArgumentException
  */
 public static function expandClassName(string $name, \ReflectionClass $rc) : string
 {
     $lower = strtolower($name);
     if (empty($name)) {
         throw new Nette\InvalidArgumentException('Class name must not be empty.');
     } elseif (in_array($lower, ['string', 'int', 'float', 'bool', 'array', 'callable'], TRUE)) {
         return $lower;
     } elseif ($lower === 'self') {
         return $rc->getName();
     } elseif ($name[0] === '\\') {
         // fully qualified name
         return ltrim($name, '\\');
     }
     $uses =& self::$cache[$rc->getName()];
     if ($uses === NULL) {
         self::$cache = self::parseUseStatemenets(file_get_contents($rc->getFileName()), $rc->getName()) + self::$cache;
         $uses =& self::$cache[$rc->getName()];
     }
     $parts = explode('\\', $name, 2);
     if (isset($uses[$parts[0]])) {
         $parts[0] = $uses[$parts[0]];
         return implode('\\', $parts);
     } elseif ($rc->inNamespace()) {
         return $rc->getNamespaceName() . '\\' . $name;
     } else {
         return $name;
     }
 }
Example #16
0
 /**
  * Constructor
  *
  * @param   array  $config  Configuration options
  * @return  void
  */
 public function __construct($config = array())
 {
     $this->_db = App::get('db');
     $this->args = '';
     // Set the controller name
     if (empty($this->_name)) {
         if (isset($config['name'])) {
             $this->_name = $config['name'];
         } else {
             // Get the reflection info
             $r = new ReflectionClass($this);
             // Is it namespaced?
             if ($r->inNamespace()) {
                 // It is! This makes things easy.
                 $this->_name = strtolower($r->getShortName());
             } else {
                 if (preg_match('/(.*)Macro/i', get_class($this), $r)) {
                     $this->_name = strtolower($r[1]);
                 } else {
                     throw new RuntimeException(__CLASS__ . '::__construct(); Can\'t get or parse class name.');
                 }
             }
         }
     }
 }
 /**
  * Return the path alias for the module the element belongs to based on its namespace
  * (assumes elements exist in a namespace below the module namespace)
  *
  * @param BaseEventTypeElement $element
  * @return string
  */
 public function getElementModulePathAlias(\BaseEventTypeElement $element)
 {
     $r = new ReflectionClass($element);
     if ($r->inNamespace()) {
         $ns_parts = explode('\\', $r->getNamespaceName());
         return implode('.', array_slice($ns_parts, 0, count($ns_parts) - 1));
     }
     return $this->modulePathAlias;
 }
Example #18
0
 /**
  * Expands class name into full name.
  * @param  string
  * @return string  full name
  * @throws Nette\InvalidArgumentException
  */
 public static function expandClassName($name, \ReflectionClass $rc)
 {
     if (empty($name)) {
         throw new Nette\InvalidArgumentException('Class name must not be empty.');
     } elseif ($name === 'self') {
         return $rc->getName();
     } elseif ($name[0] === '\\') {
         // fully qualified name
         return ltrim($name, '\\');
     }
     $uses =& self::$cache[$rc->getName()];
     if ($uses === NULL) {
         self::$cache = self::parseUseStatemenets(file_get_contents($rc->getFileName()), $rc->getName()) + self::$cache;
         $uses =& self::$cache[$rc->getName()];
     }
     $parts = explode('\\', $name, 2);
     if (isset($uses[$parts[0]])) {
         $parts[0] = $uses[$parts[0]];
         return implode('\\', $parts);
     } elseif ($rc->inNamespace()) {
         return $rc->getNamespaceName() . '\\' . $name;
     } else {
         return $name;
     }
 }
 /**
  * Parses internal PHP method modifiers (abstract, final, public, ...).
  *
  * @param \TokenReflection\ReflectionClass $class Parent class
  *
  * @return \TokenReflection\ReflectionMethod
  */
 private function parseInternalModifiers(ReflectionClass $class)
 {
     $name = strtolower($this->name);
     // In PHP 5.3.3+ the ctor can be named only __construct in namespaced classes
     if ('__construct' === $name || (!$class->inNamespace() || PHP_VERSION_ID < 50303) && strtolower($class->getShortName()) === $name) {
         $this->modifiers |= self::IS_CONSTRUCTOR;
     } elseif ('__destruct' === $name) {
         $this->modifiers |= self::IS_DESTRUCTOR;
     } elseif ('__clone' === $name) {
         $this->modifiers |= self::IS_CLONE;
     }
     if ($class->isInterface()) {
         $this->modifiers |= InternalReflectionMethod::IS_ABSTRACT;
     } else {
         // Can be called statically, see http://svn.php.net/viewvc/php/php-src/branches/PHP_5_3/Zend/zend_API.c?revision=309853&view=markup#l1795
         static $notAllowed = array('__clone' => true, '__tostring' => true, '__get' => true, '__set' => true, '__isset' => true, '__unset' => true);
         if (!$this->isStatic() && !$this->isConstructor() && !$this->isDestructor() && !isset($notAllowed[$name])) {
             $this->modifiers |= self::IS_ALLOWED_STATIC;
         }
     }
     return $this;
 }
<?php

namespace A\B;

class Foo
{
}
$function = new \ReflectionClass('stdClass');
var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
$function = new \ReflectionClass('A\\B\\Foo');
var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());