Ready-made class for working with API via Curl

Finishing the main part of the course, in the last lesson we will look at a full-fledged class for sending requests to the Yandex.Disk API. We will simplify all the code written earlier and leave only the necessary methods.

Knowing the methods and URL for requests, I decided to remove the methods that are wrappers and access the method directly sendQueryYaDisk().

Also I solved the line https://cloud-api.yandex.net/v1/disk add to property $basicApiUrland the method sendQueryYaDisk() now the first parameter will not take the full URL, but its ending in which the methods are indicated.

Class for working with Yandex.Disk via API


class Backup
{
    protected $token = 'токен';
    protected $basicApiUrl="https://cloud-api.yandex.net/v1/disk/";

    /**
     * Method sendQueryYaDisk
     *
     * @param string $urlQuery URL для отправки запросов
     * @param array $arrQuery массив параметров
     * @param string $methodQuery метод отправки
     *
     * @return array
     */
    public function sendQueryYaDisk(string $methodAPI = '', array $arrQuery = [], string $methodQuery = 'GET'): array
    {
        if($methodQuery == 'POST') {
            $fullUrlQuery = $this->basicApiUrl . $methodAPI;
        } else {
            $fullUrlQuery = $this->basicApiUrl . $methodAPI . '?' . http_build_query($arrQuery);
        }

        $ch = curl_init($fullUrlQuery);
        switch ($methodQuery) {
            case 'PUT':
                curl_setopt($ch, CURLOPT_PUT, true);
                break;

            case 'POST':
                curl_setopt($ch, CURLOPT_POST, 1);
	            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arrQuery));
                break;

            case 'DELETE':
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
                break;
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: OAuth ' . $this->token]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $resultQuery = curl_exec($ch);
        curl_close($ch);

        return (!empty($resultQuery)) ? json_decode($resultQuery, true) : [];
    }


    
    /**
     * Метод для загрузки файлов
     *
     * @param string $filePath путь до файла
     * @param string $dirPath путь до директории на Яндекс.Диск
     *
     * @return string
     */
    public function disk_resources_upload(string $filePath, string $dirPath=""): string
    {
        $arrParams = [
            'path' => $dirPath . basename($filePath),
            'overwrite' => 'true',
        ];

        $urlQuery = 'https://cloud-api.yandex.net/v1/disk/resources/upload';
        $resultQuery = $this->sendQueryYaDisk('resources/upload', $arrParams);

        if (empty($resultQuery['error'])) {
            $fp = fopen($filePath, 'r');
        
            $ch = curl_init($resultQuery['href']);
            curl_setopt($ch, CURLOPT_PUT, true);
            curl_setopt($ch, CURLOPT_UPLOAD, true);
            curl_setopt($ch, CURLOPT_INFILESIZE, filesize($filePath));
            curl_setopt($ch, CURLOPT_INFILE, $fp);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HEADER, false);
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
        
            return $http_code;
        } else {
            return $resultQuery['message'];
        }
    }
    

    
    /**
     * Метод для скачивания файлов на сервера
     *
     * @param string $filePath путь до файла в Яндекс.Диске
     * @param string $dirPath путь до директории на сервере
     *
     * @return array
     */
    public function disk_resources_download(string $filePath, string $dirPath=""): array
    {
        $arrParams = [
            'path' => $filePath,
        ];
        $resultQuery = $this->sendQueryYaDisk('resources/download', $arrParams);

        if(empty($resultQuery['error'])) {
            $file_name = $dirPath . basename($filePath);
            $file = @fopen($file_name, 'w');
        
            $ch = curl_init($resultQuery['href']);
            curl_setopt($ch, CURLOPT_FILE, $file);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: OAuth ' . $this->token));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_HEADER, false);
            $resultQuery = curl_exec($ch);
            curl_close($ch);

            fclose($file);

            return [
                'message' => 'Файл успешно загружен',
                'path' => $file_name,
            ];
        } else {
            return $resultQuery;
        }
    }
    

}

Obtaining general information about a Yandex.Disk account via the API

$resultQuery = $backupClass->sendQueryYaDisk();

Getting meta information about folders and files on Yandex.Disk via the API

$arrParams = [
    'path' => '/uploads',
    'fields' => 'name,_embedded.items.path',
    'limit' => 100,
    'offset' => 0,
    'preview_crop' => false,
    'preview_size' => '',
    'sort' => 'created'
];
$resultQuery = $backupClass->sendQueryYaDisk('resources', $arrParams);

Getting meta-information about folders and files in the trash on Yandex.Disk via the API

$arrParams = [
    'path' => '/',
    'fields' => 'name,_embedded.items.path',
    'limit' => 100,
    'offset' => 0,
    'preview_crop' => false,
    'preview_size' => '',
    'sort' => 'created'
];
$resultQuery = $backupClass->sendQueryYaDisk('trash/resources', $arrParams);

Getting a flat list of all files from Yandex.Disk via API

$arrParams = [
    'limit' => 100,
    'media_type' => 'image',
    'offset' => 0,
    'fields' => 'name,_embedded.items.path',
    'preview_size' => '',
    'preview_crop' => false,
];
$resultQuery = $backupClass->sendQueryYaDisk('resources/files', $arrParams);

Getting the latest uploaded items to Yandex.Disk via the API

$arrParams = [
    'limit' => 10,
    'media_type' => 'image',
    'fields' => 'name,_embedded.items.path',
    'preview_size' => '',
    'preview_crop' => false,
];
$resultQuery = $backupClass->sendQueryYaDisk('resources/last-uploaded', $arrParams);

Method for creating a directory on Yandex.Disk via the API

$arrParams = [
    'path' => '/uploads/prog_time',
    'fields' => 'name,_embedded.items.path',
];
$resultQuery = $backupClass->sendQueryYaDisk('resources', $arrParams, 'PUT');

Method for uploading files to Yandex.Disk via API

$filePath = $_SERVER['DOCUMENT_ROOT'] . '/public/image.png';
$dirPath="/uploads";
$resultQuery = $backupClass->disk_resources_upload($filePath, $dirPath);

Method for downloading files from Yandex.Disk to servers via API

$filePath="/test.docx";
$dirPath = $_SERVER['DOCUMENT_ROOT'] . '/public';
$resultQuery = $backupClass->disk_resources_download($filePath, $dirPath);

Deleting a resource from Yandex.Disk via the API

$arrParams = [
    'path' => '/test.docx',
    'permanently' => false,
    'fields' => 'name,_embedded.items.path',
];
$resultQuery = $backupClass->sendQueryYaDisk('resources', $arrParams, 'DELETE');

Publishing a file in Yandex.Disk via the API

$arrParams = [
    'path' => '/uploads/test.xlsx',
];
$resultQuery = $backupClass->sendQueryYaDisk('resources/publish', $arrParams, 'PUT');

Unpublishing a file in Yandex.Disk via the API

$arrParams = [
    'path' => '/uploads/test.xlsx',
];
$resultQuery = $backupClass->sendQueryYaDisk('resources/unpublish', $arrParams, 'PUT');

Getting a list of public files from Yandex.Disk via the API

$arrParams = [
    'limit' => 10,
    'offset' => 0,
    'type' => 'dir',
    'fields' => 'name,_embedded.items.path',
    'preview_size' => '',
];
$resultQuery = $backupClass->sendQueryYaDisk('resources/public', $arrParams);

Method for restoring a file from the trash in Yandex.Disk via the API

$arrParams = [
    'path' => 'trash:/test.docx_f8fb153e7cb73695ee2fdada79a7871b0093596e',
    'name' => 'new_name.docx'
];
$resultQuery = $backupClass->sendQueryYaDisk('trash/resources/restore', $arrParams, 'PUT');

Emptying the trash in Yandex.Disk via the API

$resultQuery = $backupClass->sendQueryYaDisk('trash/resources', [], 'DELETE');

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *