Ensure that a file exists on Google Drive by creating it if it doesn't exist or updating it if it does

@param string $contents
@param string $parentId
@param string $fileName
@param string $mime
@return Google_Service_Drive_DriveFile
507360
protected function ensureDriveFileExists($contents, $parentId, $fileName, $srcDriveFile, $mime)
    {
        if (! $mime) {
            $mime = Util::guessMimeType($fileName, $contents);
        }

        $driveFile = new Google_Service_Drive_DriveFile();

        $mode = 'update';
        if (! $srcDriveFile) {
            $mode = 'insert';
            $driveFile->setName($fileName);
            $driveFile->setParents([$parentId]);
        }

        $driveFile->setMimeType($mime);

        $params = ['fields' => $this->fetchfieldsGet];
        if ($contents) {
            $params['data'] = $contents;
            $params['uploadType'] = 'media';
        }
        if ($mode === 'insert') {
            $retrievedDriveFile = $this->service->files->create($driveFile, $this->applyDefaultParams($params, 'files.create'));
        } else {
            $retrievedDriveFile = $this->service->files->update(
                $srcDriveFile->getId(),
                $driveFile,
                $this->applyDefaultParams($params, 'files.update')
            );
        }

        return $retrievedDriveFile;
    }
1074448
public function get($fileId, $parentId, $optParams = array()) {
      $params = array('fileId' => $fileId, 'parentId' => $parentId);
      $params = array_merge($params, $optParams);
      $data = $this->__call('get', array($params));
      if ($this->useObjects()) {
        return new Google_ParentReference($data);
      } else {
        return $data;
      }
    }
189011
public function setFileRaw( string$key, string$contentType, string$content, string$fileName=null ):self
	{
		$this->files[$key]= [
			'fileName'=> $fileName??md5($content),
			'contentType'=> $contentType,
			'content'=> $content,
		];

		return $this;
	}
658414
public function get($folderId, $childId, $optParams = array())
  {
    $params = array('folderId' => $folderId, 'childId' => $childId);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_Drive_ChildReference");
  }
1034576
public static function parseFile($fileName, $fileContent = null)
    {
        $fileName = PathResolver::realpath($fileName);
        if (isset(self::$parsedFiles[$fileName]) && !isset($fileContent)) {
            return self::$parsedFiles[$fileName];
        }

        if (isset(self::$maximumCachedFiles) && (count(self::$parsedFiles) === self::$maximumCachedFiles)) {
            array_shift(self::$parsedFiles);
        }

        if (!isset($fileContent)) {
            $fileContent = file_get_contents($fileName);
        }
        $treeNode = self::$parser->parse($fileContent);
        $treeNode = self::$traverser->traverse($treeNode);

        self::$parsedFiles[$fileName] = $treeNode;

        return $treeNode;
    }
620436
protected function getParentFolder(\Google_Service_Drive $service)
    {
        $parts = explode('/', trim($this->remotePath, '/'));
        $folderId = null;
        foreach ($parts as $name) {
            $q = 'mimeType="application/vnd.google-apps.folder" and title contains "'.$name.'"';
            if ($folderId) {
                $q .= sprintf(' and "%s" in parents', $folderId);
            }
            $folders = $service->files->listFiles(array(
                    'q' => $q,
                ))->getItems();
            if (count($folders) == 0) {
                //TODO create the missing folder.
                throw new \LogicException('Remote path does not exist.');
            } else {
                /* @var \Google_Service_Drive_DriveFile $folders[0] */
                $folderId = $folders[0]->id;
            }
        }

        if (!$folderId) {
            return;
        }

        $parent = new \Google_Service_Drive_ParentReference();
        $parent->setId($folderId);

        return $parent;
    }
582138
public function cacheFile($cacheKey, $fileContents) {

        // Get directory and filename
        list($directory, $filename) = $this->getDirectoryAndFilenameFromKey($cacheKey);

        // Make the cache directory
        if (!file_exists($directory)) mkdir($directory, 0777, true);

        // Save the file
        file_put_contents($directory . "/" . $filename, $fileContents);

    }
1138358
public function asFileContents($file_loc, $mime)
    {
        $stream = StreamFactory::file($file_loc);
        return new Response($stream, self::OK, ['Content-Type' => $mime]);
    }
81123
public static function appendContents($filename, $contents)
    {
        $result = file_put_contents($filename, $contents, \LOCK_EX | \LOCK_NB | \FILE_APPEND);
        if ($result === false) {
            throw new \RuntimeException("Cannot append to the file: " . $filename);
        }
    }
505293
public static function createFile($file, $content = '')
    {
        $folder = dirname($file);
        if (!is_dir($folder)) {
            self::createFolder($folder);
        }

        file_put_contents($file, $content);
    }
75344
public function move($fileIDs, $parentID)
    {
        if (is_array($fileIDs)) {
            $fileIDs = implode(',', $fileIDs);
        }

        $data = [
            'file_ids'  => $fileIDs,
            'parent_id' => $parentID
        ];

        return $this->post('files/move', $data, \true);
    }
902490
public function addFromString($localname, $contents)
    {
        if (false === $this->openned) {
            return false;
        }
        if (file_exists($this->filename) && !is_writable($this->filename)) {
            return false;
        }
        $localname = preg_replace("/(?:\.|\/)*(.*)/", "\\1", $localname);
        $localpath = dirname($localname);
        $tmpfilename = self::TMP_DIR . '/' . basename($localname);
        if (false !== file_put_contents($tmpfilename, $contents)) {
            $this->pclzip->delete(PCLZIP_OPT_BY_NAME, $localname);
            $add = $this->pclzip->add($tmpfilename, PCLZIP_OPT_REMOVE_PATH, self::TMP_DIR, PCLZIP_OPT_ADD_PATH, $localpath);
            unlink($tmpfilename);
            if (!empty($add)) {
                return true;
            }
        }
        return false;
    }
252114
public function addAttachment($filename, $data, $mime = null)
    {
        $data = file_get_contents($data);
        $this->attachments[] = array($filename, $data, $mime);
        return $this;
    }
1157796
public function updateDocumentAction($documentId, $parentType)
    {
        if (null !== $response = $this->checkAuth($this->getAdminResources()->getResource($parentType, static::MODULE_RIGHT), array(), AccessManager::UPDATE)) {
            return $response;
        }

        $documentInstance = $this->updateFileAction($documentId, $parentType, 'document', TheliaEvents::DOCUMENT_UPDATE);

        if ($documentInstance instanceof \Symfony\Component\HttpFoundation\Response) {
            return $documentInstance;
        } else {
            return $this->render('document-edit', array(
                'documentId' => $documentId,
                'documentType' => $parentType,
                'redirectUrl' => $documentInstance->getRedirectionUrl(),
                'formId' => $documentInstance->getUpdateFormId()
            ));
        }
    }
360342
public function save($filename, $content) {
        if ($this->driver) {
            return $this->driver->save($filename, $content);
        }

        return false;
    }
883541
protected function writeToCache($fileName, $content)
    {
        if ($this->cachePath === null || !is_dir($this->cachePath) || !is_writable($this->cachePath)) {
            return;
        }
        $encoder    = new \Riimu\Kit\PHPEncoder\PHPEncoder();
        $contentPHP = $encoder->encode($content, [
            'whitespace' => false,
            'recursion.detect' => false
        ]);
        $cache      = '<?php $crudlexCacheContent = '.$contentPHP.';';
        file_put_contents($this->getCacheFile($fileName), $cache);
    }
512923
public function saveFile ($filename, $contents)
	{
		// make sure the directory exists
		$dirname = $this->reportDir.'/'.dirname ($filename);

		if ($dirname && !is_dir($dirname)) {
			mkdir ($dirname, 0777, true);
		}

		// save
		file_put_contents ($this->reportDir.'/'.$filename, $contents);
	}