Update a Reference

@link https://developer.github.com/v3/git/refs/#update-a-reference

@param string $ref
@param string $sha
@param bool   $force

@return array
@throws \Exception
175379
public function update(string $ref, string $sha, bool $force = false): array
    {
        return $this->getApi()->request($this->getApi()->sprintf('/repos/:owner/:repo/git/refs/:ref',
            $this->getGitData()->getOwner(), $this->getGitData()->getRepo(), $ref), Request::METHOD_POST, [
                'sha'   => $sha,
                'force' => $force
            ]);
    }
449764
private function updateJalaliFromGeorgian($force = false) {
        
        if ($this->converted && ! $force) {
            return;
        }
        
        list($year, $month, $day) = self::julian2jalali(self::georgian2julian($this->carbon->year, $this->carbon->month, $this->carbon->day));
        
        $this->year  = $year;
        $this->month = $month;
        $this->day   = $day;
        
        // it tells that the jalali core is updated
        $this->converted = true;
        
    }
902703
function update ($commit = true)
    {
        if (! $this->isValid()) {
            throw new Pluf_Exception(
                    __('cannot save the location from an invalid form'));
        }
        // Set attributes
        $this->location->setFromFormData($this->cleaned_data);
        if ($commit) {
            if (! $this->location->update()) {
                throw new Pluf_Exception(
                        sprintf(__('fail to update the location %s'), 
                                $this->location->name));
            }
        }
        return $this->location;
    }
382436
def refs_to(cls, sha1, repo):
        """"""
        matching = []
        for refname in repo.listall_references():
            symref = repo.lookup_reference(refname)
            dref = symref.resolve()
            oid = dref.target
            commit = repo.get(oid)
            if commit.hex == sha1:
                matching.append(symref.shorthand)

        return matching
509076
public function flushCacheState(bool $force = false): void
    {
        if ((!empty($this->newCacheState) && is_writable($this->cacheDir)) || $force) {
            $fullCacheMap = $this->newCacheState + $this->cacheState;
            $cachePath    = substr(var_export($this->cacheDir, true), 1, -1);
            $rootPath     = substr(var_export($this->appDir, true), 1, -1);
            $cacheData    = '<?php return ' . var_export($fullCacheMap, true) . ';';
            $cacheData    = strtr($cacheData, [
                '\'' . $cachePath => 'AOP_CACHE_DIR . \'',
                '\'' . $rootPath  => 'AOP_ROOT_DIR . \''
            ]);
            $fullCacheFileName = $this->cacheDir . self::CACHE_FILE_NAME;
            file_put_contents($fullCacheFileName, $cacheData, LOCK_EX);
            // For cache files we don't want executable bits by default
            chmod($fullCacheFileName, $this->fileMode & (~0111));

            if (function_exists('opcache_invalidate')) {
                opcache_invalidate($fullCacheFileName, true);
            }
            $this->cacheState    = $this->newCacheState + $this->cacheState;
            $this->newCacheState = [];
        }
    }
1128950
public function updateUser($force = false)
    {
        $user = $this->user;
        if (!$user || $force) {
            $wechat = $this->wechat;
            $user = new MpUser();
            $this->populateRelation('user',$user);
            $data = $wechat->getSdk()->getUserInfo($this->open_id);
            if ($data) {
                $user->setAttributes([
                    'id' => $this->id,
                    'nickname' => $data['nickname'],
                    'sex' => $data['sex'],
                    'city' => $data['city'],
                    'country' => $data['country'],
                    'province' => $data['province'],
                    'language' => $data['language'],
                    'avatar' => $data['headimgurl'],
                    'subscribe_time' => $data['subscribe_time'],
                    'remark' => $data['remark'],
                    'union_id' => isset($data['unionid']) ? $data['unionid'] : '', // 测试号无此项
                    'group_id' => $data['groupid'],
                ]);
                return $user->save();
            }
            $user->addError('id', '用户资料更新失败!');
            return false;
        }
        return true;
    }
310694
protected function refExist($path, $ref)
    {
        $content = file_get_contents($path);

        if (false === strpos($content, $ref)) {
            return false;
        }

        return true;
    }
767302
public function attr($key, $value = null, $force = false)
    {
        $attrs = $this->ctx->attrs ?: ($this->ctx->attrs = []);
        if (func_num_args() === 1) {
            return isset($attrs[$key]) ? $attrs[$key] : null;
        }

        $this->ctx->attrs[$key] = !array_key_exists($key, $attrs) || $force ? $value : $attrs[$key];

        return $this;
    }
655806
public function refreshToken($forceRefresh = false)
    {
        if (property_exists($this, "sdl") && $this->sdl == 0) {
            parent::__construct($this->xmlLoc, array('trace'=>1, 'exceptions'=>0));
        }
        try {
            $currentTime = new DateTime();
            if (is_null($this->getAuthTokenExpiration($this->tenantKey))) {
                $timeDiff = 0;
            } else {
                $timeDiff = $currentTime->diff($this->getAuthTokenExpiration($this->tenantKey))->format('%i');
                $timeDiff = $timeDiff  + (60 * $currentTime->diff($this->getAuthTokenExpiration($this->tenantKey))->format('%H'));
            }
            if (is_null($this->getAuthToken($this->tenantKey)) || ($timeDiff < 5) || $forceRefresh) {
                $url = $this->tenantKey == null
                        ? $this->baseAuthUrl."/v1/requestToken?legacy=1"
                        : $this->baseUrl."/provisioning/v1/tenants/{$this->tenantKey}/requestToken?legacy=1";

                $jsonRequest = new stdClass();
                $jsonRequest->clientId = $this->clientId;
                $jsonRequest->clientSecret = $this->clientSecret;
                $jsonRequest->accessType = "offline";
                if (!is_null($this->getRefreshToken($this->tenantKey))) {
                    $jsonRequest->refreshToken = $this->getRefreshToken($this->tenantKey);
                }
                $authResponse = ET_Util::restPost($url, json_encode($jsonRequest), $this);
                $authObject = json_decode($authResponse->body);
                //echo "auth:  \n";
                //print_r($authResponse);

                if ($authResponse && property_exists($authObject, "accessToken")) {
                    $dv = new DateInterval('PT'.$authObject->expiresIn.'S');
                    $newexpTime = new DateTime();
                    $this->setAuthToken($this->tenantKey, $authObject->accessToken, $newexpTime->add($dv));
                    $this->setInternalAuthToken($this->tenantKey, $authObject->legacyToken);
                    if (property_exists($authObject, 'refreshToken')) {
                        $this->setRefreshToken($this->tenantKey, $authObject->refreshToken);
                    }
                } else {
                    throw new Exception('Unable to validate App Keys(ClientID/ClientSecret) provided, requestToken response:'.$authResponse->body);
                }
            }
        } catch (Exception $e) {
            throw new Exception('Unable to validate App Keys(ClientID/ClientSecret) provided.: '.$e->getMessage());
        }
    }
626503
public function delete(string $ref): bool
    {
        $this->getApi()->request($this->getApi()
                                      ->sprintf('/repos/:owner/:repo/git/refs/:ref', $this->getGitData()->getOwner(),
                                          $this->getGitData()->getRepo(), $ref), Request::METHOD_DELETE);

        if ($this->getApi()->getHeaders()['Status'] == '204 No Content') {
            return true;
        }

        return false;
    }
441608
public function update($username, $repository, $reference, array $params)
    {
        if (!isset($params['sha'])) {
            throw new MissingArgumentException('sha');
        }

        $reference = $this->encodeReference($reference);

        return $this->patch('/repos/'.rawurlencode($username).'/'.rawurlencode($repository).'/git/refs/'.$reference, $params);
    }
975907
public function storeInsert($force = false)
    {
        // update table if needed
        static::applySchema();

        // collect field names for sql query
        $fieldsArray = [];

        // collect values for sql query
        $valuesArray = [];

        // collect tokens value for pdo parametric
        $tokensArray = [];

        // get primary field name
        $key = static::getPrimaryKey();

        // get complete fields schema
        $schema = static::getSchema();

        //
        foreach ($schema as $field => &$column) {
            if (($field == $key || is_null($this->{$field})) && !$force) {
                continue;
            }
            // get current value of attribute of object
            $value = static::insertRelationBefore($this->{$field}, $column);
            $token = ':'.$field;
            $fieldsArray[] = '`'.$field.'`';
            $valuesArray[] = $token;
            $tokensArray[$token] = $value;
        }

        //
        $fields = implode(',', $fieldsArray);

        //
        $values = implode(',', $valuesArray);

        //
        $table = static::getTable();

        //
        $sql = "INSERT INTO {$table} ({$fields}) VALUES ({$values})";

        //
        static::getDatabase()->execute($sql, $tokensArray);

        //
        foreach ($schema as $field => &$column) {
            if (!$force && $field == $key) {
                continue;
            }

            static::insertRelationAfter($this->{$field}, $column);
        }

        //
        if ($key) {
            $index = static::getDatabase()->getLastId();
            $this->{$key} = $index;
        } else {
            $index = static::getMainFieldValue();
        }

        //
        return $index;
    }
393423
protected function resolveReference($ref)
	{
		// @todo Better resolver (Only work with internal components atm)
		if (strpos($ref, '#/components/') !== 0) {
			throw new Exception('Can not resolve this $ref atm (todo) : ' . $ref);
		}

		$componentPath = str_replace('#/components/', '', $ref);
		$pathParts = explode('/', $componentPath);

		$target = $this->openApiFileContent['components'];
		$processingPathParts = ['#', 'components'];
		$targetName = '';
		foreach ($pathParts as $pathPart) {
			$processingPathParts[] = $pathPart;
			if (!isset($target[$pathPart])) {
				throw new Exception('Can not resolve $ref "' . $ref . '" : Segment not found at "' . implode('/', $processingPathParts) . '"');
			}
			$target = $target[$pathPart];
			$targetName = $pathPart;
		}

		return [
			'name' => $targetName,
			'target' => $target
		];
	}
646169
public function get($force = false)
    {
        if (is_null($this->settings) || $force) {
            $_settings = $this->db->select()
                ->from($this->getTable())
                ->get();
            $settings = array();
            foreach ($_settings as $setting) {
                // decrypt the value if needed
                if (in_array($setting['setting_key'], $this->getEncrypted()) && ! empty($setting['setting_value'])) {
                    $settings[$setting['setting_key']] = $setting['setting_value'] = $this->getEncrypt()->decode($setting['setting_value']);
                }
                
                // unserialize the value
                if (in_array($setting['setting_key'], $this->getSerialized()) && ! empty($setting['setting_value'])) {
                    $settings[$setting['setting_key']] = $setting['setting_value'] = unserialize($setting['setting_value']);
                    foreach ($settings[$setting['setting_key']] as $key => $value) {
                        if ($value == '') {
                            unset($settings[$setting['setting_key']][$key]); // remove blank entries
                        }
                    }
                }
                
                // sort out new line values
                if (in_array($setting['setting_key'], $this->getNewLines())) {
                    $settings[$setting['setting_key']] = $setting['setting_value'] = explode("\n", $setting['setting_value']);
                    foreach ($settings[$setting['setting_key']] as $key => $value) {
                        $value = trim($value);
                        if ($value == '') {
                            unset($settings[$setting['setting_key']][$key]); // remove blank entries
                        } else {
                            $settings[$setting['setting_key']][$key] = $value;
                        }
                    }
                }
                
                $settings[$setting['setting_key']] = $setting['setting_value'];
            }
            
            $ignore = array(
                'license_check',
                'license_status'
            );
            foreach ($this->getDefaults() as $key => $value) {
                // setup the override check
                if (isset($this->overrides[$key]) && ! in_array($key, $ignore)) {
                    $settings[$key] = $this->overrides[$key];
                }
                
                if (! isset($settings[$key])) {
                    $settings[$key] = $value;
                }
            }
            
            $this->settings = $settings;
            
            if($this->settings['api_key'] == '')
            {
                $this->settings['api_key'] = $this->getEncrypt()->guid();
            }
            
            if($this->settings['api_secret'] == '')
            {
                $this->settings['api_secret'] = $this->getEncrypt()->guid();
            }            
        }
        
        return $this->settings;
    }
87912
protected function update($step)
    {
        $sectionCollection = $this->matchSections('update', $step);

        if (count($sectionCollection) > 1 && array_key_exists('references', $step->dsl)) {
            throw new \Exception("Can not execute Section update because multiple sections match, and a references section is specified in the dsl. References can be set when only 1 section matches");
        }

        $sectionService = $this->repository->getSectionService();
        foreach ($sectionCollection as $key => $section) {
            $sectionUpdateStruct = $sectionService->newSectionUpdateStruct();

            if (isset($step->dsl['identifier'])) {
                $sectionUpdateStruct->identifier = $this->referenceResolver->resolveReference($step->dsl['identifier']);
            }
            if (isset($step->dsl['name'])) {
                $sectionUpdateStruct->name = $this->referenceResolver->resolveReference($step->dsl['name']);
            }

            $section = $sectionService->updateSection($section, $sectionUpdateStruct);

            $sectionCollection[$key] = $section;
        }

        $this->setReferences($sectionCollection, $step);

        return $sectionCollection;
    }
117625
public static function ref($ref)
    {
        if (isset($ref['$id'])) {
            if ($ref['$ref'] == self::collectionName()) {
                return self::id($ref['$id']);
            }
        }

        return null;
    }
1264184
public function setup($force = false) {
		if(!$force && $this->description)
			return;
		
		$this->changeDescription($this->fetchDescription());
	}