Skip to content

Commit

Permalink
Merge branch 'Hi-Folks:main' into patch-1
Browse files Browse the repository at this point in the history
  • Loading branch information
wildwalks authored Oct 11, 2024
2 parents d08a7f8 + 1d35246 commit 75b0506
Show file tree
Hide file tree
Showing 9 changed files with 147 additions and 5 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## WIP
- Implementing a Trait for formatting data
- Implementing getFormattedDateTime for getting value as formatted data

## 0.3.10 - 2024-10-07
- Implementing the `saveToJson()` method

## 0.3.9 - 2024-08-08
- Implementing the `exists()` method

Expand Down
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,19 @@ $value = $data->get(
); // 🫠
```

### The `getFormattedDateTime()` for getting and formatting a date-time field value

When working with date-time fields, consider utilizing the `getFormattedDateTime()` method instead of relying solely on `get()`. This approach not only retrieves the value but also formats it according to the specified date-time format, as defined by the second optional parameter `$format`.

By default, this formatting is set to "Y-m-d H:i:s", providing a convenient and standardized output. However, customizing the format allows for more flexibility in presenting your data.

Here are some key points:

* `getFormattedDateTime()` combines the functionality of `get()` with date-time formatting.
* The second parameter `$format` controls the date-time format used for formatting.
* Custom formats can be applied to provide tailored outputs for different use cases.


### The `getBlock()` method
If you need to manage a complex array (nested array) or an array obtained from a complex JSON structure, you can access a portion of the array and obtain the `Block` object via the `getBlock()` method.

Expand Down Expand Up @@ -293,6 +306,21 @@ $data = Block::make($fruitsArray);
$yamlString = $data->toYaml(); // YAML string
```

### Saving JSON to a file with `saveToJson()`
If you need to save the JSON string in a file using the content of the Block object, you can use the `saveToJson()` method.

This is helpful when you are manipulating data with the Block class and at a certain point need to save the data in JSON string format to a file.
The `saveToJson()` method has two parameters:

- `filename`: the first parameter (mandatory) with the filename;
- `overwrite`: the second parameter (optional), If the file exists, the file is not saved by default, unless you set the overwrite parameter as true.

```php
$data = Block::make($fruitsArray);
$jsonString = $data->saveToJson('./fruits.json', true);
```


## Loading Data

### Loading Data from JSON file
Expand Down
3 changes: 3 additions & 0 deletions src/Block.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use HiFolks\DataType\Traits\EditableBlock;
use HiFolks\DataType\Traits\QueryableBlock;
use HiFolks\DataType\Traits\ExportableBlock;
use HiFolks\DataType\Traits\FormattableBlock;
use HiFolks\DataType\Traits\IteratableBlock;
use HiFolks\DataType\Traits\LoadableBlock;
use HiFolks\DataType\Traits\ValidableBlock;
Expand All @@ -29,6 +30,8 @@ final class Block implements Iterator, ArrayAccess, Countable
use LoadableBlock;
use IteratableBlock;
use ValidableBlock;
use FormattableBlock;


/** @var array<int|string, mixed> */
private array $data;
Expand Down
23 changes: 20 additions & 3 deletions src/Traits/ExportableBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
trait ExportableBlock
{
/**
* Returns the native array
* @return array<int|string, mixed>
*/
* Returns the native array
* @return array<int|string, mixed>
*/
public function toArray(): array
{
return $this->data;
Expand Down Expand Up @@ -53,4 +53,21 @@ public function toYaml(): string
{
return Yaml::dump($this->data, 3, 2);
}

/**
* Saves the JSON String to a file
* @param string $filename file name for example "./file.json"
* @param bool $overwrite if the file already exists you can force overwriting
* @return bool true if the file is saved, if already exists and you don't want to
* force overwiting the file it returns false
*/
public function saveToJson(string $filename, bool $overwrite = false): bool
{
if (file_exists($filename) && !$overwrite) {
return false;
}

file_put_contents($filename, $this->toJson());
return true;
}
}
30 changes: 30 additions & 0 deletions src/Traits/FormattableBlock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace HiFolks\DataType\Traits;

trait FormattableBlock
{
/**
* Get and format as date the element with $key
* @param mixed $key the key, can be nested for example "some.datetime"
* @param string $format the format default is "Y-m-d H:i:s"
* @param mixed $defaultValue, the value returned in the case the key not exists
* @param non-empty-string $charNestedKey the separator for nested keys, default is "."
*/
public function getFormattedDateTime(
mixed $key,
string $format = "Y-m-d H:i:s",
mixed $defaultValue = null,
string $charNestedKey = ".",
): string|null {
$value = $this->get($key, $defaultValue, $charNestedKey);
if (is_null($value)) {
return null;
}
$date = new \DateTimeImmutable($value);

return $date->format($format);
}
}
2 changes: 1 addition & 1 deletion src/Traits/QueryableBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public function groupBy(string|int $field): self

private static function castVariableForStrval(mixed $property): bool|float|int|string|null
{
return match(gettype($property)) {
return match (gettype($property)) {
'boolean' => $property,
'double' => $property,
'integer' => $property,
Expand Down
2 changes: 1 addition & 1 deletion tests/Feature/UrlTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
$posts = Block::fromJsonUrl($url)
->getBlock("posts")
->where(
field:"tags",
field: "tags",
operator: "in",
value: "love",
preseveKeys: false,
Expand Down
38 changes: 38 additions & 0 deletions tests/Unit/Traits/ExportableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,41 @@ function () use ($fruitsArray): void {
expect($string1)->toBe($string2);
},
);

test(
'Test saveToJson',
function () use ($fruitsArray): void {
$data = Block::make($fruitsArray);
$data->saveToJson('fruits.json');
expect(file_exists('fruits.json'))->toBeTrue();
unlink('fruits.json');
},
);

test(
'Test saveToJson with overwrite',
function () use ($fruitsArray): void {
$data = Block::make($fruitsArray);
$data->saveToJson('fruits.json');
expect(file_exists('fruits.json'))->toBeTrue();

$result = $data->saveToJson('fruits.json', true);
expect($result)->toBeTrue();

unlink('fruits.json');
},
);

test(
'Test saveToJson with existing file',
function () use ($fruitsArray): void {
$data = Block::make($fruitsArray);
$data->saveToJson('fruits.json');
expect(file_exists('fruits.json'))->toBeTrue();

$result = $data->saveToJson('fruits.json');
expect($result)->toBeFalse();

unlink('fruits.json');
},
);
19 changes: 19 additions & 0 deletions tests/Unit/Traits/FormattableBlokTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

use HiFolks\DataType\Block;

test(
'Format field to data',
function (): void {
$data1 = Block::fromJsonFile(__DIR__ . "/../../data/commits-json/commits-10-p1.json");
$data2 = Block::fromJsonFile(__DIR__ . "/../../data/commits-json/commits-10-p2.json");
$data3 = Block::fromJsonFile(__DIR__ . "/../../data/commits-json/commits-10-p3.json");

expect($data1)->toHaveCount(10);
expect($data2)->toHaveCount(10);
expect($data1->getFormattedDateTime("0.commit.author.date", "Y"))->toBe("2024");
expect($data1->getFormattedDateTime("0.commit.author.date", "Y-m-d"))->toBe("2024-06-28");
expect($data1->getFormattedDateTime("0.commit.author.dateNOTEXISTS", "Y-m-d"))->toBeNull();

},
);

0 comments on commit 75b0506

Please sign in to comment.