Completed
Pull Request — master (#12)
by Harry
05:25
created

FileWriter::insertAll()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * This file is part of graze/data-file
4
 *
5
 * Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/data-file/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/data-file
12
 */
13
14
namespace Graze\DataFile\IO;
15
16
use Graze\DataFile\Format\FormatAwareInterface;
17
use Graze\DataFile\Format\FormatInterface;
18
use Graze\DataFile\Format\Formatter\FormatterFactory;
19
use Graze\DataFile\Format\Formatter\FormatterFactoryInterface;
20
use Graze\DataFile\Helper\OptionalLoggerTrait;
21
use Graze\DataFile\Node\FileNodeInterface;
22
use Graze\DataFile\Node\NodeStreamInterface;
23
use InvalidArgumentException;
24
25
class FileWriter extends StreamWriter
26
{
27
    use OptionalLoggerTrait;
28
29
    /**
30
     * FileReader constructor.
31
     *
32
     * @param FileNodeInterface              $file
33
     * @param FormatInterface|null           $format
34
     * @param FormatterFactoryInterface|null $formatterFactory
35
     */
36 7
    public function __construct(
37
        FileNodeInterface $file,
38
        FormatInterface $format = null,
39
        FormatterFactoryInterface $formatterFactory = null
40
    ) {
41 7
        if ($file instanceof NodeStreamInterface) {
42 6
            $stream = $file->getStream('c+b');
43 6
        } else {
44 1
            throw new InvalidArgumentException(
45 1
                "Only files that implement " . NodeStreamInterface::class . "can be written to"
46 1
            );
47
        }
48
49 6
        if (is_null($format)
50 6
            && $file instanceof FormatAwareInterface
51 6
        ) {
52 2
            $format = $file->getFormat();
53 2
        }
54
55 6
        if (is_null($format)) {
56 1
            throw new InvalidArgumentException("No format could be determined from \$file or \$format");
57
        }
58
59 5
        $factory = $formatterFactory ?: new FormatterFactory();
60 5
        $formatter = $factory->getFormatter($format);
61
62 5
        parent::__construct($stream, $formatter);
63 5
    }
64
}
65