Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

GridFS Problem #15

Open
marcoberri opened this Issue · 7 comments

5 participants

Marco Berri Pablo Díez Haykel Ben Jemia Christian Bruce Doan
Marco Berri

HI,

for example i see http://mandango.org/doc/mandango/grid-fs.html

my object is :

array(
'CommonsFile' => array(
'isFile' => true,
'collection' => 'Commons_File',
'fields' => array(
'name' => 'string',
),
),
);

php code:

            $file = $mandango->create('CommonsFile');
            $file->setFile("/usr/local/data/sample/pdf2.pdf");
            $file->setName("New File");
            $file->save();

log:

[error] [client 192.168.0.200] PHP Fatal error: Call to undefined
method CommonsFile::setFile()

tnx

Pablo Díez
Owner

The tests are passing. Could you provide more information to reproduce the bug?

Marco Berri
    this is the code: (the connection on ReplicaSet )

$connection = new Connection('mongodb://mongodb1:27017,mongodb2:27017,mongodb3:27017', 'test');

        $mondator = new Mondator();
        $mondator->setConfigClasses(
                                    array(
                                            'CommonsFile' => array(
                                                                    'isFile' => true,
                                                                    'collection' => 'Commons_File',
                                                                    'fields' => array(
                                                                        'name' => 'string',
                                                                    )
                                                                )
                                    )
        );


        $modelDir = '/usr/local/customers/test/mandango';

        if(!file_exists($modelDir))
            mkdir($modelDir);

        set_include_path(get_include_path() . PATH_SEPARATOR . $modelDir);
        set_include_path(get_include_path() . PATH_SEPARATOR . $modelDir.'/Base');

        $mappingDir = '/usr/local/customers/test/mandango_cache';
        if(!file_exists($mappingDir))
            mkdir($mappingDir); 

        set_include_path(get_include_path() . PATH_SEPARATOR . $mappingDir);



        $mondator->setExtensions(array(
            new Core(array(
                'metadata_factory_class' => 'MetadataFactory',
                'metadata_factory_output' => $mappingDir,
                'default_output'         => $modelDir,
            )),
        ));

        $result = $mondator->process();


        $metadataFactory = new MetadataFactory();
        $mandango = new Mandango($metadataFactory, $cache);

        $mandango->setConnection('my_connection', $connection);
        $mandango->setDefaultConnectionName('my_connection');

        $file = $mandango->create('CommonsFile');
        $file->setFile("/usr/local/data/sample/pdf2.pdf");
        $file->setName("New File");
        $file->save();

error is:

PHP Fatal error: Call to undefined method CommonsFile::setFile() in /....../Mandango.php on line 125 (is my class)

Pablo Díez
Owner

Have you regenerated the model after modifying the schema? It's weird the method hasn't been generated.

Marco Berri

yes, this is the class

ps.

in all class the tag php is not closed..

<?php

/**

  • CommonsFile document. */ class CommonsFile extends \BaseCommonsFile { }

<?php

/**

  • Query of CommonsFile document. */ class CommonsFileQuery extends \BaseCommonsFileQuery { }

<?php

/**

  • Repository of CommonsFile document. */ class CommonsFileRepository extends \BaseCommonsFileRepository { }

<?php

/**

  • Base class of CommonsFile document.
    /
    abstract class BaseCommonsFile extends \Mandango\Document\Document
    {
    /
    *

    • Initializes the document defaults. */ public function initializeDefaults() { }

    /**

    • Set the document data (hydrate). *
    • @param array $data The document data.
    • @param bool $clean Whether clean the document. *
    • @return CommonsFile The document (fluent interface).
      */
      public function setDocumentData($data, $clean = false)
      {
      if ($clean) {
      $this->data = array();
      $this->fieldsModified = array();
      }

      if (isset($data['_query_hash'])) {
      $this->addQueryHash($data['_query_hash']);
      }
      if (isset($data['_id'])) {
      $this->setId($data['_id']);
      $this->setIsNew(false);
      }
      if (isset($data['name'])) {
      $this->data['fields']['name'] = (string) $data['name'];
      } elseif (isset($data['_fields']['name'])) {
      $this->data['fields']['name'] = null;
      }

      return $this;
      }

    /**

    • Set the "name" field. *
    • @param mixed $value The value. *
    • @return CommonsFile The document (fluent interface).
      */
      public function setName($value)
      {
      if (!isset($this->data['fields']['name'])) {
      if (!$this->isNew()) {
      $this->getName();
      if ($value === $this->data['fields']['name']) {
      return $this;
      }
      } else {
      if (null === $value) {
      return $this;
      }
      $this->fieldsModified['name'] = null;
      $this->data['fields']['name'] = $value;
      return $this;
      }
      } elseif ($value === $this->data['fields']['name']) {
      return $this;
      }

      if (!isset($this->fieldsModified['name']) && !array_key_exists('name', $this->fieldsModified)) {
      $this->fieldsModified['name'] = $this->data['fields']['name'];
      } elseif ($value === $this->fieldsModified['name']) {
      unset($this->fieldsModified['name']);
      }

      $this->data['fields']['name'] = $value;

      return $this;
      }

    /**

    • Returns the "name" field. *
    • @return mixed The $name field.
      */
      public function getName()
      {
      if (!isset($this->data['fields']['name'])) {
      if ($this->isNew()) {
      $this->data['fields']['name'] = null;
      } elseif (!isset($this->data['fields']) || !array_key_exists('name', $this->data['fields'])) {
      $this->addFieldCache('name');
      $data = $this->getRepository()->getCollection()->findOne(array('_id' => $this->getId()), array('name' => 1));
      if (isset($data['name'])) {
      $this->data['fields']['name'] = (string) $data['name'];
      } else {
      $this->data['fields']['name'] = null;
      }
      }
      }

      return $this->data['fields']['name'];
      }

    /**

    • Set a document data value by data name as string. *
    • @param string $name The data name.
    • @param mixed $vaule The value. *
    • @return mixed the data name setter return value. *
    • @throws \InvalidArgumentException If the data name is not valid.
      */
      public function set($name, $value)
      {
      if ('name' == $name) {
      return $this->setName($value);
      }

      throw new \InvalidArgumentException(sprintf('The document data "%s" is not valid.', $name));
      }

    /**

    • Returns a document data by data name as string. *
    • @param string $name The data name. *
    • @return mixed The data name getter return value. *
    • @throws \InvalidArgumentException If the data name is not valid.
      */
      public function get($name)
      {
      if ('name' == $name) {
      return $this->getName();
      }

      throw new \InvalidArgumentException(sprintf('The document data "%s" is not valid.', $name));
      }

    /**

    • Imports data from an array. *
    • @param array $data An array. *
    • @return {$this->class} The document (fluent interface).
      */
      public function fromArray(array $array)
      {
      if (isset($array['name'])) {
      $this->setName($array['name']);
      }

      return $this;
      }

    /**

    • Export the document data to an array. *
    • @param Boolean \$withReferenceFields Whether include the fields of references or not (false by default). *
    • @return array An array with the document data.
      */
      public function toArray($withReferenceFields = false)
      {
      $array = array();

      $array['name'] = $this->getName();

      return $array;
      }

    /**

    • Query for save.
      */
      public function queryForSave()
      {
      $isNew = $this->isNew();
      $query = array();
      $reset = false;

      if (isset($this->data['fields'])) {
      if ($isNew || $reset) {
      if (isset($this->data['fields']['name'])) {
      $query['name'] = (string) $this->data['fields']['name'];
      }
      } else {
      if (isset($this->data['fields']['name']) || array_key_exists('name', $this->data['fields'])) {
      $value = $this->data['fields']['name'];
      $originalValue = $this->getOriginalFieldValue('name');
      if ($value !== $originalValue) {
      if (null !== $value) {
      $query['$set']['name'] = (string) $this->data['fields']['name'];
      } else {
      $query['$unset']['name'] = 1;
      }
      }
      }
      }
      }
      if (true === $reset) {
      $reset = 'deep';
      }

      return $query;
      }
      }

<?php

/**

  • Base class of query of CommonsFile document.
    /
    abstract class BaseCommonsFileQuery extends \Mandango\Query
    {
    /
    *

    • {@inheritdoc}
      */
      public function all()
      {
      $repository = $this->getRepository();
      $mandango = $repository->getMandango();
      $documentClass = $repository->getDocumentClass();
      $identityMap =& $repository->getIdentityMap()->allByReference();
      $isFile = $repository->isFile();

      $fields = array();
      foreach (array_keys($this->getFields()) as $field) {
      if (false === strpos($field, '.')) {
      $fields[$field] = 1;
      continue;
      }
      $f =& $fields;
      foreach (explode('.', $field) as $name) {
      if (!isset($f[$name])) {
      $f[$name] = array();
      }
      $f =& $f[$name];
      }
      $f = 1;
      }

      $documents = array();
      foreach ($this->createCursor() as $id => $data) {
      if (isset($identityMap[$id])) {
      $document = $identityMap[$id];
      $document->addQueryHash($this->getHash());
      } else {
      if ($isFile) {
      $file = $data;
      $data = $file->file;
      $data['file'] = $file;
      }
      $data['_query_hash'] = $this->getHash();
      $data['_fields'] = $fields;

          $document = new $documentClass($mandango);
          $document->setDocumentData($data);
      
          $identityMap[$id] = $document;
      }
      $documents[$id] = $document;
      

      }

      if ($references = $this->getReferences()) {
      $mandango = $this->getRepository()->getMandango();
      $metadata = $mandango->getMetadataFactory()->getClass($this->getRepository()->getDocumentClass());
      foreach ($references as $referenceName) {
      // one
      if (isset($metadata['referencesOne'][$referenceName])) {
      $reference = $metadata['referencesOne'][$referenceName];
      $field = $reference['field'];

              $ids = array();
              foreach ($documents as $document) {
                  if ($id = $document->get($field)) {
                      $ids[] = $id;
                  }
              }
              if ($ids) {
                  $mandango->getRepository($reference['class'])->findById(array_unique($ids));
              }
      
              continue;
          }
      
          // many
          if (isset($metadata['referencesMany'][$referenceName])) {
              $reference = $metadata['referencesMany'][$referenceName];
              $field = $reference['field'];
      
              $ids = array();
              foreach ($documents as $document) {
                  if ($id = $document->get($field)) {
                      foreach ($id as $i) {
                          $ids[] = $i;
                      }
                  }
              }
              if ($ids) {
                  $mandango->getRepository($reference['class'])->findById(array_unique($ids));
              }
      
              continue;
          }
      
          // invalid
          throw new \RuntimeException(sprintf('The reference "%s" does not exist in the class "%s".', $referenceName, $documentClass));
      }
      

      }

      return $documents;
      }
      }

<?php

/**

  • Base class of repository of CommonsFile document.
    /
    abstract class BaseCommonsFileRepository extends \Mandango\Repository
    {
    /
    *

    • {@inheritdoc}
      */
      public function __construct(\Mandango\Mandango $mandango)
      {
      $this->documentClass = 'CommonsFile';
      $this->isFile = true;
      $this->collectionName = 'Commons_File';

      parent::__construct($mandango);
      }

    /**

    • {@inheritdoc}
      */
      public function idToMongo($id)
      {
      if (!$id instanceof \MongoId) {
      $id = new \MongoId($id);
      }

      return $id;
      }

    /**

    • Save documents. *
    • @param mixed $documents A document or an array of documents.
    • @param array $batchInsertOptions The options for the batch insert operation (optional).
    • @param array $updateOptions The options for the update operation (optional).
      */
      public function save($documents, array $batchInsertOptions = array(), array $updateOptions = array())
      {
      $repository = $this;

      if (!is_array($documents)) {
      $documents = array($documents);
      }

      $identityMap =& $this->getIdentityMap()->allByReference();
      $collection = $this->getCollection();

      $inserts = array();
      $updates = array();
      foreach ($documents as $document) {
      if ($document->isNew()) {
      $inserts[spl_object_hash($document)] = $document;
      } else {
      $updates[] = $document;
      }
      }

      // insert
      if ($inserts) {
      $a = array();
      foreach ($inserts as $oid => $document) {
      $a[$oid] = $document->queryForSave();
      $a[$oid]['_id'] = new \MongoId();
      }

      if ($a) {
          $collection->batchInsert($a, $batchInsertOptions);
      
          foreach ($a as $oid => $data) {
              $document = $inserts[$oid];
      
              $document->setId($data['_id']);
              $document->setIsNew(false);
              $document->clearModified();
              $identityMap[(string) $data['_id']] = $document;
          }
      }
      

      }

      // updates
      foreach ($updates as $document) {
      if ($document->isModified()) {
      $query = $document->queryForSave();
      $collection->update(array('_id' => $document->getId()), $query, $updateOptions);
      $document->clearModified();
      }
      }
      }

    /**

    • Delete documents. *
    • @param mixed $documents A document or an array of documents.
      */
      public function delete($documents)
      {
      if (!is_array($documents)) {
      $documents = array($documents);
      }

      $identityMap =& $this->getIdentityMap()->allByReference();

      $ids = array();
      foreach ($documents as $document) {
      $ids[] = $id = $document->getAndRemoveId();
      $document->setIsNew(true);
      unset($identityMap[(string) $id]);
      }

      $this->getCollection()->remove(array('_id' => array('$in' => $ids)));
      }

    /**

    • Ensure the inexes. */ public function ensureIndexes() { } }

Haykel Ben Jemia
hbj commented

Same issue here, GridFS does not work. I could not find any code related to it in the generated model classes or subclasses. Are the Twig templates for GridFS missing?

Christian

Hi all,

I'm also experimenting the same issue. I'm working with Symfony2 + mandango. My schema.yml looks like this

Model\Application:
    fields:
        name: { type: string, validation: [ NotBlank: ~, Type: string] }
    embeddesOne:
        image:
            class: Model\Image
    behaviors:
        - { class: Mandango\Behavior\Timestampable }
        - { class: Mandango\Behavior\Sluggable, options: { fromField: name } }
    events:
        preInsert: [processImage]
        preUpdate: [processImage]

Model\Image:
    isEmbedded: true
    isFile: true

The class generation is OK. But when I try to execute this code on a preInsert callback

$image = $this->getMandango()->create('Model\Image');
$image->setFile($this->getFile()->getRealPath());
$this->setImage($image);

It's throwing the error

Fatal error: Call to undefined method Model\Image::setFile() in Model/Application.php on line 43
Daniel Ripolles dripolles referenced this issue from a commit in dripolles/mandango
Máximo Cuadros mcuadros #15 moderm times arrives 88f9519
Bruce Doan

I stuck with this problem too, any update?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.