| 1 |
<?php |
| 2 |
|
| 3 |
namespace Code_Snippets\Cloud; |
| 4 |
|
| 5 |
use Code_Snippets\Data_Item; |
| 6 |
|
| 7 |
/** |
| 8 |
* A list of snippets as retrieved from the cloud API. |
| 9 |
* |
| 10 |
* @since 3.4.0 |
| 11 |
* @package Code_Snippets |
| 12 |
* |
| 13 |
* @property Cloud_Snippet[] $snippets List of snippet items for the current page. |
| 14 |
* @property integer $page Page of data that this data belongs to. |
| 15 |
* @property integer $total_pages Total number of available pages of items. |
| 16 |
* @property integer $total_snippets Total number of available snippet items. |
| 17 |
* @property array $cloud_id_rev An array of all cloud snippet IDs and their revision numbers. |
| 18 |
* @property bool $success If the request has any results. |
| 19 |
*/ |
| 20 |
class Cloud_Snippets extends Data_Item { |
| 21 |
|
| 22 |
/** |
| 23 |
* Class constructor. |
| 24 |
* |
| 25 |
* @param array<string, Cloud_Snippet[]|integer> $initial_data Initial data. |
| 26 |
*/ |
| 27 |
public function __construct( $initial_data = null ) { |
| 28 |
parent::__construct( |
| 29 |
[ |
| 30 |
'snippets' => [], |
| 31 |
'total_snippets' => 0, |
| 32 |
'total_pages' => 0, |
| 33 |
'page' => 0, |
| 34 |
'cloud_id_rev' => [], |
| 35 |
], |
| 36 |
$initial_data, |
| 37 |
[ |
| 38 |
'items' => 'snippets', |
| 39 |
'total_items' => 'total_snippets', |
| 40 |
'page' => 'page', |
| 41 |
'cloud_id_rev' => 'cloud_id_rev', |
| 42 |
] |
| 43 |
); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Prepare a value before it is stored. |
| 48 |
* |
| 49 |
* @param mixed $value Value to prepare. |
| 50 |
* @param string $field Field name. |
| 51 |
* |
| 52 |
* @return mixed Value in the correct format. |
| 53 |
*/ |
| 54 |
protected function prepare_field( $value, string $field ) { |
| 55 |
switch ( $field ) { |
| 56 |
case 'page': |
| 57 |
case 'total_pages': |
| 58 |
case 'total_snippets': |
| 59 |
return absint( $value ); |
| 60 |
|
| 61 |
default: |
| 62 |
return $value; |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* Prepare the `snippets` field by ensuring it is a list of Cloud_Snippets objects. |
| 68 |
* |
| 69 |
* @param mixed $snippets The field as provided. |
| 70 |
* |
| 71 |
* @return Cloud_Snippets[] The field in the correct format. |
| 72 |
*/ |
| 73 |
protected function prepare_snippets( $snippets ): array { |
| 74 |
$result = []; |
| 75 |
$snippets = is_array( $snippets ) ? $snippets : [ $snippets ]; |
| 76 |
|
| 77 |
foreach ( $snippets as $snippet ) { |
| 78 |
$result[] = $snippet instanceof Cloud_Snippet ? $snippet : new Cloud_Snippet( $snippet ); |
| 79 |
} |
| 80 |
|
| 81 |
return $result; |
| 82 |
} |
| 83 |
} |
| 84 |
|