Last active
August 29, 2015 13:56
-
-
Save akluth/8978414 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Minimal and very simple annotation parser. | |
* | |
* For examples, look at the doc comments beneath. | |
* | |
* Licensed under the terms and conditions of the MIT license. | |
* | |
* @author Alexander Kluth <contact@alexander.kluth.com> | |
*/ | |
class AnnotationParser | |
{ | |
static $ANNOTATION_NAME = 1; | |
static $ANNOTATION_VALUE = 2; | |
static private $reflector; | |
/** | |
* The AnnotationParser itself contains those documents so it can test itself via phpspec. | |
* | |
* @Route\Name{"/hello"} | |
* @Route\Method{"POST"} | |
* @Route\Returns{"json"} | |
*/ | |
static public function parseMethod($class, $method) | |
{ | |
self::$reflector = new \ReflectionMethod($class, $method); | |
return self::parseAnnotation(self::$reflector->getDocComment()); | |
} | |
/** | |
* The AnnotationParser itself contains those documents so it can test itself via phpspec. | |
* | |
* @Route\Name{"/"} | |
* @Route\Method{"GET"} | |
* @Route\Returns{"xml"} | |
*/ | |
static public function parseClass($class) | |
{ | |
self::$reflector = new \ReflectionClass($class); | |
$parsedData = []; | |
foreach (self::$reflector->getMethods() as $method) { | |
$parsedData[$method->getName()] = self::parseAnnotation($method->getDocComment()); | |
} | |
return $parsedData; | |
} | |
static private function parseAnnotation($docBlock) | |
{ | |
if (!$docBlock) { | |
return null; | |
} | |
$rawAnnotations = []; | |
$annotationTokens = []; | |
$parsedAnnotations = []; | |
if (!preg_match_all('/@(.*)/', $docBlock, $rawAnnotations)) { | |
return null; | |
} | |
foreach ($rawAnnotations[1] as $annotation) { | |
preg_match('/\\\\([\w]+)\{"([\/a-zA-Z\-]+)"}/', $annotation, $annotationTokens); | |
$parsedAnnotations[$annotationTokens[self::$ANNOTATION_NAME]] = $annotationTokens[self::$ANNOTATION_VALUE]; | |
} | |
return $parsedAnnotations; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment