Jelajahi Sumber

Promoted Zend_Amf_Adobe_Introspector to trunk

git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@15412 44c647ce-9c0f-0410-b52a-842ac1e357ba
matthew 16 tahun lalu
induk
melakukan
fffd22bdf8

+ 307 - 0
library/Zend/Amf/Adobe/Introspector.php

@@ -0,0 +1,307 @@
+<?php
+/**
+ * Zend Framework
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://framework.zend.com/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@zend.com so we can send you a copy immediately.
+ *
+ * @category   Zend
+ * @package    Zend_Amf
+ * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
+ * @license    http://framework.zend.com/license/new-bsd     New BSD License
+ */
+
+/** Zend_Amf_Parse_TypeLoader */
+require_once 'Zend/Amf/Parse/TypeLoader.php';
+
+/** Zend_Reflection_Class */
+require_once 'Zend/Reflection/Class.php';
+
+/** Zend_Server_Reflection */
+require_once 'Zend/Server/Reflection.php';
+
+/**
+ * This class implements a service for generating AMF service descriptions as XML.
+ *
+ * @package    Zend_Amf
+ * @subpackage Adobe
+ * @copyright  Copyright (c) 2009 Zend Technologies USA Inc. (http://www.zend.com)
+ * @license    http://framework.zend.com/license/new-bsd     New BSD License
+ */
+class Zend_Amf_Adobe_Introspector 
+{
+    /**
+     * Options used:
+     * - server: instance of Zend_Amf_Server to use
+     * - directories: directories where class files may be looked up
+     *
+     * @var array Introspector options
+     */
+    protected $_options;
+
+    /**
+     * @var DOMElement DOM element to store types
+     */
+    protected $_types;
+
+    /**
+     * @var array Map of the known types
+     */
+    protected $_typesMap = array();
+
+    /**
+     * @var DOMDocument XML document to store data
+     */
+    protected $_xml;
+   
+    /**
+     * Constructor
+     * 
+     * @return void
+     */
+    public function __construct()
+    {
+        $this->_xml = new DOMDocument('1.0', 'utf-8');
+    }
+    
+    /**
+     * Create XML definition on an AMF service class
+     * 
+     * @param  string $serviceClass Service class name
+     * @param  array $options invocation options
+     * @return string XML with service class introspection
+     */
+    public function introspect($serviceClass, $options = array()) 
+    {
+        $this->_options = $options;
+        
+        if (strpbrk($serviceClass, '\\/<>')) {
+            return $this->_returnError('Invalid service name');
+        }
+
+        // Transform com.foo.Bar into com_foo_Bar
+        $serviceClass = str_replace('.' , '_', $serviceClass);
+
+        // Introspect!
+        if (!class_exists($serviceClass)) {
+            Zend_Loader::loadClass($serviceClass, $this->_getServicePath());
+        }
+        
+        $serv = $this->_xml->createElement('operations');
+        $serv->setAttribute('xmlns', 'http://ns.adobe.com/flex/service-description/2008');
+
+        $this->_types = $this->_xml->createElement('types');
+        $this->_ops   = $this->_xml->createElement('operations');
+
+        $r = Zend_Server_Reflection::reflectClass($serviceClass);
+        $this->_addService($r, $this->_ops);
+    
+        $serv->appendChild($this->_types);
+        $serv->appendChild($this->_ops);
+        $this->_xml->appendChild($serv);
+
+        return $this->_xml->saveXML();
+    }
+    
+    /**
+     * Authentication handler
+     * 
+     * @param  Zend_Acl $acl
+     * @return unknown_type
+     */
+    public function initAcl(Zend_Acl $acl)
+    {
+        return false; // we do not need auth for this class
+    }
+
+    /**
+     * Generate map of public class attributes
+     * 
+     * @param  string $typename type name
+     * @param  DOMElement $typexml target XML element 
+     * @return void
+     */
+    protected function _addClassAttributes($typename, DOMElement $typexml)
+    {
+        // Do not try to autoload here because _phpTypeToAS should 
+        // have already attempted to load this class
+        if (!class_exists($typename, false)) {
+            return;
+        }
+
+        $rc = new Zend_Reflection_Class($typename);
+        foreach ($rc->getProperties() as $prop) {
+            if (!$prop->isPublic()) {
+                continue;
+            }
+
+            $propxml = $this->_xml->createElement('property');
+            $propxml->setAttribute('name', $prop->getName());
+
+            $type = $this->_registerType($this->_getPropertyType($prop));
+            $propxml->setAttribute('type', $type);
+
+            $typexml->appendChild($propxml);
+        }
+    }
+
+    /**
+     * Build XML service description from reflection class
+     * 
+     * @param  Zend_Server_Reflection_Class $refclass  
+     * @param  DOMElement $target target XML element
+     * @return void
+     */
+    protected function _addService(Zend_Server_Reflection_Class $refclass, DOMElement $target)
+    {
+        foreach ($refclass->getMethods() as $method) {
+            if (!$method->isPublic() 
+                || $method->isConstructor()
+                || ('__' == substr($method->name, 0, 2))
+            ) {
+                continue;
+            }
+
+            foreach ($method->getPrototypes() as $proto) {
+                $op = $this->_xml->createElement('operation');
+                $op->setAttribute('name', $method->getName());
+
+                $rettype = $this->_registerType($proto->getReturnType());
+                $op->setAttribute('returnType', $rettype);
+
+                foreach ($proto->getParameters() as $param) {
+                    $arg = $this->_xml->createElement('argument');
+                    $arg->setAttribute('name', $param->getName());
+
+                    $type = $param->getType();
+                    if ($type == 'mixed' && ($pclass = $param->getClass())) {
+                        $type = $pclass->getName();
+                    }
+
+                    $ptype = $this->_registerType($type);
+                    $arg->setAttribute('type', $ptype);
+
+                    $op->appendChild($arg);
+                }
+
+                $target->appendChild($op);
+            }
+        }
+    }
+    
+    /**
+     * Extract type of the property from DocBlock
+     * 
+     * @param  Zend_Reflection_Property $prop reflection property object
+     * @return string Property type
+     */
+    protected function _getPropertyType(Zend_Reflection_Property $prop)
+    {
+        $docBlock = $prop->getDocComment();
+
+        if (!$docBlock) {
+            return 'Unknown';
+        }
+
+        if (!$docBlock->hasTag('var')) {
+            return 'Unknown';
+        }
+
+        $tag = $docBlock->getTag('var');
+        return trim($tag->getDescription());
+    }
+    
+    /**
+     * Get the array of service directories
+     * 
+     * @return array Service class directories
+     */
+    protected function _getServicePath() 
+    {
+        if (isset($this->_options['server'])) {
+            return $this->_options['server']->getDirectory();
+        }
+
+        if (isset($this->_options['directories'])) {
+            return $this->_options['directories'];
+        }
+
+        return array();
+    }
+
+    /**
+     * Map from PHP type name to AS type name
+     * 
+     * @param  string $typename PHP type name
+     * @return string AS type name
+     */
+    protected function _phpTypeToAS($typename)
+    {
+        if (class_exists($typename)) {
+            $vars = get_class_vars($typename);
+
+            if (isset($vars['_explicitType'])) {
+                return $vars['_explicitType'];
+            }
+        }
+
+        if (false !== ($asname = Zend_Amf_Parse_TypeLoader::getMappedClassName($typename))) {
+            return $asname;
+        }
+
+        return $typename;
+    }
+
+    /**
+     * Register new type on the system
+     * 
+     * @param  string $typename type name
+     * @return string New type name
+     */
+    protected function _registerType($typename) 
+    {
+        // Known type - return its AS name
+        if (isset($this->_typesMap[$typename])) {
+            return $this->_typesMap[$typename];
+        }
+
+        // Standard types
+        if (in_array($typename, array('null', 'mixed', 'unknown_type'))) {
+            return 'Unknown';
+        }
+
+        if (in_array($typename, array('void', 'string', 'object', 'Unknown', 'stdClass', 'array'))) {
+            return $typename;
+        }
+
+        // Resolve and store AS name
+        $asTypeName = $this->_phpTypeToAS($typename);
+        $this->_typesMap[$typename] = $asTypeName;
+
+        // Create element for the name
+        $typeEl = $this->_xml->createElement('type');
+        $typeEl->setAttribute('name', $asTypeName);
+        $this->_addClassAttributes($typename, $typeEl);
+        $this->_types->appendChild($typeEl);    
+
+        return $asTypeName;
+    }
+    
+   /**
+     * Return error with error message
+     * 
+     * @param  string $msg Error message
+     * @return string 
+     */
+    protected function _returnError($msg) 
+    {
+        return 'ERROR: $msg';    
+    }
+}

+ 192 - 0
tests/Zend/Amf/Adobe/IntrospectorTest.php

@@ -0,0 +1,192 @@
+<?php
+// Call Zend_Controller_Action_Helper_MultiPageFormTest::main() if this source file is executed directly.
+if (!defined("PHPUnit_MAIN_METHOD")) {
+    define("PHPUnit_MAIN_METHOD", "Zend_Amf_Adobe_IntrospectorTest::main");
+}
+
+require_once dirname(__FILE__) . '/../../../TestHelper.php';
+
+/**
+ * @see Zend_Amf_Adobe_Introspector
+ */
+require_once 'Zend/Amf/Adobe/Introspector.php';
+
+class Zend_Amf_Adobe_IntrospectorTest extends PHPUnit_Framework_TestCase
+{
+    public static function main()
+    {
+        $suite  = new PHPUnit_Framework_TestSuite(__CLASS__);
+        PHPUnit_TextUI_TestRunner::run($suite);
+    }
+    
+    public function setUp()
+    {
+        $this->introspector = new Zend_Amf_Adobe_Introspector();
+    }
+
+    public function testIntrospectionDoesNotIncludeConstructor()
+    {
+        $xml = $this->introspector->introspect('com.zend.framework.IntrospectorTest');
+        $this->assertNotContains('__construct', $xml);
+    }
+
+    public function testIntrospectionDoesNotIncludeMagicMethods()
+    {
+        $xml = $this->introspector->introspect('com.zend.framework.IntrospectorTest');
+        $this->assertNotContains('__get', $xml);
+    }
+
+    public function testIntrospectionContainsPublicPropertiesOfReturnClassTypes()
+    {
+        $xml = $this->introspector->introspect('com.zend.framework.IntrospectorTest');
+        $this->assertRegexp('/<type[^>]*(name="com_zend_framework_IntrospectorTestCustomType")/', $xml, $xml);
+        $this->assertRegexp('/<property[^>]*(name="foo")/', $xml, $xml);
+        $this->assertRegexp('/<property[^>]*(type="string")/', $xml, $xml);
+    }
+
+    public function testIntrospectionDoesNotContainNonPublicPropertiesOfReturnClassTypes()
+    {
+        $xml = $this->introspector->introspect('com.zend.framework.IntrospectorTest');
+        $this->assertNotRegexp('/<property[^>]*(name="_bar")/', $xml, $xml);
+    }
+
+    public function testIntrospectionContainsPublicMethods()
+    {
+        $xml = $this->introspector->introspect('com.zend.framework.IntrospectorTest');
+        $this->assertRegexp('/<operation[^>]*(name="foobar")/', $xml, $xml);
+        $this->assertRegexp('/<operation[^>]*(name="barbaz")/', $xml, $xml);
+        $this->assertRegexp('/<operation[^>]*(name="bazbat")/', $xml, $xml);
+    }
+
+    public function testIntrospectionContainsOperationForEachPrototypeOfAPublicMethod()
+    {
+        $xml = $this->introspector->introspect('com.zend.framework.IntrospectorTest');
+        $this->assertEquals(4, substr_count($xml, 'name="foobar"'));
+        $this->assertEquals(1, substr_count($xml, 'name="barbaz"'));
+        $this->assertEquals(1, substr_count($xml, 'name="bazbat"'));
+    }
+
+    public function testPassingDirectoriesOptionShouldResolveServiceClassAndType()
+    {
+        require_once dirname(__FILE__) . '/_files/ZendAmfAdobeIntrospectorTestType.php';
+        $xml = $this->introspector->introspect('ZendAmfAdobeIntrospectorTest', array(
+            'directories' => array(dirname(__FILE__) . '/_files'),
+        ));
+        $this->assertRegexp('/<operation[^>]*(name="foo")/', $xml, $xml);
+        $this->assertRegexp('/<type[^>]*(name="ZendAmfAdobeIntrospectorTestType")/', $xml, $xml);
+        $this->assertRegexp('/<property[^>]*(name="bar")/', $xml, $xml);
+    }
+
+    public function testMissingPropertyDocblockInTypedClassShouldReportTypeAsUnknown()
+    {
+        $xml = $this->introspector->introspect('com.zend.framework.IntrospectorTest');
+        if (!preg_match('/(<property[^>]*(name="baz")[^>]*>)/', $xml, $matches)) {
+            $this->fail('Baz property of com.zend.framework.IntrospectorTestCustomType not found');
+        }
+        $node = $matches[1];
+        $this->assertContains('type="Unknown"', $node, $node);
+    }
+
+    public function testPropertyDocblockWithoutAnnotationInTypedClassShouldReportTypeAsUnknown()
+    {
+        $xml = $this->introspector->introspect('com.zend.framework.IntrospectorTest');
+        if (!preg_match('/(<property[^>]*(name="bat")[^>]*>)/', $xml, $matches)) {
+            $this->fail('Bat property of com.zend.framework.IntrospectorTestCustomType not found');
+        }
+        $node = $matches[1];
+        $this->assertContains('type="Unknown"', $node, $node);
+    }
+
+    public function testTypedClassWithExplicitTypeShouldReportAsThatType()
+    {
+        $xml = $this->introspector->introspect('com.zend.framework.IntrospectorTest');
+        $this->assertRegexp('/<type[^>]*(name="explicit")/', $xml, $xml);
+    }
+}
+
+class com_zend_framework_IntrospectorTest
+{
+    /**
+     * Constructor
+     * 
+     * @return void
+     */
+    public function __construct()
+    {
+    }
+
+    /**
+     * Overloading: get properties
+     * 
+     * @param  string $name 
+     * @return mixed
+     */
+    public function __get($name)
+    {
+        $prop = '_' . $name;
+        if (!isset($this->$prop)) {
+            return null;
+        }
+        return $this->$prop;
+    }
+
+    /**
+     * Foobar
+     * 
+     * @param  string|int $arg
+     * @return string|stdClass
+     */
+    public function foobar($arg)
+    {
+    }
+
+    /**
+     * Barbaz
+     * 
+     * @param  com_zend_framework_IntrospectorTestCustomType $arg
+     * @return boolean
+     */
+    public function barbaz($arg)
+    {
+    }
+
+    /**
+     * Bazbat 
+     * 
+     * @return com_zend_framework_IntrospectorTestExplicitType
+     */
+    public function bazbat()
+    {
+    }
+}
+
+class com_zend_framework_IntrospectorTestCustomType
+{
+    /**
+     * @var string
+     */
+    public $foo;
+
+    public $baz;
+
+    /**
+     * Docblock without an annotation
+     */
+    public $bat;
+
+    /**
+     * @var bool
+     */
+    protected $_bar;
+}
+
+class com_zend_framework_IntrospectorTestExplicitType
+{
+    public $_explicitType = 'explicit';
+}
+
+
+// Call Zend_Amf_Adobe_IntrospectorTest::main() if this source file is executed directly.
+if (PHPUnit_MAIN_METHOD == "Zend_Amf_Adobe_IntrospectorTest::main") {
+    Zend_Amf_Adobe_IntrospectorTest::main();
+}

+ 14 - 0
tests/Zend/Amf/Adobe/_files/ZendAmfAdobeIntrospectorTest.php

@@ -0,0 +1,14 @@
+<?php
+class ZendAmfAdobeIntrospectorTest
+{
+    /**
+     * Foobar
+     * 
+     * @param  string $arg
+     * @return ZendAmfAdobeIntrospectorTestType
+     */
+    public function foo($arg)
+    {
+    }
+}
+

+ 8 - 0
tests/Zend/Amf/Adobe/_files/ZendAmfAdobeIntrospectorTestType.php

@@ -0,0 +1,8 @@
+<?php
+class ZendAmfAdobeIntrospectorTestType
+{
+    /**
+     * @var string
+     */
+    public $bar;
+}

+ 2 - 1
tests/Zend/Amf/AllTests.php

@@ -7,6 +7,7 @@ if (!defined('PHPUnit_MAIN_METHOD')) {
     define('PHPUnit_MAIN_METHOD', 'Zend_Amf_AllTests::main');
 }
 
+require_once 'Zend/Amf/Adobe/IntrospectorTest.php';
 require_once 'Zend/Amf/RequestTest.php';
 require_once 'Zend/Amf/ResponseTest.php';
 require_once 'Zend/Amf/ServerTest.php';
@@ -26,6 +27,7 @@ class Zend_Amf_AllTests
     {
         $suite = new PHPUnit_Framework_TestSuite('Zend Framework - Zend_Amf');
 
+        $suite->addTestSuite('Zend_Amf_Adobe_IntrospectorTest');
         $suite->addTestSuite('Zend_Amf_RequestTest');
         $suite->addTestSuite('Zend_Amf_ResponseTest');
         $suite->addTestSuite('Zend_Amf_ServerTest');
@@ -41,4 +43,3 @@ class Zend_Amf_AllTests
 if (PHPUnit_MAIN_METHOD == 'Zend_Amf_AllTests::main') {
     Zend_Amf_AllTests::main();
 }
-?>