/** * Parse class methods annotation and add route * * @param string $class * @param array $meta * @return $this */ public function parse($class, array $meta = []) { $methods = get_class_methods($class); foreach ($methods as $method) { $query = Annotation::ofMethod($class, $method, 'uri'); if ($query) { $this->add($query, [$class, $method], $meta); } } return $this; }
/** * Generate entity from model class * * @param string $class * @return Entity */ public static function of($class) { $reflector = new \ReflectionClass($class); $name = Annotation::ofClass($class, 'entity') ?: strtolower($reflector->getShortName()); $entity = new static($name, $class); $defaults = $reflector->getDefaultProperties(); foreach ($defaults as $property => $default) { $annotations = Annotation::ofProperty($class, $property); $type = !empty($annotations['var']) ? $annotations['var'] : 'string'; $field = new Entity\Field($property, $type); $field->nullable = $default !== null; $field->default = $default; $field->primary = isset($annotations['id']) ?: $property === 'id'; $entity->fields[$property] = $field; } return $entity; }
/** * Create entity * * @param array $specs * @return bool */ public function create(array $specs = []) { // read class specs if (!$specs and $this->class) { $reflector = new \ReflectionClass($this->class); $defaults = $reflector->getDefaultProperties(); foreach ($defaults as $property => $default) { $annotations = Annotation::ofProperty($this->class, $property); $specs[$property] = ['type' => !empty($annotations['var']) ? $annotations['var'] : 'string', 'nullable' => $default !== null, 'default' => $default, 'primary' => isset($annotations['id']) ?: $property === 'id']; } } else { foreach ($specs as $field => &$opts) { $opts += ['type' => 'string', 'nullable' => true, 'default' => null, 'primary' => $field === 'i']; if (isset($this->types[$opts['type']])) { $opts['type'] = $this->types[$opts['type']]; } } } $sql = $this->compiler->createTable($this->name, $specs); return $this->pdo->query($sql); }