Save a document

@param array $data
@throws \Exception
@return \Neobazaar\Entity\Document
188568
public function save(array $data)
    {
		// All the services we need
		$main = $this->getServiceLocator()->get('neobazaar.service.main');
		$em = $main->getEntityManager();
		$documentRepository = $main->getDocumentEntityRepository();
		$userRepository = $main->getUserEntityRepository();
		$locationRepository = $main->getGeonamesEntityRepository();
		$cache = $this->getServiceLocator()->get('ClassifiedCache');
		$auth = $this->getServiceLocator()->get('ControllerPluginManager')->get('zfcUserAuthentication');
		$form = $this->getServiceLocator()->get('document.form.classifiedadd');
		
		$user = isset($data['user']) && is_array($data['user']) ? $data['user'] : null;
		$userId = null !== $user && isset($user['id']) ? $user['id'] : null;
		$email = isset($user['email']) ? $user['email'] : null;
		$name = isset($user['name']) ? $user['name'] : null;
		
		$document = isset($data['document']) && is_array($data['document']) ? $data['document'] : null;
		$documentId = null !== $document && isset($document['id']) ? $document['id'] : null;

		$children = isset($document["children"]) && is_array($document['children']) ? 
			$document["children"] : array();
		$metadata = isset($document['metadata']) && is_array($document['metadata']) ? 
			$document['metadata'] : array();
		
		$location = null;
		$locationUrl = isset($document["location"]) ? $document["location"] : null;
		
		if(null === $document) {
			throw new \Exception('Trying to save an empty document');
		}
		
		$data["document"]["documentType"] = Document::DOCUMENT_TYPE_CLASSIFIED;
		
		foreach($children as $k => $child) {
			if(!isset($child["content"])) {
				continue;
			}
			$image = $documentRepository->findByEncryptedId(
				$child["content"],
				'documentId'
			);
			unset($data["document"]["children"][$k]["content"]);
			$data["document"]["children"][$k]["documentId"] = $image->getDocumentId();
			$data["document"]["children"][$k]["documentType"] = Document::DOCUMENT_TYPE_IMAGE;
		}
		
		if(null !== $userId) {
			$repo = $main->getUserEntityRepository();
			$user = $repo->findByEncryptedId($userId, 'userId');
		} elseif(null !== $email) {
			$user = $userRepository->findOneBy(array('email' => $email));
			if(null === $user) {
				// @todo: validate email before insert
				$userService = $this->getServiceLocator()->get('user.service.user');
				
				// This was previously called $data and nothing worked, wonder why??
				$userdata = array();
				// This ws will take only CREATION of user, state will be always DEACTIVE
				$userdata['state'] = UserEntity::USER_STATE_DEACTIVE;
				// Edit these in the future for nicer localization and authorization
				$userdata['locale'] = 'it_IT';
				$userdata['role'] = 'guest';
				$userdata['email'] = $email;
				$userdata['name'] = $name;
				
				// This is necessary for validation
				$userdata['agreeterms'] = 1;
				$userdata['surname'] = $name;
					
				try {
					$user = $userService->save($userdata, false); // second arg for NOT to trigger event
				} catch(\Exception $e) {}
			}
		}
		
		$theUserId = $user instanceof UserEntity ? $user->getUserId() : null;
		$data["document"] = array_merge($data["document"], array('user' => $theUserId));
		
		$data["user"] = array(
			'name' => $name,
			'email' => $email
		);
		
		foreach($metadata as $meta) {
			if(isset($meta['key']) && 'comune' == $meta['key']) {
				$location = isset($meta['value']) && !empty($meta['value']) ? $meta['value'] : null;
				$location = $locationRepository->findOneBy(array('url' => $location));
				$data["document"]["geoname"] = $location ? $location->getGeonameId() : '';
				break;
			}
		}
		
		if (isset($document["location"]) && null === $location && null !== $locationUrl) {
			$location = $locationRepository->findOneBy(array('url' => $locationUrl));
			$data["document"]["geoname"] = $location instanceof GeonamesEntity
				? $location->getGeonameId() : '';
		}
		
		// @todo: get from a service
		if(null === $documentId) {
			$entity = new Document();
		} else {
			$repo = $main->getDocumentEntityRepository();
			$entity = $repo->findByEncryptedId($documentId, 'documentId');
		}
    	
		if(null === $documentId) {
			$data["document"]["state"] = $auth->hasIdentity() ? 
				Document::DOCUMENT_STATE_ACTIVE : Document::DOCUMENT_STATE_DEACTIVE;
		} else {
			$data["document"]["state"] = $entity->getState();
		}
		
		// checking for permission, only if we are in edit mode
		if(!$this->checkIfOwnerOrAdmin($entity) && null !== $documentId) {
			throw new \Exception('Non possiedi i permessi per agire su questo documento');
		}
		
		$form->setData($data);
		$form->bind($entity);
		
		if (!$form->isValid()) {
			throw new \Exception(serialize($form->getMessages()));
		}
		
		$em->persist($entity);
		$em->flush();
		$key = $documentRepository->getEncryptedId($entity->getDocumentId());
		if($cache->hasItem($key)) {
			$cache->removeItem($key);
		}
		
		// Depending on existence of $documentId will be dispatched the correct event
		if($documentId) {
		    
		} else {
		    $url = $this->getServiceLocator()->get('ControllerPluginManager')->get('Url');
		    $classifiedModel = $this->getServiceLocator()->get('document.model.classifiedAdminListing');
		    $classifiedModel->init($entity, $this->getServiceLocator());
		    $event = new ClassifiedCreatedEvent(__FUNCTION__, null, array(
    		    'to' => $classifiedModel->email, 
    		    'siteurl' => $url->fromRoute('home', array(), array('force_canonical' => true)),
    		    'fullname' => $classifiedModel->fullname,
		        'title' => $classifiedModel->title, 
		        'hash' => $classifiedModel->hashId,
		        'state' => $classifiedModel->state
    		));
		    $this->getEventManager()->trigger('classifiedCreated.post', $this, $event);
		}
		
		return $entity;
    }
904633
public static function createFromData(array $data): self
    {
        if (!isset($data['method'])) {
            throw new DomainException(self::REQUIRED_METHOD);
        }

        switch ($data['method']) {
            case self::NONE:
                $paymentInstruction = new NoneType($data);

                break;
            case self::PARTIAL:
                $paymentInstruction = new PartialType($data);

                break;
            case self::DISCOUNT:
                $paymentInstruction = new DiscountType($data);

                break;
            default:
                throw new DomainException(
                    sprintf(self::UNSUPPORTED_METHOD, implode(',', self::$availableMethods))
                );
        }

        return $paymentInstruction;
    }
417725
public function saveCategory($data = [])
    {
        if (!empty($data)) {
            $this->data($data);
        }
        $validate = new \gmars\rbac\validate\PermissionCategory();
        if (!$validate->check($this)) {
            throw new Exception($validate->getError());
        }
        $data = $this->getData();
        if (isset($data['id']) && !empty($data['id'])) {
            $this->isUpdate(true);
        }
        $this->save();
        return $this;
    }
532556
public function create(array $data)
    {
        $model = $this->app->make($this->model());
        $model->fill($data);

        $wasSaved = $model->save();

        if ($wasSaved) {
            return $this->find($model->id);
        }

        $errorMessage = "Não foi possível salvar.";

        if (method_exists($model, 'isValid')) {
            $exception = new ValidationException();
            $exception->setMessages($model->getValidationErrors()->all());

            throw $exception;
        }
        throw new ApiException($errorMessage);

    }
184351
public function save(array $data)
    {
        if (!$this->getModel()->isSingle()) {
            $id = $data['id'] ?? $this->id;
            $this->id = $id;
        }

        $columns = $this->data;
        foreach ($columns as $key => $column) {
            if (array_key_exists($key, $data)) {
                $column->setValue($data[$key]);
            } else {
                $column->setValue(null);
            }
        }

        $yaml = Yaml::dump($this->getData(), 5, 4, YAML::DUMP_MULTI_LINE_LITERAL_BLOCK | YAML::DUMP_OBJECT_AS_MAP);

        $fs = new Filesystem();
        $fs->dumpFile($this->getContentFilePath(), $yaml);
    }
461988
public function update(array $data)
    {
        $cardId = empty($data['id']) ? 0: (int) $data['id'];
        if ($cardId <= 0) {
            throw new Exception('Required field id');
        }
        $data['cardId'] = $data['id'];
        unset($data['id']);

        if (empty($data['columnId'])) {
            throw new Exception('Required field columnId');
        }

        if (empty($data['oldColumnId'])) {
            throw new Exception('Required field oldColumnId');
        }

        return $this->rest->put("$this->action/$cardId/move", $data);
    }
961169
public function save($data)
	{
		$related = $this->related;
		$model   = $related::newFromResults($data);

		return $this->associate($model)->save();
	}
881747
public function createDocument(array $data = null)
    {
        $className = $this->getDocumentClassName($data);

        /* @var $document \Sokil\Mongo\Document */
        $document = new $className(
            $this,
            $data,
            array('stored' => false) + $this->definition->getOptions()
        );

        // store document to identity map
        if ($this->isDocumentPoolEnabled()) {
            $collection = $this;
            $document->onAfterInsert(function (\Sokil\Mongo\Event $event) use ($collection) {
                $collection->addDocumentToDocumentPool($event->getTarget());
            });
        }

        return $document;
    }
455863
public static function toArray($data)
    {
        $XML = new \sasco\LibreDTE\XML();
        if (!$XML->loadXML($data)) {
            throw new \Exception('Ocurrió un problema al cargar el XML');
        }
        $datos = $XML->toArray();
        if (!isset($datos['DTE'])) {
            throw new \Exception('El nodo raíz del string XML debe ser el tag DTE');
        }
        if (isset($datos['DTE']['Documento']))
            $dte = $datos['DTE']['Documento'];
        else if (isset($datos['DTE']['Exportaciones']))
            $dte = $datos['DTE']['Exportaciones'];
        else if (isset($datos['DTE']['Liquidacion']))
            $dte = $datos['DTE']['Liquidacion'];
        unset($dte['@attributes']);
        return $dte;
    }
624988
public function save($data = null)
    {
        if ($data !== null) {
            $this->data = $data;
        }

        return $this->getHandler()->renderPath($this->getPath(), $this->data);
    }
881310
public function setData(array $data)
    {
        foreach ($data as $d) {
            if (!$this->isValid($d)) {
                throw new \Exception('Data Provided invalid structure.');
            }
        }

        // set options {
        if ($this->getNoConflictMode()) {
            // add script for noConflict mode
            $scriptItem = array(
                'mode'       => 'script',
                'content'    => ($this->getNoConflictHandler())
                        ? 'var '.$this->getNoConflictHandler().' = '. 'jQuery.noConflict();'
                        : 'jQuery.noConflict();',
                'attributes' => array(
                    'type' => 'text/javascript',
                ),
            );

            # add to items
            array_unshift($data, $scriptItem);
        }
        // .........
        $baseLibrary = $this->getBaseLibrary();
        if ($baseLibrary) {
            // add base script library
            $scriptItem = array(
                'mode'       => 'file',
                'content'    => null,
                'attributes' => array(
                    'src'  => $baseLibrary,
                    'type' => 'text/javascript',
                ),
            );

            # add to items
            array_unshift($data, $scriptItem);
        }
        // ... }

        return parent::setData($data);
    }
1039794
public function addRawData(array $data): self
    {
        foreach ($data as $row) {
            if (\is_array($row)) {
                $opType = \key($row);
                $metadata = \reset($row);
                if (Action::isValidOpType($opType)) {
                    // add previous action
                    if (isset($action)) {
                        $this->addAction($action);
                    }
                    $action = new Action($opType, $metadata);
                } elseif (isset($action)) {
                    $action->setSource($row);
                    $this->addAction($action);
                    $action = null;
                } else {
                    throw new InvalidException('Invalid bulk data, source must follow action metadata');
                }
            } else {
                throw new InvalidException('Invalid bulk data, should be array of array, Document or Bulk/Action');
            }
        }

        // add last action if available
        if (isset($action)) {
            $this->addAction($action);
        }

        return $this;
    }
67987
public function writeText(string $data): XmlStreamWriter
    {
        return $this->append(
                function(\DOMNode $parent) use ($data)
                {
                    $parent->appendChild(
                            $this->doc->createTextNode($this->encode($data))
                    );
                },
                'text'
        );
    }
409379
public function setData($data)
    {
        if ($this->getType() == PdfConverter::URL && strpos(substr($data, 0, 5), 'http') === false) {
            throw new \Exception(sprintf('Error : Given URL MUST contain the protocol. Current : %s', $data));
        }
        $this->data = $data;

        return $this;
    }
52127
protected function createDocument($data = array())
    {
        $enginePage = $this->getServiceLocator()->get('MelisEngineTree');
        $translator = $this->getServiceLocator()->get('translator');
        $pageSvc    = $this->getServiceLocator()->get('MelisEnginePage');
        $doc = new Document();
        if(is_array($data)) {
            $uri = $enginePage->getPageLink($data['page_id'], true);
            $pattern = '/(http|https)\:\/\/(www\.)?[a-zA-Z0-9-_.]+(\.([a-z.])?)*/';
            $domain = $this->getCurrentDomain();
            if($domain === '/'){
             echo  getenv('MELIS_PLATFORM') . " configuration is incorrect or does not exists in db";
             die;
           }
            if(!preg_match($pattern, $uri)) {
                $uri = $domain . $uri;
            }

            #$pageContent = $this->getUrlContent($uri) -- old ;

            $pageId = $data['page_id'] ?? null;
            $pageData  = $pageSvc->getDatasPage($pageId);
            $melisPageTree  = $pageData->getMelisPageTree();
            $pageContent = $melisPageTree->page_content;

            if($pageContent) {

                $doc->addField(Document\Field::Text('description', $enginePage->cleanString($this->getHtmlDescription($pageContent))));
                $doc->addField(Document\Field::Keyword('url', $uri));
                $doc->addField(Document\Field::Keyword('page_id', $data['page_id']));
                $doc->addField(Document\Field::Keyword('page_name', $data['page_name']));
                $doc->addField(Document\Field::UnStored('contents', $pageContent));


                $this->tmpLogs .= 'OK ' . sprintf($translator->translate('tr_melis_engine_search_create_index'), $data['page_id']) . sprintf($translator->translate('tr_melis_engine_search_create_index_success'), $uri) . PHP_EOL . '<br/>';
            }
            else {
                $this->tmpLogs .= 'KO ' . sprintf($translator->translate('tr_melis_engine_search_create_index'), $data['page_id']) . $translator->translate('tr_melis_engine_search_create_index_fail_unreachable') . ', ' . $uri . PHP_EOL . '<br/>';
                $this->unreachableCount++;
            }

        }

        return $doc;

    }
1348448
private function parseDocument(array $data)
    {
        $result = null;

        $dataSegment = $this->getArrayValue($data, DocumentInterface::KEYWORD_DATA, null);
        if (empty($dataSegment) === false && is_array($dataSegment) === true) {
            $isProbablySingle = $this->isProbablySingleIdentity($dataSegment);
            $parsed           = $isProbablySingle === true ?
                $this->parseSinglePrimaryData($dataSegment) :
                $this->parseArrayOfPrimaryData($dataSegment);

            if ($parsed !== null) {
                $result = new DocumentObject($parsed);
            }
        } elseif ($dataSegment !== null) {
            $this->errors->addDataError('Invalid element.');
        }

        return $result;
    }
1280579
public function byData($data)
    {
        \UArray::doConvertToArray($data);
        $model = new $this;
        $model->id = $this->entity->extractId($data);
        foreach ($data as $name => $seed) {
            $attribute = $model->getAttribute($name);
            if (is_object($attribute)) {
                $attribute->setSeed($seed);
            } else {
                $model->set($name, $seed);
            }
        }
        $model->initialize();
        return $model;
    }