### Setup Logging Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/README.md Configure a PSR-3 logger, such as Monolog, and inject it into the service. ```php use Monolog\Logger; use Monolog\Handlers\StreamHandler; $logger = new Logger('yandex-search'); $logger->pushHandler(new StreamHandler('php://stderr', Logger::ERROR)); $service = new YandexSearchService( $httpClient, $factory, $logger, $apiId, $apiKey ); ``` -------------------------------- ### Initializing YandexSearchService Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/YandexSearchService.md Example showing how to instantiate the service with required PSR-compliant dependencies. ```php use YandexSearchAPI\YandexSearchService; use Nyholm\Psr7\Factory\Psr17Factory; use Symfony\Component\HttpClient\Psr18Client; use Psr\Log\NullLogger; $factory = new Psr17Factory(); $httpClient = new Psr18Client(); $logger = new NullLogger(); $service = new YandexSearchService( $httpClient, $factory, $logger, 'your-folder-id', 'your-api-key' ); ``` -------------------------------- ### Complete usage example Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/Result.md Demonstrates iterating through search results and accessing their properties. ```php use YandexSearchAPI\SearchRequest; use YandexSearchAPI\SearchException; try { $request = new SearchRequest('PHP frameworks'); $response = $service->search($request); foreach ($response->getResults() as $result) { // Extract title $title = $result->getTitle(); // Extract full URL $url = $result->getURL(); // Extract domain $domain = $result->getDomain(); // Display with snippet if available echo $title . "\n"; echo $url . "\n"; echo "Domain: " . $domain . "\n"; if ($result->getSnippet() !== null) { echo "Snippet: " . $result->getSnippet() . "\n"; } echo "\n"; } } catch (SearchException $e) { error_log('Search failed: ' . $e->getMessage()); } ``` -------------------------------- ### Configure Minimal Service Instance Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Demonstrates a basic setup using PSR-compliant dependencies and direct credential injection. ```php use YandexSearchAPI\YandexSearchService; use Nyholm\Psr7\Factory\Psr17Factory; use Symfony\Component\HttpClient\Psr18Client; use Psr\Log\NullLogger; // Create dependencies $httpClient = new Psr18Client(); $factory = new Psr17Factory(); $logger = new NullLogger(); // Initialize service with credentials $service = new YandexSearchService( $httpClient, $factory, $logger, 'your-folder-id', // From Yandex Cloud 'your-api-key' // From Yandex Cloud ); // Ready to search $request = new SearchRequest('query'); $response = $service->search($request); ``` -------------------------------- ### Install via Composer Source: https://github.com/starkeen/yandex-search-api/blob/main/README.md Use this command to add the library to your project dependencies. ```bash composer require starkeen/yandex-search-api ``` -------------------------------- ### Complete Search Request Configuration Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Example demonstrating a full configuration of a search request and its execution. ```php use YandexSearchAPI\SearchRequest; use YandexSearchAPI\constant\Language; use YandexSearchAPI\constant\Sort; use YandexSearchAPI\constant\Filter; $request = new SearchRequest('machine learning tutorials'); // Pagination $request->setNumResults(50); $request->setPage(0); // Content preferences $request->setMaxPassages(5); $request->setLanguage(Language::ENGLISH); $request->setSort(Sort::DATE); $request->setFilter(Filter::STRICT); // Execute $response = $service->search($request); ``` -------------------------------- ### Configure Laminas Diactoros Factories Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Demonstrates factory setup for Laminas Diactoros, noting the preference for Nyholm factories for PSR-18 compatibility. ```php use Laminas\Diactoros\RequestFactory; use Laminas\Diactoros\StreamFactory; $factory = new RequestFactory(); // Note: RequestFactory doesn't implement StreamFactory, use combined: // Laminas\Diactoros\RequestFactory + custom stream handling // Or use Nyholm with Laminas HTTP client adapter use Nyholm\Psr7\Factory\Psr17Factory; $factory = new Psr17Factory(); ``` -------------------------------- ### Set Search Language Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/types.md Example of applying a language constant to a SearchRequest instance. ```php use YandexSearchAPI\constant\Language; use YandexSearchAPI\SearchRequest; $request = new SearchRequest('query'); $request->setLanguage(Language::ENGLISH); ``` -------------------------------- ### Apply Filter to Search Request Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/types.md Example of setting the content filter level on a search request instance. ```php use YandexSearchAPI\constant\Filter; use YandexSearchAPI\SearchRequest; $request = new SearchRequest('query'); $request->setFilter(Filter::STRICT); ``` -------------------------------- ### Internal usage in ResultsParser Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/ResultsCollection.md Example of how the collection is populated internally during the parsing process. ```php // Inside ResultsParser::parse() $collection = new ResultsCollection(); foreach ($grouping->getGroups() as $group) { foreach ($group->getDocuments() as $doc) { $resultItem = new Result(...); $collection->appendResult($resultItem); } } $response->setResultsCollection($collection); ``` -------------------------------- ### Get sort order Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchRequest.md Retrieves the current sort order setting. ```php public function getSort(): string ``` -------------------------------- ### Get language Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchRequest.md Retrieves the current search result language setting. ```php public function getLanguage(): string ``` -------------------------------- ### Set page number Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchRequest.md Sets the page number for pagination starting from 0. ```php public function setPage(int $page): void ``` ```php $request->setPage(2); // Get 3rd page of results ``` -------------------------------- ### Get search query Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchRequest.md Retrieves the current search query string. ```php public function getQuery(): string ``` -------------------------------- ### Get filter level Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchRequest.md Retrieves the current adult content filter level. ```php public function getFilter(): string ``` -------------------------------- ### Configure and execute a search request in PHP Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchRequest.md Demonstrates initializing a search query and applying configuration settings for pagination, language, sorting, and filtering. ```php use YandexSearchAPI\SearchRequest; use YandexSearchAPI\constant\Language; use YandexSearchAPI\constant\Sort; use YandexSearchAPI\constant\Filter; $request = new SearchRequest('machine learning'); // Configure pagination $request->setNumResults(25); $request->setPage(0); // Configure presentation $request->setMaxPassages(5); // Configure filtering $request->setLanguage(Language::ENGLISH); $request->setSort(Sort::RELEVANCE); $request->setFilter(Filter::STRICT); // Use with service $response = $service->search($request); ``` -------------------------------- ### Perform a Search Request Source: https://github.com/starkeen/yandex-search-api/blob/main/README.md Initialize the service with PSR-compliant dependencies and credentials, then execute a search query. ```php search($searchRequest); // Process the results foreach ($response->getResults() as $result) { echo 'Title: ' . $result->getTitle() . PHP_EOL; echo 'URL: ' . $result->getUrl() . PHP_EOL; echo 'Domain: ' . $result->getDomain() . PHP_EOL; echo 'Snippet: ' . $result->getSnippet() . PHP_EOL; } } catch (SearchException $e) { echo $e->getMessage(); } ``` -------------------------------- ### Initialize and execute a search request in PHP Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/00-START-HERE.md Demonstrates the full lifecycle of a search request, including service initialization with PSR-compliant dependencies and handling of search results, pagination, and spelling corrections. ```php use YandexSearchAPI\YandexSearchService; use YandexSearchAPI\SearchRequest; use YandexSearchAPI\constant\Language; // Initialize service $service = new YandexSearchService( $httpClient, // PSR-18 $httpFactory, // PSR-17 $logger, // PSR-3 'folder-id', // From Yandex Cloud 'api-key' // From Yandex Cloud ); // Create request $request = new SearchRequest('query'); $request->setNumResults(20); $request->setLanguage(Language::ENGLISH); // Execute search try { $response = $service->search($request); // Access results foreach ($response->getResults() as $result) { echo $result->getTitle() . "\n"; echo $result->getURL() . "\n"; } // Access pagination $pagination = $response->getPagination(); echo "Page " . ($pagination->getCurrentPage() + 1) . "\n"; // Check spelling correction if ($response->getCorrection()) { echo "Did you mean: " . $response->getCorrection()->getResultText() . "?\n"; } } catch (SearchException $e) { error_log('Search failed: ' . $e->getMessage()); } ``` -------------------------------- ### Configure Service with Environment Variables Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Recommended approach for production environments, utilizing environment variables for credentials and Monolog for logging. ```php use YandexSearchAPI\YandexSearchService; use Nyholm\Psr7\Factory\Psr17Factory; use Symfony\Component\HttpClient\Psr18Client; use Monolog\Logger; use Monolog\Handlers\StreamHandler; // Load from environment $apiId = getenv('YANDEX_FOLDER_ID'); $apiKey = getenv('YANDEX_API_KEY'); if (!$apiId || !$apiKey) { throw new Exception('Missing Yandex credentials in environment'); } // Setup logging $logger = new Logger('yandex-search'); $logger->pushHandler(new StreamHandler('php://stderr', Logger::ERROR)); // Create service $service = new YandexSearchService( new Psr18Client(), new Psr17Factory(), $logger, $apiId, $apiKey ); ``` -------------------------------- ### Validating Configuration with Exception Handling Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/errors.md Shows how to safely set request parameters like language and catch potential configuration exceptions when inputs are dynamic. ```php use YandexSearchAPI\ConfigurationException; use YandexSearchAPI\constant\Language; try { // Set language safely $language = $_GET['lang'] ?? 'ru'; $request = new SearchRequest('query'); $request->setLanguage($language); // May throw ConfigurationException } catch (ConfigurationException $e) { echo 'Invalid language: ' . htmlspecialchars($language); echo 'Valid options: ru, en, tr'; } ``` -------------------------------- ### Get max passages Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchRequest.md Retrieves the maximum number of text passages per document. ```php public function getMaxPassages(): int ``` -------------------------------- ### Initialize YandexSearchService Source: https://github.com/starkeen/yandex-search-api/blob/main/README.md Inject credentials directly into the constructor. Avoid hard-coding by using environment variables or configuration files. ```php $service = new YandexSearchService($httpClient, $factory, $logger, 'abcdefg', 'A1B2C3D4'); ``` -------------------------------- ### Catching ConfigurationException in PHP Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/errors.md Demonstrates how to wrap service calls and request configurations in a try-catch block to handle configuration-related exceptions. ```php use YandexSearchAPI\ConfigurationException; try { $service = new YandexSearchService($client, $factory, $logger); $request = new SearchRequest('test'); $request->setLanguage('invalid'); // Throws ConfigurationException $response = $service->search($request); // Throws ConfigurationException } catch (ConfigurationException $e) { // Handle configuration errors error_log('Configuration error: ' . $e->getMessage()); } ``` -------------------------------- ### Executing a search request Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/YandexSearchService.md Demonstrates configuring a search request and handling the response or potential exceptions. ```php use YandexSearchAPI\SearchRequest; use YandexSearchAPI\SearchException; $request = new SearchRequest('PHP programming'); $request->setNumResults(20); try { $response = $service->search($request); foreach ($response->getResults() as $result) { echo $result->getTitle() . "\n"; echo $result->getURL() . "\n"; } } catch (SearchException $e) { error_log('Search failed: ' . $e->getMessage()); } ``` -------------------------------- ### Instantiate a Result object Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/Result.md Create a new Result instance by providing the document title, URL, and an optional snippet. ```php use YandexSearchAPI\Result; $result = new Result( 'PHP Official Website', 'https://www.php.net/', 'PHP: Hypertext Preprocessor is a widely-used open source general-purpose scripting...' ); ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Define required credentials and logging levels in a .env file. ```bash # .env file YANDEX_FOLDER_ID=your-folder-id YANDEX_API_KEY=your-api-key YANDEX_LOG_LEVEL=error ``` -------------------------------- ### Handle Configuration and Runtime Exceptions in PHP Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/errors.md Differentiate between developer-level configuration errors and runtime search failures to improve error logging and recovery. ```php use YandexSearchAPI\ConfigurationException; use YandexSearchAPI\SearchException; try { $service = new YandexSearchService($client, $factory, $logger, $apiId, $apiKey); $request = new SearchRequest($_GET['q'] ?? ''); $response = $service->search($request); } catch (ConfigurationException $e) { // Configuration issues - usually developer error error_log('CRITICAL: ' . $e->getMessage()); // Contact developer } catch (SearchException $e) { // Runtime issues - may be transient error_log('Search failed: ' . $e->getMessage()); // Retry or notify user } ``` -------------------------------- ### Get Passage Text Internal Method Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/ResultsParser.md Signature for the private method used to concatenate multiple passage fragments into a single snippet string. ```php private function getPassageText(array $passages): string ``` -------------------------------- ### Execute a Search Request Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/README.md Initialize the service with PSR-18 dependencies and execute a search query. Ensure you have valid folder ID and API key credentials from Yandex Cloud. ```php use YandexSearchAPI\YandexSearchService; use YandexSearchAPI\SearchRequest; use YandexSearchAPI\SearchException; use Nyholm\Psr7\Factory\Psr17Factory; use Symfony\Component\HttpClient\Psr18Client; use Psr\Log\NullLogger; // Create service dependencies $factory = new Psr17Factory(); $httpClient = new Psr18Client(); $logger = new NullLogger(); // Initialize service $service = new YandexSearchService( $httpClient, $factory, $logger, 'your-folder-id', // From Yandex Cloud 'your-api-key' // From Yandex Cloud ); // Create and configure search request $request = new SearchRequest('your search query'); $request->setNumResults(20); // Execute search try { $response = $service->search($request); // Process results foreach ($response->getResults() as $result) { echo $result->getTitle() . "\n"; echo $result->getURL() . "\n\n"; } } catch (SearchException $e) { error_log('Search failed: ' . $e->getMessage()); } ``` -------------------------------- ### Initialize SearchRequest Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchRequest.md Instantiate a new search request object with a required query string. ```php use YandexSearchAPI\SearchRequest; $request = new SearchRequest('Russian literature'); ``` -------------------------------- ### Handle Configuration Exceptions Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/MODULE-REFERENCE.md Catches errors related to invalid configuration settings or missing credentials. ```php try { $request->setLanguage('invalid'); } catch (ConfigurationException $e) { error_log($e->getMessage()); } ``` -------------------------------- ### Implement Service Factory for Dependency Injection Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Create a factory class to instantiate the service with required dependencies from a PSR container. ```php use Psr\\Container\\ContainerInterface; class YandexSearchServiceFactory { public function __invoke(ContainerInterface $container) { return new YandexSearchService( $container->get('httpClient'), $container->get('httpFactory'), $container->get('logger'), getenv('YANDEX_FOLDER_ID'), getenv('YANDEX_API_KEY') ); } } ``` -------------------------------- ### Pagination Constructor Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/MODULE-REFERENCE.md Initializes the pagination metadata container. ```php public function __construct(): void ``` -------------------------------- ### Instantiate and Use ResultsParser Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/ResultsParser.md Demonstrates the internal usage of the ResultsParser class. This is intended for internal library use and should not be called directly by consumers. ```php use YandexSearchAPI\parser\ResultsParser; // This is called internally by YandexSearchService // Do not call directly unless working with raw XML parsing $parser = new ResultsParser(); $response = $parser->parse($request, $xmlResponse); ``` -------------------------------- ### Process Search Results in PHP Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchResponse.md Demonstrates how to execute a search request, handle potential exceptions, and iterate through results with pagination and spelling correction metadata. ```php use YandexSearchAPI\SearchRequest; use YandexSearchAPI\SearchException; $request = new SearchRequest('Python tutorial'); $request->setNumResults(20); try { $response = $service->search($request); // Get request metadata echo 'Request ID: ' . $response->getRequestID() . "\n\n"; // Check for spelling correction $correction = $response->getCorrection(); if ($correction !== null) { echo 'Note: Did you mean "' . $correction->getResultText() . '"?' . "\n\n"; } // Display results with pagination $pagination = $response->getPagination(); if ($pagination !== null) { echo 'Found ' . $pagination->getTotal() . ' results' . "\n"; echo 'Page ' . ($pagination->getCurrentPage() + 1) . ' of ' . $pagination->getPagesCount() . "\n\n"; } // Display each result foreach ($response->getResults() as $index => $result) { echo ($index + 1) . '. ' . $result->getTitle() . "\n"; echo ' URL: ' . $result->getURL() . "\n"; if ($result->getSnippet()) { echo ' ' . substr($result->getSnippet(), 0, 100) . '...' . "\n"; } echo "\n"; } } catch (SearchException $e) { echo 'Search error: ' . $e->getMessage() . "\n"; } ``` -------------------------------- ### Construct SearchResponse Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchResponse.md Initializes a new instance of the SearchResponse class using the original search request. ```php public function __construct(SearchRequest $request): void ``` -------------------------------- ### Load Environment Variables in PHP Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Utilize the DotEnv library to load configuration into the global environment. ```php use DotEnv\\\DotEnv; $dotenv = DotEnv::createImmutable(__DIR__); $dotenv->load(); $apiId = $_ENV['YANDEX_FOLDER_ID']; $apiKey = $_ENV['YANDEX_API_KEY']; ``` -------------------------------- ### Project File Structure Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/INDEX.md Visual representation of the project's documentation directory layout. ```text output/ ├── INDEX.md (this file) ├── README.md (overview and quick start) ├── MODULE-REFERENCE.md (complete module reference) ├── types.md (type definitions and constants) ├── configuration.md (setup and configuration) ├── errors.md (exception reference) └── api-reference/ ├── YandexSearchService.md ├── SearchRequest.md ├── SearchResponse.md ├── Result.md ├── Pagination.md ├── Correction.md ├── ResultsParser.md └── ResultsCollection.md ``` -------------------------------- ### Constructor definition for YandexSearchService Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/YandexSearchService.md Defines the required dependencies and optional credentials for initializing the service. ```php public function __construct( ClientInterface $client, RequestFactoryInterface&StreamFactoryInterface $factory, LoggerInterface $logger, ?string $apiId = null, ?string $apiKey = null ): void ``` -------------------------------- ### SearchRequest Constructor Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Initializes a new search request with a required query string. ```APIDOC ## Constructor: YandexSearchAPI\SearchRequest ### Description Initializes a new search request object. ### Parameters - **$query** (string) - Required - The search query string. ``` -------------------------------- ### Implement Full Correction Workflow Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/Correction.md Demonstrates checking for a correction and either displaying a hint or performing a new search. ```php use YandexSearchAPI\SearchRequest; use YandexSearchAPI\SearchException; $request = new SearchRequest('Artifical Intelligence'); // Misspelled $response = $service->search($request); $correction = $response->getCorrection(); if ($correction !== null) { // Display spelling correction hint to user echo 'Did you mean: ' . $correction->getResultText() . '?' . "\n"; echo 'Original query: ' . $correction->getSourceText() . "\n\n"; // Option 1: Show results but with a hint echo 'Showing results for: "' . $correction->getSourceText() . '"' . "\n"; echo '(Search for "' . $correction->getResultText() . '" instead?)' . "\n\n"; // Option 2: Re-search with corrected query if (userWantsCorrection()) { $correctedRequest = new SearchRequest($correction->getResultText()); $correctedResponse = $service->search($correctedRequest); // Display corrected results } } else { echo 'No spelling suggestion available.' . "\n"; } foreach ($response->getResults() as $result) { echo $result->getTitle() . "\n"; } ``` -------------------------------- ### Verify PHP Environment Requirements Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Checks for the minimum required PHP version and the presence of necessary XML extensions. ```php // Check PHP version if (PHP_VERSION_ID < 80100) { throw new Exception('PHP 8.1+ required'); } // Check extensions if (!extension_loaded('simplexml') || !extension_loaded('libxml')) { throw new Exception('ext-simplexml and ext-libxml required'); } ``` -------------------------------- ### Configure Symfony HttpClient Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Initializes the YandexSearchService using the Symfony PSR-18 client. ```php use Symfony\Component\HttpClient\Psr18Client; use Nyholm\Psr7\Factory\Psr17Factory; $httpClient = new Psr18Client(); $factory = new Psr17Factory(); $service = new YandexSearchService( $httpClient, $factory, $logger, $apiId, $apiKey ); ``` -------------------------------- ### Catching SearchException Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/errors.md Basic implementation for catching and logging search-related exceptions. ```php use YandexSearchAPI\SearchException; try { $response = $service->search($request); } catch (SearchException $e) { // Handle search errors error_log('Search failed: ' . $e->getMessage()); error_log('Exception code: ' . $e->getCode()); if ($e->getPrevious() !== null) { error_log('Root cause: ' . $e->getPrevious()->getMessage()); } } ``` -------------------------------- ### Configuration Methods Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Methods to configure search parameters such as pagination, language, sorting, and filtering. ```APIDOC ## setNumResults(int $numResults) Sets the number of results per page (1-100). ## setPage(int $page) Sets the page number for pagination (0-indexed). ## setMaxPassages(int $maxPassages) Sets the number of text passages extracted per result (1+). ## setLanguage(string $language) Sets the language of search results using Language constants. ## setSort(string $sort) Sets the sort order of results using Sort constants. ## setFilter(string $filter) Sets adult content filtering level using Filter constants. ``` -------------------------------- ### Convert Markdown to HTML using Pandoc Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/INDEX.md Use these commands to generate HTML files from the project's Markdown documentation. ```bash pandoc README.md -o README.html pandoc api-reference/*.md -o api-reference.html # etc. ``` -------------------------------- ### Handle Search API Exceptions in PHP Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/errors.md Use try-catch blocks to differentiate between configuration and search-specific errors, logging relevant request context for debugging. ```php use YandexSearchAPI\SearchException; use YandexSearchAPI\ConfigurationException; try { $response = $service->search($request); } catch (ConfigurationException $e) { // Log configuration errors with full context $logger->critical('Search configuration error', [ 'message' => $e->getMessage(), 'query' => $request->getQuery(), 'code' => $e->getCode(), ]); // Re-throw or return error to client throw $e; } catch (SearchException $e) { // Log search errors with request info $logger->error('Search API error', [ 'message' => $e->getMessage(), 'query' => $request->getQuery(), 'code' => $e->getCode(), 'previous' => $e->getPrevious() ? $e->getPrevious()->getMessage() : null, ]); // Return appropriate response to client return null; } ``` -------------------------------- ### Result Constructor Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/MODULE-REFERENCE.md Creates a representation of a single search result. ```php public function __construct(string $title, string $url, ?string $snippet): void ``` -------------------------------- ### Accessing API constants for configuration Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/00-START-HERE.md Lists the available constants for language, sorting, and filtering options used to configure search requests. ```php use YandexSearchAPI\constant\Language; use YandexSearchAPI\constant\Sort; use YandexSearchAPI\constant\Filter; Language::RUSSIAN; Language::ENGLISH; Language::TURKISH; Sort::RELEVANCE; Sort::DATE; Filter::NONE; Filter::MODERATE; Filter::STRICT; ``` -------------------------------- ### Display project file structure Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/README.md Visual representation of the source directory layout for the Yandex Search API service. ```text src/ ├── YandexSearchService.php # Main service class ├── SearchRequest.php # Search query configuration ├── SearchResponse.php # Search results container ├── Result.php # Individual result ├── Pagination.php # Result pagination ├── Correction.php # Spelling correction ├── SearchException.php # Search error exception ├── ConfigurationException.php # Configuration error exception ├── constant/ │ ├── Language.php # Language constants │ ├── Sort.php # Sort order constants │ └── Filter.php # Filter level constants ├── parser/ │ └── ResultsParser.php # XML response parser ├── dto/ │ └── ResultsCollection.php # Results collection └── xml/ ├── ResponseRoot.php ├── Response.php ├── Results.php ├── Grouping.php ├── Group.php ├── Document.php ├── Passage.php ├── Error.php ├── Misspelling.php └── Request.php ``` -------------------------------- ### Execute a Simple Search Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/README.md Perform a basic search query and iterate through the returned results. ```php $request = new SearchRequest('php programming'); $response = $service->search($request); foreach ($response->getResults() as $result) { echo $result->getTitle() . "\n"; } ``` -------------------------------- ### Configure Guzzle 7+ HTTP Client Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Initializes the YandexSearchService using Guzzle 7, which supports PSR-18 natively. ```php use GuzzleHttp\Client as GuzzleClient; use Nyholm\Psr7\Factory\Psr17Factory; $httpClient = new GuzzleClient(); $factory = new Psr17Factory(); $service = new YandexSearchService( $httpClient, $factory, $logger, $apiId, $apiKey ); ``` -------------------------------- ### Handle Pagination Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchResponse.md Retrieves or sets pagination information. Returns null if no results were found. ```php public function getPagination(): ?Pagination ``` ```php $pagination = $response->getPagination(); if ($pagination !== null) { echo 'Total found: ' . $pagination->getTotal() . "\n"; echo 'Current page: ' . $pagination->getCurrentPage() . "\n"; echo 'Total pages: ' . $pagination->getPagesCount() . "\n"; } ``` ```php public function setPagination(?Pagination $pagination): void ``` -------------------------------- ### Configure Monolog with Rotating File Handler Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Use RotatingFileHandler to manage log files with automatic rotation. ```php use Monolog\Logger; use Monolog\Handlers\RotatingFileHandler; $logger = new Logger('yandex-search'); $logger->pushHandler(new RotatingFileHandler('logs/yandex', 30, Logger::ERROR)); ``` -------------------------------- ### Append a result to the collection Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/ResultsCollection.md Demonstrates instantiating the collection and adding a new Result object. ```php use YandexSearchAPI\Result; use YandexSearchAPI\dto\ResultsCollection; $collection = new ResultsCollection(); $result = new Result( 'PHP Documentation', 'https://www.php.net/docs', 'The official PHP reference' ); $collection->appendResult($result); ``` -------------------------------- ### Instantiate Correction Object Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/Correction.md Create a new instance by providing the original misspelled query and the corrected version. ```php use YandexSearchAPI\Correction; $correction = new Correction( 'Pyton', 'Python' ); ``` -------------------------------- ### Configure Search Parameters Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/README.md Customize search behavior using language, sorting, and filtering constants. ```php use YandexSearchAPI\constant\Language; use YandexSearchAPI\constant\Sort; use YandexSearchAPI\constant\Filter; $request = new SearchRequest('query'); $request->setNumResults(25); $request->setLanguage(Language::ENGLISH); $request->setSort(Sort::DATE); $request->setFilter(Filter::MODERATE); ``` -------------------------------- ### Stable SDK Classes Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/MODULE-REFERENCE.md List of stable classes and components available for public use. ```APIDOC ## Stable SDK Classes The following classes and components are guaranteed to be stable: - `YandexSearchService`: Main service class and public methods. - `SearchRequest`: Configuration and request building. - `SearchResponse`: Result handling and response objects. - `Result`, `Pagination`, `Correction`: Data structures for search results. - `SearchException`, `ConfigurationException`: Standardized exception handling. - `Language`, `Sort`, `Filter`: Constants for search configuration. ``` -------------------------------- ### Define ConfigurationException class Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/types.md Represents errors related to invalid configuration, such as missing credentials or invalid enum values. ```php class ConfigurationException extends RuntimeException { } ``` -------------------------------- ### Offer Suggestion Without Auto-Redirect Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/Correction.md Pattern for preparing correction data for a UI response without triggering an automatic search. ```php $correction = $response->getCorrection(); $data = [ 'results' => $response->getResults(), 'original_query' => $correction ? $correction->getSourceText() : null, 'suggested_query' => $correction ? $correction->getResultText() : null, ]; ``` -------------------------------- ### Import Yandex Search API Components Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/MODULE-REFERENCE.md Standard import statements required to access the main API services, exceptions, and configuration constants. ```php // Main API use YandexSearchAPI YandexSearchService; use YandexSearchAPI SearchRequest; use YandexSearchAPI SearchResponse; use YandexSearchAPI Result; use YandexSearchAPI Pagination; use YandexSearchAPI Correction; // Exceptions use YandexSearchAPI SearchException; use YandexSearchAPI ConfigurationException; // Constants use YandexSearchAPI constant Language; use YandexSearchAPI constant Sort; use YandexSearchAPI constant Filter; // Internal (rarely needed) use YandexSearchAPI parser ResultsParser; use YandexSearchAPI dto ResultsCollection; ``` -------------------------------- ### Configure Monolog with File Handler Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Use StreamHandler to log messages to a file or standard error stream. ```php use Monolog\Logger; use Monolog\Handlers\StreamHandler; $logger = new Logger('yandex-search'); $logger->pushHandler(new StreamHandler('logs/yandex-search.log', Logger::ERROR)); // Or log to stderr $logger->pushHandler(new StreamHandler('php://stderr', Logger::WARNING)); ``` -------------------------------- ### Retrieve all results from the collection Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/ResultsCollection.md Shows how to iterate through the collection after appending multiple results. ```php $collection = new ResultsCollection(); $collection->appendResult($result1); $collection->appendResult($result2); $allResults = $collection->getResults(); // [$result1, $result2] foreach ($allResults as $result) { echo $result->getTitle() . "\n"; } ``` -------------------------------- ### Service Usage vs Internal Parsing Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/ResultsParser.md Compares the standard public API usage with the internal parsing logic performed by the service. ```php // Users do this: $response = $service->search($request); // YandexSearchService does this internally: // $parser = new ResultsParser(); // $response = $parser->parse($request, $xmlResponse); ``` -------------------------------- ### Configure SearchRequest parameters Source: https://github.com/starkeen/yandex-search-api/blob/main/README.md Use SearchRequest setters to define query constraints. Passing invalid enum values to these methods will trigger a ConfigurationException. ```php use YandexSearchAPI\SearchRequest; use YandexSearchAPI\constant\Filter; use YandexSearchAPI\constant\Language; use YandexSearchAPI\constant\Sort; $request = new SearchRequest('php'); $request->setNumResults(20); // results per page (default 10) $request->setPage(1); // page number, starting from 0 $request->setMaxPassages(5); // passages per document (default 4) $request->setLanguage(Language::ENGLISH); // RUSSIAN (default) | ENGLISH | TURKISH $request->setSort(Sort::DATE); // RELEVANCE (default) | DATE $request->setFilter(Filter::STRICT); // NONE (default) | MODERATE | STRICT ``` -------------------------------- ### Configure NullLogger Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Use NullLogger to disable logging entirely. ```php use Psr\Log\NullLogger; $logger = new NullLogger(); ``` -------------------------------- ### SearchRequest Configuration Methods Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchRequest.md Methods for configuring and retrieving search request parameters. ```APIDOC ## SearchRequest Methods ### getQuery() Returns the search query string. ### getNumResults() / setNumResults(int $numResults) Gets or sets the number of results to return per page (default: 10). ### getPage() / setPage(int $page) Gets or sets the current page number (0-indexed). ### getMaxPassages() / setMaxPassages(int $maxPassages) Gets or sets the maximum number of text passages per document (default: 4). ### getLanguage() / setLanguage(string $language) Gets or sets the search result language. Valid values: `Language::RUSSIAN`, `Language::ENGLISH`, `Language::TURKISH`. ### getSort() / setSort(string $sort) Gets or sets the sort order. Valid values: `Sort::RELEVANCE`, `Sort::DATE`. ### getFilter() / setFilter(string $filter) Gets or sets the adult content filter level. Valid values: `Filter::NONE`, `Filter::MODERATE`, `Filter::STRICT`. ``` -------------------------------- ### Exception Hierarchy Structure Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/errors.md Visual representation of the library's exception class inheritance. ```text Throwable └── Exception └── RuntimeException ├── SearchException (YandexSearchAPI\SearchException) └── ConfigurationException (YandexSearchAPI\ConfigurationException) ``` -------------------------------- ### Handle Search Errors Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/README.md Catch specific exceptions related to configuration or API search failures. ```php use YandexSearchAPI\SearchException; use YandexSearchAPI\ConfigurationException; try { $response = $service->search($request); } catch (ConfigurationException $e) { // Handle configuration errors } catch (SearchException $e) { // Handle search/API errors } ``` -------------------------------- ### Implement Custom PSR-3 Logger Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Create a custom class implementing LoggerInterface to define specific logging behavior. ```php use Psr\Log\LoggerInterface; class SimpleLogger implements LoggerInterface { public function emergency($message, array $context = []) {} public function alert($message, array $context = []) {} public function critical($message, array $context = []) { error_log($message); } public function error($message, array $context = []) { error_log($message); } public function warning($message, array $context = []) {} public function notice($message, array $context = []) {} public function info($message, array $context = []) {} public function debug($message, array $context = []) {} public function log($level, $message, array $context = []) { error_log("[$level] $message"); } } $logger = new SimpleLogger(); ``` -------------------------------- ### Paginate Through Results Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/README.md Configure page index and result count to navigate through search results. ```php $request = new SearchRequest('query'); $request->setPage(0); $request->setNumResults(10); $response = $service->search($request); if ($response->getPagination()) { echo 'Page ' . ($pagination->getCurrentPage() + 1) . ' of ' . $pagination->getPagesCount(); } ``` -------------------------------- ### Register Service in Pimple Container Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Register the factory within a Pimple container instance. ```php $container['yandex.service'] = $container->factory( new YandexSearchServiceFactory() ); $service = $container['yandex.service']; ``` -------------------------------- ### Configure Pagination Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Sets the 0-indexed page number for search results. ```php $request->setPage(0); // First page $request->setPage(1); // Second page $request->setPage(2); // Third page ``` -------------------------------- ### Retrieve result URL Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/Result.md Access the full document URL. ```php echo $result->getURL(); // "https://www.php.net/" ``` -------------------------------- ### Retrieve result domain Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/Result.md Extract the hostname from the document URL. Throws a SearchException if the URL is invalid. ```php echo $result->getDomain(); // "www.php.net" ``` -------------------------------- ### Build Pagination Internal Method Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/ResultsParser.md Signature for the private method used to extract pagination details from the XML grouping element. ```php private function buildPagination(Grouping $grouping): Pagination ``` -------------------------------- ### Accessing results via SearchResponse Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/ResultsCollection.md Standard way for library users to access results, abstracting the internal collection. ```php // Users do this: $response = $service->search($request); $results = $response->getResults(); // Returns array of Result objects // Internally, SearchResponse uses: // $this->resultsCollection->getResults() ``` -------------------------------- ### Implement Retry Logic for Transient Errors in PHP Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/errors.md Use exponential backoff to retry search requests when encountering transient errors like rate limits or HTTP 5xx codes. ```php use YandexSearchAPI\SearchException; function searchWithRetry($service, $request, $maxRetries = 3) { for ($attempt = 1; $attempt <= $maxRetries; $attempt++) { try { return $service->search($request); } catch (SearchException $e) { // Check if error is retryable if ($attempt < $maxRetries && isRetryable($e)) { sleep(2 ** $attempt); // Exponential backoff continue; } throw $e; } } } function isRetryable(SearchException $e) { $code = $e->getCode(); // Retry on rate limit (18) or generic errors return $code === 18 || $code === 0 || str_contains($e->getMessage(), 'HTTP 5'); } ``` -------------------------------- ### Validate Yandex API Configuration Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/configuration.md Ensures that the folder ID and API key are present and meet minimum length requirements before initialization. ```php function validateYandexConfig($apiId, $apiKey) { if (!$apiId) { throw new Exception('YANDEX_FOLDER_ID not set'); } if (!$apiKey) { throw new Exception('YANDEX_API_KEY not set'); } if (strlen($apiId) < 5) { throw new Exception('Invalid YANDEX_FOLDER_ID'); } if (strlen($apiKey) < 10) { throw new Exception('Invalid YANDEX_API_KEY'); } } validateYandexConfig( getenv('YANDEX_FOLDER_ID'), getenv('YANDEX_API_KEY') ); ``` -------------------------------- ### SearchRequest Configuration Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/SearchRequest.md Methods available for configuring a search request object before execution. ```APIDOC ## SearchRequest ### Description Configures the parameters for a Yandex search query. ### Methods - **__construct(string $query)** - Initializes the request with a search string. - **setNumResults(int $num)** - Sets the number of results to return. - **setPage(int $page)** - Sets the page index for pagination. - **setMaxPassages(int $max)** - Sets the maximum number of passages to return. - **setLanguage(Language $lang)** - Sets the language filter for results. - **setSort(Sort $sort)** - Sets the sorting order for results. - **setFilter(Filter $filter)** - Sets the content filter level. ``` -------------------------------- ### Displaying Search Pagination in PHP Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/Pagination.md Retrieves pagination metadata from a SearchResponse object to display result counts and navigation instructions. Requires a valid SearchRequest and service instance. ```php use YandexSearchAPI\SearchRequest; use YandexSearchAPI\constant\Sort; // Search for first page $request = new SearchRequest('Laravel tutorials'); $request->setNumResults(10); $request->setPage(0); $response = $service->search($request); $pagination = $response->getPagination(); if ($pagination !== null) { echo 'Search Results' . "\n"; echo '==============' . "\n\n"; // Display pagination summary if ($pagination->getTotalHuman() !== null) { echo $pagination->getTotalHuman() . "\n"; } if ($pagination->getTotal() !== null) { echo 'Page ' . ($pagination->getCurrentPage() + 1) . ' of ' . $pagination->getPagesCount() . "\n"; echo 'Items ' . ($pagination->getCurrentPage() * $pagination->getPageSize() + 1) . ' to ' . min(($pagination->getCurrentPage() + 1) * $pagination->getPageSize(), $pagination->getTotal()) . "\n\n"; } // Display results $results = $response->getResults(); foreach ($results as $index => $result) { $resultNumber = ($pagination->getCurrentPage() * $pagination->getPageSize()) + $index + 1; echo $resultNumber . '. ' . $result->getTitle() . "\n"; } // Navigation hint if ($pagination->getPagesCount() > 1) { echo "\nNext page available: set \$request->setPage(" . ($pagination->getCurrentPage() + 1) . ");\n"; } } ``` -------------------------------- ### Calculate total pages Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/api-reference/Pagination.md Determine the total number of pages based on the total documents and page size. ```php $pagination = $response->getPagination(); if ($pagination !== null) { $totalPages = $pagination->getPagesCount(); echo 'Total pages: ' . $totalPages; } ``` -------------------------------- ### search() Source: https://github.com/starkeen/yandex-search-api/blob/main/README.md Executes a search request and returns a SearchResponse object containing results, pagination, and spelling correction data. ```APIDOC ## search() ### Description Performs a search query using the Yandex Search API and returns a `YandexSearchAPI\SearchResponse` object. ### Method `$service->search($request)` ### Response - **getRequestID()** (string) - Returns the unique Yandex request ID. - **getResults()** (array) - Returns a collection of result objects containing title, url, domain, and snippet. - **getPagination()** (object|null) - Returns pagination details including total documents, current page, and page size. - **getCorrection()** (object|null) - Returns spelling correction suggestions if available. ``` -------------------------------- ### Handling Specific API Errors Source: https://github.com/starkeen/yandex-search-api/blob/main/_autodocs/errors.md Demonstrates how to handle specific API error codes returned by Yandex. ```php use YandexSearchAPI\SearchException; try { $response = $service->search($request); } catch (SearchException $e) { $code = $e->getCode(); switch ($code) { case 17: error_log('Invalid API key'); // Prompt user to check credentials break; case 18: error_log('Rate limit exceeded, backing off'); sleep(60); // Wait before retry break; case 15: error_log('Invalid query: ' . $e->getMessage()); // Invalid query syntax break; default: error_log('Unhandled error: ' . $e->getMessage()); } } ```