Completed
Push — id3-metadata-objects ( e55453...161f4c )
by Daniel
11:12
created

TagWriter::padData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 3
1
<?php
2
/**
3
 * This file is part of the Metadata project.
4
 *
5
 * @author Daniel Schröder <[email protected]>
6
 */
7
8
namespace GravityMedia\Metadata\ID3v1\Writer;
9
10
use GravityMedia\Metadata\ID3v1\Enum\Version;
11
use GravityMedia\Metadata\Metadata\MetadataInterface;
12
use GravityMedia\Metadata\Metadata\TagInterface;
13
use GravityMedia\Stream\StreamInterface;
14
15
/**
16
 * ID3v1 tag writer.
17
 *
18
 * @package GravityMedia\Metadata\ID3v1\Writer
19
 */
20
class TagWriter
21
{
22
    /**
23
     * @var MetadataInterface
24
     */
25
    protected $metadata;
26
27
    /**
28
     * @var StreamInterface
29
     */
30
    protected $stream;
31
32
    /**
33
     * Create ID3v1 tag writer object.
34
     *
35
     * @param MetadataInterface $metadata
36
     * @param StreamInterface $stream
37
     */
38
    public function __construct(MetadataInterface $metadata, StreamInterface $stream)
39
    {
40
        $this->metadata = $metadata;
41
        $this->stream = $stream;
42
    }
43
44
    /**
45
     * Pad data.
46
     *
47
     * @param string $data The data to pad
48
     * @param int $length The final length
49
     * @param int $type The type of padding
50
     *
51
     * @return string
52
     */
53
    protected function padData($data, $length, $type)
54
    {
55
        return str_pad(trim(substr($data, 0, $length)), $length, "\x00", $type);
56
    }
57
58
    /**
59
     * Write ID3v1 tag.
60
     *
61
     * @param TagInterface $tag
62
     *
63
     * @return $this
64
     */
65
    public function write(TagInterface $tag)
66
    {
67
        $offset = 0;
68
        if ($this->metadata->exists()) {
69
            $offset = -128;
70
        }
71
72
        $this->stream->seek($offset, SEEK_END);
73
74
        $data = 'TAG';
75
        $data .= $this->padData($tag->getTitle(), 30, STR_PAD_RIGHT);
76
        $data .= $this->padData($tag->getArtist(), 30, STR_PAD_RIGHT);
77
        $data .= $this->padData($tag->getAlbum(), 30, STR_PAD_RIGHT);
78
        $data .= $this->padData($tag->getYear(), 4, STR_PAD_LEFT);
79
80
        if (Version::VERSION_11 === $tag->getVersion()) {
81
            $data .= $this->padData($tag->getComment(), 28, STR_PAD_RIGHT);
82
            $data .= "\x00";
83
            $data .= chr($tag->getTrack());
84
        } else {
85
            $data .= $this->padData($tag->getComment(), 30, STR_PAD_RIGHT);
86
        }
87
88
        $data .= chr($tag->getGenre());
89
90
        $this->stream->write($data);
91
92
        return $this;
93
    }
94
}
95