Skip to content

Commit ac9f79d

Browse files
authored
Merge pull request #54 from keboola/tf-fix-json-helper
Fix JsonHelper implementation and tests
2 parents 49accf7 + 56e909b commit ac9f79d

File tree

3 files changed

+19
-6
lines changed

3 files changed

+19
-6
lines changed

src/JsonHelper.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace Keboola\Component;
66

7+
use Keboola\Component\JsonHelper\JsonHelperException;
78
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
89
use Symfony\Component\Serializer\Encoder\JsonEncoder;
910

@@ -42,13 +43,13 @@ public static function writeFile(string $filePath, array $data, bool $formatted
4243
mkdir($filePathDir, 0777, true);
4344
}
4445

45-
$result = file_put_contents(
46+
$result = @file_put_contents(
4647
$filePath,
4748
self::encode($data, $formatted)
4849
);
4950

5051
if ($result === false) {
51-
throw new \ErrorException('Could not write to file "%s".');
52+
throw new JsonHelperException(sprintf('Could not write to file "%s".', $filePath));
5253
}
5354
}
5455
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Keboola\Component\JsonHelper;
6+
7+
use Exception;
8+
9+
class JsonHelperException extends Exception
10+
{
11+
}

tests/JsonHelperTest.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace Keboola\Component\Tests;
66

77
use Keboola\Component\JsonHelper;
8+
use Keboola\Component\JsonHelper\JsonHelperException;
89
use PHPUnit\Framework\TestCase;
910
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
1011
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
@@ -142,13 +143,13 @@ public function testWriteToNonExistingDirectorySuccessfully(): void
142143
rmdir(pathinfo($filePath, PATHINFO_DIRNAME));
143144
}
144145

145-
public function testWriteToProtectedDirectoryThrowsException(): void
146+
public function testFailedWriteThrowsException(): void
146147
{
147-
$filePath = '/tmp.json';
148+
$filePath = 'php://stdin';
148149
$array = ['key'];
149150

150-
$this->expectException(\ErrorException::class);
151-
$this->expectExceptionMessageRegExp('~^file_put_contents(.*): failed to open stream: Permission denied$~');
151+
$this->expectException(JsonHelperException::class);
152+
$this->expectExceptionMessage('Could not write to file "php://stdin".');
152153
JsonHelper::writeFile($filePath, $array);
153154
}
154155
}

0 commit comments

Comments
 (0)