Skip to content

Instantly share code, notes, and snippets.

@simshaun
Created April 25, 2013 18:53
Show Gist options
  • Save simshaun/5462135 to your computer and use it in GitHub Desktop.
Save simshaun/5462135 to your computer and use it in GitHub Desktop.
This is a bad example (it was thrown together) of getting a namespace and class names that are in a file. It doesn't support multiple namespaces and it makes assumptions about the src. It would need rewritten to make it flexible (probably looping through token_get_all to construct all of the necessary information).
<?php
class FileInspector
{
protected $filename;
protected $namespace;
protected $contents;
public function __construct($filename) {
if ( ! $this->contents = @file_get_contents($filename)) {
throw new \Exception('File not found');
}
$this->filename = $filename;
}
public function getNamespace() {
if (null === $this->namespace) {
preg_match('/^namespace\s+(.*?);/im', $this->contents, $matches);
$this->namespace = empty($matches) ? false : $matches[1];
}
return $this->namespace;
}
public function getClasses() {
$tokens = token_get_all($this->contents);
$classes = array();
foreach ($tokens as $i => $token) {
if (T_CLASS === $token[0]) {
$classes[] = array(
'ns' => $this->getNamespace(),
'class' => $tokens[$i+2][1],
);
}
}
return $classes;
}
}
$fi = new FileInspector('test.php');
var_dump($fi->getClasses());
<?php
namespace Acme\Foo;
class TestClass1 {
// namespace Bar;
// namespace Foo;
}
class TestClass2 {
// namespace Bar;
// namespace Foo;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment