public static function injectDependencies($instance) { // inject other instances that are annotated with @Inject $reflection = new ReflectionAnnotatedClass($instance); foreach ($reflection->getProperties() as $property) { if ($property->hasAnnotation('Inject')) { if ($property->getAnnotation('Inject')->value != '') { $dependencyName = $property->getAnnotation('Inject')->value; } else { $dependencyName = $property->name; } $dependencyName = strtolower($dependencyName); self::$dependencies[$dependencyName][] = array($instance, $property->name); } else { if ($property->hasAnnotation('Logger')) { if (@$property->getAnnotation('Logger')->value != '') { $tag = $property->getAnnotation('Logger')->value; } else { $tag = $reflection->name; } $instance->{$property->name} = new LoggerWrapper($tag); } } } foreach (self::$repo as $instanceName => $instance) { if (isset(self::$dependencies[$instanceName]) && !empty(self::$dependencies[$instanceName])) { foreach (self::$dependencies[$instanceName] as $injection) { list($injectObject, $injectVariable) = $injection; $injectObject->{$injectVariable} = $instance; } unset(self::$dependencies[$instanceName]); } } }
public function testReflectionAnnotatedClass() { $reflection = new ReflectionAnnotatedClass('Example'); $this->assertTrue($reflection->hasAnnotation('FirstAnnotation')); $this->assertTrue($reflection->hasAnnotation('SecondAnnotation')); $this->assertFalse($reflection->hasAnnotation('NonExistentAnnotation')); $this->assertIsA($reflection->getAnnotation('FirstAnnotation'), 'FirstAnnotation'); $this->assertIsA($reflection->getAnnotation('SecondAnnotation'), 'SecondAnnotation'); $annotations = $reflection->getAnnotations(); $this->assertEqual(count($annotations), 2); $this->assertIsA($annotations[0], 'FirstAnnotation'); $this->assertIsA($annotations[1], 'SecondAnnotation'); $this->assertFalse($reflection->getAnnotation('NonExistentAnnotation')); $this->assertIsA($reflection->getConstructor(), 'ReflectionAnnotatedMethod'); $this->assertIsA($reflection->getMethod('exampleMethod'), 'ReflectionAnnotatedMethod'); foreach ($reflection->getMethods() as $method) { $this->assertIsA($method, 'ReflectionAnnotatedMethod'); } $this->assertIsA($reflection->getProperty('exampleProperty'), 'ReflectionAnnotatedProperty'); foreach ($reflection->getProperties() as $property) { $this->assertIsA($property, 'ReflectionAnnotatedProperty'); } foreach ($reflection->getInterfaces() as $interface) { $this->assertIsA($interface, 'ReflectionAnnotatedClass'); } $this->assertIsA($reflection->getParentClass(), 'ReflectionAnnotatedClass'); }
private static function prepareForSerize(\ReflectionAnnotatedClass $reflection, $object, $parent = false) { $hash = spl_object_hash($object); if (in_array($hash, self::$prepared) && $parent == false) { return; } array_push(self::$prepared, $hash); $globalAltered = false; $defaults = null; foreach ($reflection->getProperties() as $property) { $altered = false; $property->setAccessible(true); $value = $property->getValue($object); if (self::isTransient($property)) { $defaults = $defaults == null ? $reflection->getDefaultProperties() : $defaults; $name = $property->getName(); $property->setValue($object, array_key_exists($name, $defaults) ? $defaults[$name] : null); $altered = true; } else { if (is_object($value) && $value instanceof \Closure) { $property->setValue($object, new SerializableClosure($value)); $altered = true; } else { if (is_object($value) && !$value instanceof SerializableClosure && spl_object_hash($value) != $hash) { $valueReflection = new \ReflectionAnnotatedClass($value); $altered = self::prepareForSerize($valueReflection, $value); } else { if (is_array($value)) { $newValue = self::prepareArrayForSerialize($value); if (is_array($newValue)) { $property->setValue($object, $newValue); $altered = true; } } } } } if ($altered) { self::addRestore($property, $object, $value); $globalAltered = true; } } $parent = $reflection->getParentClass(); if ($parent != null) { self::prepareForSerize($parent, $object, true); } if (!$parent) { if ($object instanceof Detachable) { $object->detach(); } } return $globalAltered; }
private function reflectClass ( $class_name ) { require_once $this->file_name; // reflect class $class = new ReflectionAnnotatedClass( $class_name ); // reflect @DefinitionObject if ( $class_annotation = $class->getAnnotation( 'DefinitionObject' ) ) { // set table $table = new DefinitionObject; $table->table = $class_annotation->table; $this->setTable( $class->getName(), $table ); unset( $table ); if ( isset( $class_annotation->build ) && $class_annotation->build ) { $this->build = $class_annotation->build; } // iterate properties foreach ( $class->getProperties() as $property ) { $ref_col = $property->getAnnotation( 'DefinitionObject' ); // create column $column = new DefinitionObject; $column->column = $ref_col->column; $column->type = $ref_col->type; $column->size = $ref_col->size; $column->scale = $ref_col->scale; $column->default = $ref_col->default; $column->required = $ref_col->required; $column->autoIncrement = $ref_col->autoIncrement; $column->primaryKey = $ref_col->primaryKey; $column->index = $ref_col->index; $column->unique = $ref_col->unique; // reflect @ReferenceDef if ( $ref_ref = $property->getAnnotation( 'ReferenceDef' ) ) { // create reference $ref = new ReferenceDef(); $ref->table = $ref_ref->table; $ref->column = $ref_ref->column; $ref->onUpdate = $ref_ref->onUpdate; $ref->onDelete = $ref_ref->onDelete; } // set column string $this->setColumn( $property->getName(), $column, isset( $ref ) ? $ref : false ); unset( $ref ); unset( $column ); } } }
public function generate($entity) { $classe = get_class($entity); $reflectionClass = new ReflectionAnnotatedClass($classe); $tabela = $reflectionClass->getAnnotation('Table')->value; $propriedades = $reflectionClass->getProperties(); foreach ($propriedades as $propriedade) { if ($propriedade->hasAnnotation('Column')) { $getter = $propriedade->name; $key = $propriedade->getAnnotation('Column')->name; $params = (array) $propriedade->getAnnotation('Column'); foreach ($params as $chave => $valor) { $fields[$key][$chave] = $valor; } } if ($propriedade->hasAnnotation('Join')) { $params = (array) $propriedade->getAnnotation('Join'); foreach ($params as $chave => $valor) { $fields[$key][$chave] = $valor; } } } $script = "DROP TABLE IF EXISTS " . SCHEMA . $tabela . "; \n" . "CREATE TABLE " . SCHEMA . $tabela . " ( \n"; $uid; foreach ($fields as $key => $value) { $fk; if (isset($value['joinTable'])) { $fk = "\tCONSTRAINT " . $tabela . "_" . $value['joinTable'] . "_fk FOREIGN KEY({$key})\n"; $fk .= "\t\tREFERENCES " . SCHEMA . $value['joinTable'] . "({$value['joinColumn']}) MATCH SIMPLE\n"; $fk .= "\t\tON UPDATE NO ACTION ON DELETE NO ACTION,\n"; $script .= "\t" . $key . " integer, \n"; } else { if ($key == 'id') { $script .= "\t" . $key . " serial NOT NULL, \n"; $uid = $key; } else { $script .= "\t" . $key . " " . ($value['type'] == 'integer' ? 'integer' : ($value['type'] == 'timestamp' ? 'timestamp' : 'character varying')) . ", \n"; } } } $script .= @$fk; $script .= "\tCONSTRAINT " . $tabela . "_pk PRIMARY KEY (" . $uid . ") \n"; return $script . " );\n\n -- \n"; }
public function findPks($className) { $reflection = new ReflectionAnnotatedClass($className); // by class name $properties = $reflection->getProperties(); $atributes_column = array(); if (count($properties) > 0) { foreach ($properties as $key => $property) { $reflectionAnotatedProperty = new ReflectionAnnotatedProperty($className, $property->getName()); $Key = $reflectionAnotatedProperty->getAnnotation('Column')->Key; if (strlen($Key) > 0 && $Key == "PRI") { $atributes_column[] = (string) $reflectionAnotatedProperty->getAnnotation('Column')->Field; } } } if (count($atributes_column) > 0) { return $atributes_column; } throw new Exception('La clase ' . $className . " no tiene definidas llaves"); }
/** * @param type $object */ public function inject(&$object, $reflection = null) { if ($reflection == null) { $reflection = new \ReflectionAnnotatedClass($object); } $properties = $reflection->getProperties(); foreach ($properties as $property) { if ($property->hasAnnotation("Resource")) { $annotation = $property->getAnnotation("Resource"); $resource = $property->getName(); if (!empty($annotation->name)) { $resource = $annotation->name; } $property->setAccessible(true); $property->setValue($object, $this->context->getResource($resource)); } } $parent = $reflection->getParentClass(); if ($parent != null) { $this->inject($object, $parent); } }
/** * * @param String $filename réal path of the php file to scan ex: /home/project/src/org/foo/bar.php * @param String $namespace the name space of this file ex: org\foo * @return void * @throws IocException */ protected function scanFile($filename, $namespace) { if (!is_file($filename)) { \org\equinox\utils\Logger::error("({$filename}) is not a file!"); throw new IocException("({$filename}) is not a file!"); } include_once $filename; $name = basename($filename); $className = $namespace . '\\' . substr($name, 0, strpos($name, '.')); if (class_exists($className)) { $ref = new \ReflectionAnnotatedClass($className); $listAnnotation = $ref->getAllAnnotations(); if (empty($listAnnotation)) { return; // this class is not a Component ! } $bean = new BeanDefinition(); $bean->setClassName($className); foreach ($listAnnotation as $annotation) { if ($annotation instanceof annotations\ClassAnnotation) { $annotation->doBean($bean, $className); } } if ($bean->getId() == null) { throw new IocException("Equinox annotation found but no @Component annotation found (mandatory) in {$className}"); } $listProperties = $ref->getProperties(); foreach ($listProperties as $property) { $this->doProperty($bean, $property); } $listMethod = $ref->getMethods(); foreach ($listMethod as $method) { $this->doMethod($bean, $method); } $this->context->addBeanDefinition($bean); } }
public function testReflectionClassShouldReturnAllPropertiesWithNoFilter() { $reflection = new ReflectionAnnotatedClass('Example'); $properties = $reflection->getProperties(); $this->assertEqual(count($properties), 2); }
/** * Creates a schema.xml file based in Database Definition objects * * @param TlalokesRegistry $reg */ private static function buildSchemaFromDefs(TlalokesRegistry &$reg) { // static flags static $uniques = 0; static $indexes = 0; // build database xml dom object $dom = new DOMDocument('1.0', 'utf-8'); $dom->formatOutput = true; $db = $dom->appendChild(new DOMElement('database')); $db->setAttribute('name', $reg->conf['dsn']['name']); // find table definitions foreach (glob($reg->conf['path']['app'] . $reg->conf['path']['def'] . '*Def.php') as $def) { // get class name $class_name = preg_replace('/.*\\/(\\w*Def).php$/', '$1', $def); // reflect annotated class $ref = new ReflectionAnnotatedClass($class_name); // check if @DefinitonObject is set if (!$ref->hasAnnotation('DefinitionObject')) { tlalokes_error_msg('PropelFactory: There is no DefinitionObject in ' . $class_name); } // check if object is marked for build if ($ref->getAnnotation('DefinitionObject')->build) { // build xml table node $table = $db->appendChild(new DOMElement('table')); // set table name attribute $table_name = $ref->getAnnotation('DefinitionObject')->table; $table->setAttribute('name', $table_name); unset($table_name); $table->setAttribute('idMethod', 'native'); // find columns foreach ($ref->getProperties() as $property) { // reflect column $column = $property->getAnnotation('DefinitionObject'); // build xml column nodes $col = $table->appendChild(new DOMElement('column')); // name $col->setAttribute('name', $column->column); // phpName if ($property->getName() != $column->column) { $col->setAttribute('phpName', (string) $property->getName()); } // type $col->setAttribute('type', $column->type); // size if ($column->size) { $col->setAttribute('size', $column->size); } // scale if ($column->scale) { $col->setAttribute('scale', $column->scale); } // required if ($column->required) { $col->setAttribute('required', $column->required ? 'true' : 'false'); } // autoIncrement if ($column->autoIncrement) { $col->setAttribute('autoIncrement', $column->autoIncrement ? 'true' : 'false'); // If RBDMS is PgSQL and there is no default set the default // WARNING: It needs to be tested with Oracle if ($reg->conf['dsn']['type'] == 'pgsql') { // build id-method-parameter $imp_name = 'id-method-parameter'; $imp = $table->appendChild(new DOMElement($imp_name)); $imp->setAttribute('value', $table_name . '_seq'); // set default if (!isset($column->default)) { $col->setAttribute('default', 'nextval(\'' . $table_name . '_seq\'::regclass)'); } } } // primaryKey if ($column->primaryKey) { $col->setAttribute('primaryKey', $column->primaryKey ? 'true' : 'false'); } // default if ($column->default || $column->default === 0) { $col->setAttribute('default', tlalokes_core_get_type($column->default)); } // find unique if (isset($column->unique) && $column->unique) { if (isset($uniques)) { $uniques++; } else { $uniques = 1; } $unique_column_name[] = $column->column; } // find index if (isset($column->index) && $column->index) { $indexes = isset($indexes) ? $indexes + 1 : 1; $index_column_name[] = $column->column; } // find reference $reference = $property->getAnnotation('ReferenceDef'); if ($reference) { // build foreign-key xml node $fk = $table->appendChild(new DOMElement('foreign-key')); $fk->setAttribute('foreignTable', $reference->table); $fk->setAttribute('onDelete', strtolower($reference->onDelete)); $fk->setAttribute('onUpdate', strtolower($reference->onUpdate)); $rf = $fk->appendChild(new DOMElement('reference')); $rf->setAttribute('local', $column->column); $rf->setAttribute('foreign', $reference->column); } } // find uniques flag if (isset($uniques) && $uniques >= 1) { if (isset($unique_column_name)) { foreach ($unique_column_name as $ucn) { // build unique xml node $unique = $table->appendChild(new DOMElement('unique')); // build unique-column xml node $uc = $unique->appendChild(new DOMElement('unique-column')); $uc->setAttribute('name', $ucn); } unset($unique_column_name); } unset($uniques); } // find indexes flag if (isset($indexes) && $indexes >= 1) { foreach ($index_column_name as $icn) { // build index xml node $index = $table->appendChild(new DOMElement('index')); // build index-column xml node $ic = $index->appendChild(new DOMElement('index-column')); $ic->setAttribute('name', $icn); } unset($indexes); unset($index_column_name); } } // set file path to schema.xml $file = $reg->conf['path']['app'] . $reg->conf['path']['tmp'] . 'generator/schema.xml'; // write schema.xml file or return a CoreException if (!@file_put_contents($file, $dom->saveXML())) { tlalokes_error_msg('Propel: Cannot write database schema', true); } } }
public function registerInstance($MODULE_NAME, $name, &$obj) { $name = strtolower($name); $this->logger->log('DEBUG', "Registering instance name '{$name}' for module '{$MODULE_NAME}'"); if (Registry::instanceExists($name)) { $this->logger->log('WARN', "Instance with name '{$name}' already registered--replaced with new instance"); } $obj->moduleName = $MODULE_NAME; Registry::setInstance($name, $obj); // register settings annotated on the class $reflection = new ReflectionAnnotatedClass($obj); foreach ($reflection->getProperties() as $property) { if ($property->hasAnnotation('Setting')) { $this->settingManager->add($MODULE_NAME, $property->getAnnotation('Setting')->value, $property->getAnnotation('Description')->value, $property->getAnnotation('Visibility')->value, $property->getAnnotation('Type')->value, $obj->{$property->name}, @$property->getAnnotation('Options')->value, @$property->getAnnotation('Intoptions')->value, @$property->getAnnotation('AccessLevel')->value, @$property->getAnnotation('Help')->value); } } // register commands, subcommands, and events annotated on the class $commands = array(); $subcommands = array(); foreach ($reflection->getAllAnnotations() as $annotation) { if ($annotation instanceof DefineCommand) { if (!$annotation->command) { $this->logger->log('WARN', "Cannot parse @DefineCommand annotation in '{$name}'."); } $command = $annotation->command; $definition = array('channels' => $annotation->channels, 'defaultStatus' => $annotation->defaultStatus, 'accessLevel' => $annotation->accessLevel, 'description' => $annotation->description, 'help' => $annotation->help, 'handlers' => array()); list($parentCommand, $subCommand) = explode(" ", $command, 2); if ($subCommand) { $definition['parentCommand'] = $parentCommand; $subcommands[$command] = $definition; } else { $commands[$command] = $definition; } // register command alias if defined if ($annotation->alias) { $this->commandAlias->register($MODULE_NAME, $command, $annotation->alias); } } } foreach ($reflection->getMethods() as $method) { if ($method->hasAnnotation('Setup')) { $this->setupHandlers[] = array($name, $method->name); } else { if ($method->hasAnnotation('HandlesCommand')) { $commandName = $method->getAnnotation('HandlesCommand')->value; $methodName = $method->name; $handlerName = "{$name}.{$method->name}"; if (isset($commands[$commandName])) { $commands[$commandName]['handlers'][] = $handlerName; } else { if (isset($subcommands[$commandName])) { $subcommands[$commandName]['handlers'][] = $handlerName; } else { $this->logger->log('WARN', "Cannot handle command '{$commandName}' as it is not defined with @DefineCommand in '{$name}'."); } } } else { if ($method->hasAnnotation('Event')) { $this->eventManager->register($MODULE_NAME, $method->getAnnotation('Event')->value, $name . '.' . $method->name, @$method->getAnnotation('Description')->value, @$method->getAnnotation('Help')->value, @$method->getAnnotation('DefaultStatus')->value); } } } } foreach ($commands as $command => $definition) { $this->commandManager->register($MODULE_NAME, $definition['channels'], implode(',', $definition['handlers']), $command, $definition['accessLevel'], $definition['description'], $definition['help'], $definition['defaultStatus']); } foreach ($subcommands as $subCommand => $definition) { $this->subcommandManager->register($MODULE_NAME, $definition['channels'], implode(',', $definition['handlers']), $subCommand, $definition['accessLevel'], $definition['parentCommand'], $definition['description'], $definition['help'], $definition['defaultStatus']); } }
public function parse() { $map = array(); $map['time'] = $this->getModificationTime(); $map['fields'] = array(); $map['relations'] = array(); // pegando as anotacoes da classe $ref = new ReflectionAnnotatedClass($this->getClassname()); if (!$ref->hasAnnotation('LumineEntity')) { return; } $map['package'] = $ref->getAnnotation('LumineEntity')->package; if ($ref->hasAnnotation('LumineTable')) { $map['tablename'] = $ref->getAnnotation('LumineTable')->name; } else { $map['tablename'] = strtolower($this->getClassname()); } // pegando as propriedades $props = $ref->getProperties(); /** @var $prop ReflectionAnnotatedProperty */ foreach ($props as $prop) { if (!$prop->hasAnnotation('LumineTransient')) { if ($prop->hasAnnotation('LumineColumn')) { $anno = $prop->getAnnotation('LumineColumn'); if ($prop->hasAnnotation('LumineId')) { $anno->options['primary'] = true; } if ($prop->hasAnnotation('LumineManyToOne')) { $mto = $prop->getAnnotation('LumineManyToOne'); $anno->options['class'] = $mto->class; $anno->options['linkOn'] = $mto->linkOn; $anno->options['onUpdate'] = $mto->onUpdate; $anno->options['onDelete'] = $mto->onDelete; $anno->options['lazy'] = $mto->lazy; $anno->options['foreign'] = true; } if (empty($anno->name)) { $anno->name = $prop->getName(); } if (empty($anno->column)) { $anno->column = $prop->getName(); } $map['fields'][] = array($anno->name, $anno->column, $anno->type, $anno->length, empty($anno->options) ? array() : $anno->options); } else { if ($prop->hasAnnotation('LumineManyToMany')) { $anno = $prop->getAnnotation('LumineManyToMany'); if (empty($anno->name)) { $anno->name = $prop->getName(); } $map['relations'][] = array($anno->name, Lumine_Metadata::MANY_TO_MANY, $anno->class, $anno->linkOn, $anno->table, $anno->column, $anno->lazy); } else { if ($prop->hasAnnotation('LumineOneToMany')) { $anno = $prop->getAnnotation('LumineOneToMany'); if (empty($anno->name)) { $anno->name = $prop->getName(); } $map['relations'][] = array($anno->name, Lumine_Metadata::ONE_TO_MANY, $anno->class, $anno->linkOn, null, null, $anno->lazy); } else { if ($prop->getDeclaringClass()->getName() == $this->getClassname()) { $map['fields'][] = array($prop->getName(), $prop->getName(), 'varchar', 255, array()); } } } } } } return $map; }