Skip to content

Commit

Permalink
Merge pull request #79 from StanMenten99/feature/add-search-trait
Browse files Browse the repository at this point in the history
  • Loading branch information
Cannonb4ll authored Jul 12, 2024
2 parents 9a6d79d + 8400e44 commit 12bd790
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Ploi/Resources/Resource.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
use Ploi\Exceptions\Resource\RequiresId;
use Ploi\Ploi;
use Ploi\Traits\HasHistory;
use Ploi\Traits\HasSearch;

abstract class Resource
{
use HasHistory;
use HasHistory, HasSearch;

private $ploi;
private $action;
Expand Down
80 changes: 80 additions & 0 deletions src/Ploi/Traits/HasSearch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace Ploi\Traits;

use Ploi\Http\Response;
use Ploi\Ploi;

/**
* Trait HasSearch
*
* Provides search functionality for API calls.
*
* @package Ploi\Traits
*/
trait HasSearch
{
/**
* @var string|null
*/
protected $searchQuery;

/**
* Get the Ploi instance.
*
* @return Ploi|null
*/
abstract public function getPloi(): ?Ploi;

/**
* Get the API endpoint.
*
* @return string|null
*/
abstract public function getEndpoint(): ?string;

/**
* Set the search query.
*
* @param string|null $searchQuery
* @return self
*/
public function setSearchQuery(?string $searchQuery = null): self
{
$this->searchQuery = $searchQuery;

return $this;
}

/**
* Perform a search with the given query.
*
* @param string $searchQuery
* @return Response
* @throws \Exception
*/
public function search(string $searchQuery): Response
{
$ploi = $this->getPloi();
$endpoint = $this->getEndpoint();

if (is_null($ploi) || is_null($endpoint)) {
throw new \Exception('Ploi instance or endpoint is not set.');
}

return $ploi->makeAPICall(
$endpoint . $this->buildSearchQuery($searchQuery)
);
}

/**
* Build the search query string.
*
* @param string $searchQuery
* @return string
*/
protected function buildSearchQuery(string $searchQuery): string
{
return "?search={$searchQuery}";
}
}

0 comments on commit 12bd790

Please sign in to comment.