Store (Create or Update) the post and its related data (ex. media, categories, tags) in the database

@param  $data array of data from request
@return array Returns 200 if successful, 500 if any internal error is found
@throws \Exception
773905
public static function store($data)
    {
        // return errors if there are any
        $errorMessages = self::validateStore($data);
        if(count($errorMessages)) {
            return array('error' => true, 'data' => [], 'errorMessages' => $errorMessages, 'noty' => []);
        }

        // Set posts table
        $postObj = new Post();
        $postObj->setTable($data['postType']);
        $postType = PostType::findBySlug($data['postType']);

        // on create
        if(!isset($data['postID'])) {
            $populatedFields = self::populateStoreColumns($postObj, $data);
            $populatedFields['post']->createdByUserID = (!User::isAdmin() || !isset($data['createdByUserID'])) ? Auth::user()->userID : $data['createdByUserID'];
            $postObj = $populatedFields['post'];

            if(!$postObj->save()) {
                throw new \Exception("Post could not be saved");
            }

            $postID = $postObj->postID;
        }else{ // on update
            $postObj = $postObj->where('postID', $data['postID'])->first();

            if($postObj) {
                $populatedFields = self::populateStoreColumns($postObj, $data);
                $populatedFields['post']->createdByUserID = (!User::isAdmin() || !isset($data['createdByUserID'])) ? Auth::user()->userID : $data['createdByUserID'];
                $postObj = $populatedFields['post'];

                if($postObj->save()) {
                    // Delete existing relations, to ensure accuracy
                    if($postType->hasCategories) {
                        DB::table($data['postType'].'_categories')->where("postID", $data['postID'])->delete();
                    }

                    if($postType->hasTags) {
                        DB::table($data['postType'].'_tags')->where("postID", $data['postID'])->delete();
                    }
                    DB::table($data['postType'].'_media')->where("postID", $data['postID'])->delete();
                }

                $postID = $postObj->postID;
            }else{
                throw new \Exception("Trying to edit a post that doesn't exist!");
            }
        }

        if($postID) {
            if($postType->hasCategories) {
                // Insert categories
                self::insertCategories($data['selectedCategories'], $postObj->postID, $data['postType']);
            }

            if($postType->hasTags) {
                // Insert tags
                self::insertTags($data['selectedTags'], $postObj->postID, $postType);
            }

            // Insert media
            self::insertMedia($data['files'], $postObj->postID, $data['postType'], $data['languages'], $populatedFields['files'], $data['filesToBeIgnored']);

            // Event fired after post is stored
            Event::fire('post:stored', [$data, $postObj]);

            return [
              'error' => false,
              'postID' => $postID,
              'postType' => $data['postType'],
              'noty' => $postObj->getNotyMessages()
            ];
        }else{
            return [
              'error' => true,
              'errorMessages' => $errorMessages,
              'noty' => $postObj->getNotyMessages()
            ];
        }
    }
278156
public function store(array $data)
    {
        return DB::transaction(function () use ($data) {
            $admin = new Admin;

            $admin->name          = $data['name'];
            $admin->email         = $data['email'];
            $admin->password      = bcrypt($data['password']);
            $admin->administrator = !empty($data['administrator']) ? 1 : 0;

            $permission = [];

            if (!empty($data['permission'])) {
                $permission = $data['permission'];
            }

            $admin->permission = serialize($permission);

            $admin->save();

            return $admin->id;
        });
    }
1301451
public function setDataLinked(array &$data) {
		$this->_data   = [];
		$this->_models = [];
		
		$modelClass = $this->getModel();
		
		foreach ($data as $key => &$item) {
			if (is_object($item)) {
				if (! $item instanceof $modelClass) {
					throw new Exception('Model must be an instance of "' . $modelClass . '"');
				}
				
				$this->_data[$key]   = &$item->getDataLinked();
				$this->_models[$key] = $item;
			}
			elseif (is_array($item)) {
				$this->_data[$key] = &$item;
			}
			else {
				throw new Exception('Unknown type of item: "' . gettype($item) . '"');
			}
		}
		unset($item);
		
		$this->_pointer = 0;
		$this->_map     = array_keys($this->_data);
		
		return $this;
	}
800361
public static function json_encode(array $data)
    {
        $json = @json_encode($data);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new \Exception(
                sprintf('An error occurred while trying to encode data to JSON [code "%s"]!', json_last_error())
            );
        } else {
            $data = $json;
        }
        return $data;
    }
511817
public function createNewRecord($data) {

        $email = new $this->model;

        $email->email_type_id = $data['email_type_id'];
        $email->title         = $data['title'];
        $email->description   = $data['description'];
        $email->comments      = $data['comments'];
        $email->created_at    = $data['created_at'];
        $email->created_by    = $data['created_by'];
        $email->updated_at    = $data['updated_at'];
        $email->updated_by    = $data['updated_by'];
        $email->locked_at     = null;
        $email->locked_by     = null;

        if ($email->save()) {

            // Return the new ID
            return $email->id;
        }

        return false;
    }
126723
protected function createPayload($data = '')
    {
        $payload = $this->setMeta($data, 'id', $this->getRandomId());

        return $this->setMeta($payload, 'attempts', 1);
    }
705278
public function save($data)
    {
        $db = $this->getDb();
        $fields = [];

        foreach ($data as $field => $value) {
            $fields[] = '`' . $field . '` = ' . $db->quote($value);
        }

        $query = 'INSERT INTO `oepaypal_order` SET ';
        $query .= implode(', ', $fields);
        $query .= ' ON DUPLICATE KEY UPDATE ';
        $query .= ' `oepaypal_orderid`=LAST_INSERT_ID(`oepaypal_orderid`), ';
        $query .= implode(', ', $fields);

        $db->execute($query);

        $id = $data['oepaypal_orderid'];
        if (empty($id)) {
            $id = $db->getOne('SELECT LAST_INSERT_ID()');
        }

        return $id;
    }
209783
public function add($data = [])
    {
        $insertId = $this->db->insert($this->table, $data);
        if ($insertId) {
            return (int) $insertId;
        }

        return 0;
    }
691017
public function sendData($data)
    {
        $response = $this->braintree->transaction()->find($data['transactionReference']);

        return $this->createResponse($response);
    }
911451
public function populate($data=array())
    {
    	foreach ($data as $k=>$v)
    	{
    		// Promise that if this is a new record, we aren't handling any end-user data for $data
    		if ($this->isNewRecord)
    			$this->$k = $v;
    		else
    		{
	    		if(isset($this->attributes[$k]))
	    			$this->$k = $v;
	    	}
    	}

    	return $this->attributes;
    }
1210696
protected function unserialize(string $data)
    {
        $unserializedData = json_decode($data, true);
        $unserializedData['d'] = unserialize($unserializedData['d']);

        return $unserializedData;
    }
122149
public function update(array $data): int
    {
        $this->builder->setUpdateData($data);
        $sql = $this->builder->buildSql();
        $this->builder = new QueryBuilder($this->pdo);
        return $this->execSql($sql);
    }
246773
protected function setRequestData(array $data = [])
    {
        if (($this->post instanceof Collection) && (!$this->post->isEmpty())) {
            unset($this->post);
        }

        $this->post = new Collection($data);

        return $this->post;
    }
1258581
public function save($data = null)
    {

        //1. Check if we have data and deal with it!
        if (!is_null($data)) {
            if (!$this->bindData($data)) {
                //we could not save the data
                return false;
            }
        }
        //2. Check if the primary key has a value
        $primary = $this->keys();

        //3. if the primary key has a value, then we are updating, else we are inserting
        if (isset($primary->Value) && !empty($primary->Value)) {
            return $this->update($primary->Value);
        } else {
            return $this->insert();
        }
        //if we get here then there is a problem
        return false;
    }
247139
public function create($data)
    {
        /* ACCESS CHECK */
        if (!$this->isAllowed(ResourceName::RESOURCE_SITES, 'admin')) {
            $this->getResponse()->setStatusCode(Response::STATUS_CODE_401);

            return $this->getResponse();
        }
        /* */

        $inputFilter = new SiteInputFilter();
        $inputFilter->setData($data);

        if (!$inputFilter->isValid()) {
            return new ApiJsonModel(
                [],
                1,
                'Some values are missing or invalid.',
                $inputFilter->getMessages()
            );
        }

        $data = $inputFilter->getValues();

        $siteManager = $this->getSiteManager();
        $userId = $this->getCurrentUserId();

        $data = $siteManager->prepareSiteData($data);
        /** @var \Rcm\Repository\Domain $domainRepo */
        $domainRepo = $this->getEntityManager()->getRepository(
            \Rcm\Entity\Domain::class
        );

        $data['domain'] = $domainRepo->createDomain(
            $data['domainName'],
            $userId,
            'Create new domain in ' . get_class($this)
        );

        /** @var \Rcm\Entity\Site $newSite */
        $newSite = new Site(
            $userId,
            'Create new site in ' . get_class($this)
        );

        $newSite->populate($data);
        // make sure we don't have a siteId
        $newSite->setSiteId(null);

        $newSite = $siteManager->createSite($newSite);

        return new ApiJsonModel($newSite, 0, 'Success');
    }
854144
public function getTokenData($data = array())
    {
        // Are there token details to add?

        if ($this->getToken() || $this->getCardReference()) {
            // A card token or reference has been provided.
            $data['Token'] = $this->getToken() ?: $this->getCardReference();

            // If we don't have a StoreToken override, then set it according to
            // whether we are dealing with a token or a cardReference.
            // Overriding the default token storage flag is for legacy support.

            $storeToken = $this->getStoreToken();

            if ($storeToken === null) {
                // If we are using a cardReference, then keep it stored
                // after this transaction for future use.
                // We consider a cardReference as long term, and a token
                // as single-use.

                if ((bool)$this->getCardReference()) {
                    $data['StoreToken'] = static::STORE_TOKEN_YES;
                }
            } elseif ($storeToken !== static::STORE_TOKEN_YES
                && $storeToken !== static::STORE_TOKEN_NO
            ) {
                // A store token to treat as a boolean has been supplied.

                $data['StoreToken'] = (bool)$storeToken
                    ? static::STORE_TOKEN_YES
                    : static::STORE_TOKEN_NO;
            } else {
                // A valid store token to use directly has been supplied.

                $data['StoreToken'] = $storeToken;
            }
        }

        return $data;
    }
305212
public function save($data)
    {
        if (empty($data['_id'])) {
            return $this->insert($data);
        }

        $id = $data['_id'];

        unset($data['_id']);

        $bucketName = $this->db->quoteBucketName($this->name);

        $this->update($data, ["META($bucketName).id" => $id]);

        return $id;
    }