예제 #1
0
    /**
     * {@inheritdoc}
     */
    protected function doClassProcess()
    {
        $field = $this->getOption('field');
        $fromFields = $this->getOption('fromFields');
        if (count($fromFields) == 0) {
            $fromFields = array_diff(array_merge(array_keys($this->configClass['fields']), array_keys($this->configClass['embeddedsOne']), array_keys($this->configClass['embeddedsMany'])), array($field));
            $this->setOption('fromFields', $fromFields);
        }
        // field
        $this->configClass['fields'][$field] = array('type' => 'string');
        // document ->updateHashableHash()
        $this->processTemplate($this->definitions['document_base'], file_get_contents(__DIR__ . '/templates/HashableDocument.php.twig'));
        // repository ->findOneByHash()
        $method = new Method('public', 'findByHash', '$hash', <<<EOF

        return \$this->createQuery(array('{$field}' => \$hash))->one();
EOF
);
        $method->setDocComment(<<<EOF
    /**
     * Returns a document by hash.
     *
     * @param string \$hash The hash.
     *
     * @return mixed The document or null if it does not exist.
     */
EOF
);
        $this->definitions['repository_base']->addMethod($method);
    }
    /**
     * @return Method
     */
    public function create()
    {
        $arguments = [];
        $code = '';
        $docComment = <<<EOF
    /**
     * {$this->className} entity constructor
     *

EOF;
        /** @var Variable $variable */
        foreach ($this->variableCollection as $variable) {
            if ($variable->isScalarType() || $variable->isUnknownType()) {
                $arguments[] = '$' . $variable->getName();
            } else {
                $arguments[] = $variable->getType() . ' $' . $variable->getName();
            }
            $code .= <<<EOF
        \$this->{$variable['name']} = \${$variable['name']};

EOF;
            $ucName = ucfirst($variable['name']);
            $docComment .= <<<EOF
     * @param {$variable['type']} \${$variable['name']} {$ucName} value

EOF;
        }
        $constructor = new Method('public', '__construct', implode(', ', $arguments), $code);
        $constructor->setDocComment($docComment . <<<EOF
     */
EOF
);
        return $constructor;
    }
예제 #3
0
    /**
     * {@inheritdoc}
     */
    protected function doClassProcess()
    {
        $field = $this->getOption('field');
        $length = $this->getOption('length');
        // field
        $this->configClass['fields'][$field] = array('type' => 'string');
        // index
        $this->configClass['indexes'][] = array('keys' => array($field => 1), 'options' => array('unique' => 1));
        // event
        $fieldSetter = 'set' . ucfirst($field);
        $method = new Method('public', 'updateTokenizableToken', '', <<<EOF
        do {
            \$token = '';
            for (\$i = 1; \$i <= {$length}; \$i++) {
                \$token .= substr(sha1(microtime(true).mt_rand(111111, 999999)), mt_rand(0, 39), 1);
            };

            \$result = \$this->getRepository()->getCollection()->findOne(array('{$field}' => \$token));
        } while (\$result);

        \$this->{$fieldSetter}(\$token);
EOF
);
        $this->definitions['document_base']->addMethod($method);
        // repository ->findOneBytoken()
        $method = new Method('public', 'findByToken', '$token', <<<EOF

        return \$this->createQuery(array('{$field}' => \$token))->one();
EOF
);
        $method->setDocComment(<<<EOF
    /**
     * Returns a document by token.
     *
     * @param string \$token The token.
     *
     * @return mixed The document or null if it does not exist.
     */
EOF
);
        $this->definitions['repository_base']->addMethod($method);
    }
예제 #4
0
    protected function process__getMethod()
    {
        $method = new Method('public', '__get', '$name', <<<EOF
        return \$this->get(\$name);
EOF
);
        $method->setDocComment(<<<EOF
    /**
     * Returns data of the entity.
     *
     * @param string \$name The data name.
     *
     * @return mixed Some data.
     *
     * @see get()
     */
EOF
);
        $this->definitions['entity_base']->addMethod($method);
    }
예제 #5
0
    protected function processSortableSetPositionMethod()
    {
        $positionAsNew = 'top' == $this->getOption('new_position') ? '1' : '$maxPosition + 1';
        $method = new Method('public', 'sortableSetPosition', '', <<<EOF
        \$maxPosition = static::repository()->getMaxPosition();

        if (\$this->isNew()) {
            \$position = {$positionAsNew};
        } else {
            \$changeSet = \$this->changeSet();
            if (!isset(\$changeSet['{$this->column}'])) {
                return;
            }
            \$oldPosition = \$changeSet['{$this->column}'][0];
            \$position    = \$changeSet['{$this->column}'][1];
        }

        \$this->{$this->columnSetter}(\$position);

        // move entities
        if (\$this->isNew()) {
            \$query = 'UPDATE {$this->class} s SET s.{$this->column} = s.{$this->column} + 1 WHERE s.{$this->column} >= ?1';
            \$query = static::entityManager()->createQuery(\$query);
            \$query->setParameter(1, \$position);
        } else {
            \$sign = \$position > \$oldPosition ? '-' : '+';
            \$query = "UPDATE {$this->class} s SET s.{$this->column} = s.{$this->column} \$sign 1 WHERE s.{$this->column} BETWEEN ?1 AND ?2";
            \$query = static::entityManager()->createQuery(\$query);
            \$query->setParameter(1, min(\$position, \$oldPosition));
            \$query->setParameter(2, max(\$position, \$oldPosition));
        }

        \$query->execute();
EOF
);
        $method->setDocComment(<<<EOF
    /**
     * Set the position.
     */
EOF
);
        $this->definitions['entity_base']->addMethod($method);
    }
예제 #6
0
    /**
     * {@inheritdoc}
     */
    protected function doClassProcess()
    {
        // field
        $slugField = $this->getOption('slugField');
        // update slug
        $fromField = $this->getOption('fromField');
        $fromFieldCamelized = ucfirst($fromField);
        $slugFieldCamelized = ucfirst($slugField);
        $builder = var_export($this->getOption('builder'), true);
        $uniqueCode = '';
        if ($this->getOption('unique')) {
            $uniqueCode = <<<EOF
        \$similarSlugs = array();
        foreach (\$this->getRepository()->getCollection()
            ->find(array('{$slugField}' => new \\MongoRegex('/^'.\$slug.'/')))
        as \$result) {
            \$similarSlugs[] = \$result['{$slugField}'];
        }

        \$i = 1;
        while (in_array(\$slug, \$similarSlugs)) {
            \$slug = \$proposal.'-'.++\$i;
        }
EOF;
        }
        $method = new Method('protected', 'updateSluggableSlug', '', <<<EOF
        \$slug = \$proposal = call_user_func({$builder}, \$this->get{$fromFieldCamelized}());

{$uniqueCode}

        \$this->set{$slugFieldCamelized}(\$slug);
EOF
);
        $this->definitions['document_base']->addMethod($method);
        // repository ->findOneBySlug()
        $method = new Method('public', 'findOneBySlug', '$slug', <<<EOF
        return \$this->createQuery(array('{$slugField}' => \$slug))->one();
EOF
);
        $method->setDocComment(<<<EOF
    /**
     * Returns a document by slug.
     *
     * @param string \$slug The slug.
     *
     * @return mixed The document or null if it does not exist.
     */
EOF
);
        $this->definitions['repository_base']->addMethod($method);
    }
예제 #7
0
 /**
  * Twig.
  */
 protected function processTemplate(Definition $definition, $name, array $variables = array())
 {
     $twig = $this->getTwig();
     $variables['options'] = $this->options;
     $variables['class'] = $this->class;
     $variables['config_class'] = $this->configClass;
     $variables['config_classes'] = $this->configClasses;
     $result = $twig->loadTemplate($name)->render($variables);
     // properties
     $expression = '/
         (?P<docComment>\\ \\ \\ \\ \\/\\*\\*\\n[\\s\\S]*\\ \\ \\ \\ \\ \\*\\/)?\\n?
          \\ \\ \\ \\ (?P<static>static\\ )?
         (?P<visibility>public|protected|private)
         \\s
         \\$
         (?P<name>[a-zA-Z0-9_]+)
         ;
     /xU';
     preg_match_all($expression, $result, $matches);
     for ($i = 0; $i <= count($matches[0]) - 1; $i++) {
         $property = new Property($matches['visibility'][$i], $matches['name'][$i], null);
         if ($matches['static'][$i]) {
             $property->setStatic(true);
         }
         if ($matches['docComment'][$i]) {
             $property->setDocComment($matches['docComment'][$i]);
         }
         $definition->addProperty($property);
     }
     // methods
     $expression = '/
         (?P<docComment>\\ \\ \\ \\ \\/\\*\\*\\n[\\s\\S]*\\ \\ \\ \\ \\ \\*\\/)?\\n
         \\ \\ \\ \\ (?P<static>static\\ )?
         (?P<visibility>public|protected|private)
         \\s
         function
         \\s
         (?P<name>[a-zA-Z0-9_]+)
         \\((?P<arguments>[$a-zA-Z0-9_\\\\=\\(\\), ]*)\\)
         \\n
         \\ \\ \\ \\ \\{
             (?P<code>[\\s\\S]*)
         \\n\\ \\ \\ \\ \\}
     /xU';
     preg_match_all($expression, $result, $matches);
     for ($i = 0; $i <= count($matches[0]) - 1; $i++) {
         $code = trim($matches['code'][$i], "\n");
         $method = new Method($matches['visibility'][$i], $matches['name'][$i], $matches['arguments'][$i], $code);
         if ($matches['static'][$i]) {
             $method->setStatic(true);
         }
         if ($matches['docComment'][$i]) {
             $method->setDocComment($matches['docComment'][$i]);
         }
         $definition->addMethod($method);
     }
 }
예제 #8
0
 public function testDocComment()
 {
     $method = new Method('public', 'setVisibility', '$visibility', '$this->visibility = $visibility;');
     $method->setDocComment('myDoc');
     $this->assertSame('myDoc', $method->getDocComment());
 }
    /**
     * {@inheritdoc}
     */
    protected function doClassProcess()
    {
        $validation = array('constraints' => array(), 'getters' => array());
        // constraints
        if (isset($this->configClass['validation'])) {
            $validation['constraints'] = $this->configClass['validation'];
        }
        // getters
        // fields
        foreach ($this->configClass['fields'] as $name => $field) {
            if (empty($field['inherited']) && isset($field['validation']) && $field['validation']) {
                $validation['getters'][$name] = $field['validation'];
            }
        }
        // referencesOne
        foreach ($this->configClass['referencesOne'] as $name => $referenceOne) {
            if (empty($referenceOne['inherited']) && isset($referenceOne['validation']) && $referenceOne['validation']) {
                $validation['getters'][$name] = $referenceOne['validation'];
            }
        }
        // referencesMany
        foreach ($this->configClass['referencesMany'] as $name => $referenceMany) {
            if (empty($referenceMany['inherited']) && isset($referenceMany['validation']) && $referenceMany['validation']) {
                $validation['getters'][$name] = $referenceMany['validation'];
            }
        }
        // embeddedsOne
        foreach ($this->configClass['embeddedsOne'] as $name => $embeddedOne) {
            if (empty($embeddedOne['inherited']) && isset($embeddedOne['validation']) && $embeddedOne['validation']) {
                $validation['getters'][$name] = $embeddedOne['validation'];
            }
        }
        // embeddedsMany
        foreach ($this->configClass['embeddedsMany'] as $name => $embeddedMany) {
            if (empty($embeddedMany['inherited']) && isset($embeddedMany['validation']) && $embeddedMany['validation']) {
                $validation['getters'][$name] = $embeddedMany['validation'];
            }
        }
        $validation = Dumper::exportArray($validation, 12);
        $method = new Method('public', 'loadValidatorMetadata', '\\Symfony\\Component\\Validator\\Mapping\\ClassMetadata $metadata', <<<EOF
        \$validation = {$validation};

        foreach (\\Mandango\\MandangoBundle\\Extension\\DocumentValidation::parseNodes(\$validation['constraints']) as \$constraint) {
            \$metadata->addConstraint(\$constraint);
        }

        foreach (\$validation['getters'] as \$getter => \$constraints) {
            foreach (\\Mandango\\MandangoBundle\\Extension\\DocumentValidation::parseNodes(\$constraints) as \$constraint) {
                \$metadata->addGetterConstraint(\$getter, \$constraint);
            }
        }

        return true;
EOF
);
        $method->setStatic(true);
        $method->setDocComment(<<<EOF
    /**
     * Maps the validation.
     *
     * @param \\Symfony\\Component\\Validator\\Mapping\\ClassMetadata \$metadata The metadata class.
     */
EOF
);
        $this->definitions['document_base']->addMethod($method);
    }
예제 #10
0
    protected function processOffsetUnsetMethod()
    {
        $method = new Method('public', 'offsetUnset', '$name', <<<EOF
        throw new \\LogicException('You cannot unset data in the entity.');
EOF
);
        $method->setDocComment(<<<EOF
    /**
     * Throws a \\LogicException because you cannot unset data in the entity.
     *
     * @throws \\LogicException
     */
EOF
);
        $this->definitions['entity_base']->addMethod($method);
    }
예제 #11
0
    protected function processRepositoryGetTagsWithCountMethod()
    {
        $method = new Method('public', 'getTagsWithCount', '$limit = false', <<<EOF
        \$query = 'SELECT t.tag_id, COUNT(t.tag_id) AS total FROM {$this->class}Tagging t GROUP BY t.tag_id ORDER BY total DESC';
        \$query = \$this->getEntityManager()->createQuery(\$query);
        if (\$limit) {
            \$query->setMaxResults(\$limit);
        }

        \$tagIds = array();
        foreach (\$query->getArrayResult() as \$result) {
            \$tagIds[\$result['tag_id']] = \$result['total'];
        }

        \$tags = array();
        if (\$tagIds) {
            \$query = \$this->getEntityManager()->createQuery('SELECT t FROM {$this->class}Tag t WHERE t.id IN('.implode(', ', array_keys(\$tagIds)).')');
            foreach (\$query->getArrayResult() as \$result) {
                \$tags[\$result['name']] = \$tagIds[\$result['id']];
            }
        }

        return \$tags;
EOF
);
        $method->setDocComment(<<<EOF
    /**
     * Returns tags with count.
     *
     * @return array The tags with count.
     */
EOF
);
        $this->definitions['repository_base']->addMethod($method);
    }
예제 #12
0
파일: Core.php 프로젝트: keeguon/doctrator
    protected function processLoadMetadataMethod()
    {
        $method = new Method('public', 'loadMetadata', '\\Doctrine\\ORM\\Mapping\\ClassMetadata $metadata', implode("\n", $this->loadMetadataCode[$this->class]));
        $method->setStatic(true);
        $method->setDocComment(<<<EOF
    /**
     * Load the metadata.
     *
     * @param \\Doctrine\\ORM\\Mapping\\ClassMetadata \$metadata The metadata class.
     */
EOF
);
        $this->definitions['entity_base']->addMethod($method);
    }
예제 #13
0
    /**
     * @inheritdoc
     */
    protected function doClassProcess()
    {
        // "translation" method
        $method = new Method('public', 'translation', '$locale', <<<EOF
        foreach (\$this->getTranslations() as \$translation) {
            if (\$translation->getLocale() == \$locale) {
                return \$translation;
            }
        }

        \$translation = new \\{$this->class}Translation();
        \$translation->setParent(\$this);
        \$translation->setLocale(\$locale);

        \$this->getTranslations()->add(\$translation);

        return \$translation;
EOF
);
        $method->setDocComment(<<<EOF
    /**
     * Returns a translation entity by locale.
     *
     * @param string \$locale The locale.
     *
     * @return \\{{$this->class}}Translation The translation entity.
     */
EOF
);
        $this->definitions['entity_base']->addMethod($method);
    }
예제 #14
0
    protected function processDeleteMethod()
    {
        $method = new Method('public', 'delete', '', <<<EOF
        \$this->checkEntityManagerIsClear();

        \$em = static::entityManager();

        \$em->remove(\$this);
        \$em->flush();
EOF
);
        $method->setDocComment(<<<EOF
    /**
     * Delete the entity.
     */
EOF
);
        $this->definitions['entity_base']->addMethod($method);
    }
예제 #15
0
    /**
     * {@inheritdoc}
     */
    protected function doClassProcess()
    {
        // field
        $slugField = $this->getOption('slugField');
        $this->processTemplate($this->definitions['document_base'], file_get_contents(__DIR__ . '/templates/SluggableDocument.php.twig'));
        // repository ->findOneBySlug()
        $method = new Method('public', 'findOneBySlug', '$slug', <<<EOF

        return \$this->createQuery(array('{$slugField}' => \$slug))->one();
EOF
);
        $method->setDocComment(<<<EOF
    /**
     * Returns a document by slug.
     *
     * @param string \$slug The slug.
     *
     * @return mixed The document or null if it does not exist.
     */
EOF
);
        $this->definitions['repository_base']->addMethod($method);
    }
예제 #16
0
    private function createSetter($name, $type)
    {
        $ucName = ucfirst($name);
        $setter = new Method('public', 'set' . $ucName, '$value', <<<EOF
        \$this->{$name} = \$value;
EOF
);
        $setter->setDocComment(<<<EOF
    /**
     * Set {$ucName} value
     *
     * @param {$type} \$name {$ucName} value to set
     */
EOF
);
        return $setter;
    }