Saves the PClasses.

@param string|array $uri pclass uri

@return void
@throws KlarnaException
344767
public function save($uri)
    {
        $this->connect($uri);
        //Only attempt to savePClasses if there are any.
        if (!is_array($this->pclasses)) {
            return;
        }
        if (count($this->pclasses) == 0) {
            return;
        }
        $this->savePClasses();
    }
969005
public function save($args)
    {
        $normalized = $this->normalizeArgs(is_array($args) ? $args : []);
        if (!is_array($normalized)) {
            throw new Exception(implode("\n", $normalized->getList()));
        }
        parent::save($normalized);
    }
347297
public function save($params = array()) {
        $badges = $params['badge_badges'];
        unset($params['badge_badges']);
        foreach ($badges as $badgeid) {
            $params["badge_{$badgeid}"] = $badgeid;
        }

        parent::save($params);
    }
136161
public function save($data): void
    {
        if (\is_string($data)) {
            // Make sure that the string is valid data.
            try {
                $this->formatter->decode($data);
            } catch (RuntimeException $e) {
                throw new RuntimeException(sprintf("Failed to save file '%s': %s", $this->getFilePath(), $e->getMessage()), $e->getCode(), $e);
            }
            $encoded = $data;
        } else {
            $encoded = $this->formatter->encode($data);
        }

        parent::save($encoded);
    }
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;
    }
1103709
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();
		$cache = $this->getServiceLocator()->get('ClassifiedCache');
		$form = $this->getServiceLocator()->get('document.form.classifiedimageadd');
    	
		$classifiedId = !empty($data['classifiedid']) ? $data['classifiedid'] : null;
	    $classified = null !== $classifiedId ? 
	        $documentRepository->findByEncryptedId($classifiedId, 'documentId') : null;
	    
	    // remove parent cache
		$cache = $this->getServiceLocator()->get('ClassifiedCache');
		if (!empty($classifiedId) && $cache->hasItem($classifiedId)) {
			$cache->removeItem($classifiedId);
		}
	    
		$userId = !empty($data['userid']) ? $data['userid'] : null;
	    $user = null !== $userId ? 
	        $userRepository->findByEncryptedId($userId, 'userId') : null;
		
		$entity = new Document();
		$form->setData($data);
		
		if (!$form->isValid()) {
			throw new \Exception(serialize($form->getMessages('files')));
		}
		
		$data = $form->getData();
			
		// @todo Better recover this in a smarter way
		$files = isset($data['files']) ? $data['files'] : array();
		$firstFile = reset($files);
		
		if(empty($firstFile)) {
			throw new \Exception(serialize(array('Empty file')));
		}
		
		$title = is_array($firstFile) && isset($firstFile['name']) ? 
			$firstFile['name'] : '';
			
		$entity->setDocumentType(Document::DOCUMENT_TYPE_IMAGE);
		$entity->setTitle($title);
		$entity->setParent($classified);
		$entity->setUser($user);
		$entity->setState(Document::DOCUMENT_STATE_ACTIVE);
		
		$em->persist($entity);
		$em->flush();
		
    	// trigger saveClassified event with the saved entity
    	$this->getEventManager()->trigger('imageSaved', null, $entity);
    	
    	return $entity;
    }
574579
public function save($path)
    {
        $this->savePath = $path;
        if(!is_dir($path))
        {
            mkdir($path, 0777, true);
        }
        $this->generateConsts();
        $this->generateFunctions();
        $this->generateClasses();
    }
712581
private function _save() : void
    {
        $this->_storage->save(
            $this->_host,
            $this->_storageKey,
            $this->_requestCount,
            $this->_timekeeper->getExpiration(),
            $this->getRemainingSeconds()
        );
    }
1166919
public function persist($data = null)
    {
        if (is_null($data)) {
            $data = $this->database->toArray();
        }

        if (! is_array($data)) {
            $data = $data->toArray();
        }

        $this->makeDir($this->getFileName());

        file_put_contents($this->getFileName(), json_encode($data));
    }
803498
protected function write(array $record)
    {
        if ($this->url && !file_exists($this->url)) {
            $this->stream = null;
        }
        parent::write($record);
    }
334480
private function validateUri(string $uri): void
    {
        if (filter_var($uri, FILTER_VALIDATE_URL) === false) {
            throw new InvalidArgumentException(sprintf('%s is not a valid uri', $uri));
        }
    }
683192
protected function savePClasses()
    {
        //Insert PClass SQL statement.
        $sql = <<<SQL
            INSERT INTO `{$this->dbName}`.`{$this->dbTable}`
                (`eid`, `id`, `type`, `description`, `months`, `interestrate`,
       	         `invoicefee`, `startfee`, `minamount`, `country`, `expire`)
           	VALUES
                (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
SQL;

        foreach ($this->pclasses as $pclasses) {
            foreach ($pclasses as $pclass) {
                try {
                    //Remove the pclass if it exists.
                    $sth = $this->pdo->prepare(
                        "DELETE FROM `{$this->dbName}`.`{$this->dbTable}`
                        WHERE `id` = ? AND `eid` = ?"
                    );
                    $sth->execute(
                        array(
                            $pclass->getId(), $pclass->getEid()
                        )
                    );

                    $sth->closeCursor();
                    $sth = null;
                } catch(PDOException $e) {
                    //Fail silently, we don't care if the removal failed.
                }

                try {
                    //Attempt to insert the PClass into the DB.
                    $sth = $this->pdo->prepare($sql);
                    $sth->execute(
                        array(
                            $pclass->getEid(),
                            $pclass->getId(),
                            $pclass->getType(),
                            $pclass->getDescription(),
                            $pclass->getMonths(),
                            $pclass->getInterestRate(),
                            $pclass->getInvoiceFee(),
                            $pclass->getStartFee(),
                            $pclass->getMinAmount(),
                            $pclass->getCountry(),
                            $pclass->getExpire()
                        )
                    );

                    $sth->closeCursor();
                    $sth = null;
                } catch(PDOException $e) {
                    throw new Klarna_DatabaseException(
                        'Failed to insert PClass into database!'
                    );
                }
            }
        }
    }
1108856
public function save($entity)
    {

        $objectManager = $this->getObjectManager();

        //@TODO UnitOfWork::STATE_NEW == $em->getUnitOfWork()->getEntityState($entity)
        //@see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#entity-state
        $objectManager->persist($entity);
        $objectManager->flush();
    }
1311823
public function load($uri)
    {
        $this->splitURI($uri);
        $this->connect();
        $result = mysql_query(
            "SELECT * FROM `{$this->dbName}`.`{$this->dbTable}`",
            $this->link
        );
        if ($result === false) {
            throw new Klarna_DatabaseException(
                'SELECT query failed! ('.mysql_error().')'
            );
        }
        while ($row = mysql_fetch_assoc($result)) {
            $this->addPClass(new KlarnaPClass($row));
        }
    }
67246
public static final function save() {
        foreach (self::$dirty as $class => $true) {
            self::$instances[$class]->store();
            unset(self::$dirty[$class]);
        }
    }
1045567
public function setUriProvider( $uri = null)
	{
		$toSetUri = $uri;
		if(!$uri) {
			$toSetUri = $this->getUriPrefix().'providers';
		}

		$this->_uriProvider = $toSetUri;
	}
196261
public function save(array $options = [])
    {
        $this->attributes['slug'] = str_slug($this->attributes['name']);

        return parent::save($options);
    }