Skip to content

Commit

Permalink
Merge pull request #12 from benlipp/to-array
Browse files Browse the repository at this point in the history
added toArray function for Caption
  • Loading branch information
benlipp authored Apr 2, 2017
2 parents 2d2582a + 5559e67 commit 9c1a11b
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,20 @@ Import the `Parser` class: `use Benlipp\SrtParser\Parser;`
Use it:
````
$parser = new Parser();
$parser->loadFile('/path/to/srtfile.srt');
$captions = $parser->parse();
````
or
````
$parser = new Parser();
$parser->loadString($formatted_caption_input);
$captions = $parser->parse();
````

`parse()` returns an array of captions. Use them like so:

````
Expand All @@ -31,6 +42,25 @@ foreach($captions as $caption){
echo "Text: " . $caption->text;
}
````
A caption can be returned as an array instead of an object, if you prefer. The array is `snake_case` for compatibility with Laravel's attributes.
````
foreach($captions as $caption){
$caption = $caption->toArray();
echo "Start Time: " . $caption['start_time'];
echo "End Time: " . $caption['end_time'];
echo "Text: " . $caption['text'];
}
````
For Laravel usage with a model:
````
$url = "https://youtu.be/dQw4w9WgXcQ";
$video = new Video($url);
foreach ($captions as $caption) {
$data = new VideoMetadata($caption->toArray());
$video->videoMetadata()->save($data);
}
````

You can also chain the `parse()` method:
````
$parser = new Parser();
Expand Down
13 changes: 13 additions & 0 deletions src/SrtParser/Caption.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,17 @@ public function setText($text)

return $this;
}

/**
* Returns an array with snake_case formatted keys for Laravel
* @return array
*/
public function toArray()
{
return [
'start_time' => $this->startTime,
'end_time' => $this->endTime,
'text' => $this->text
];
}
}
21 changes: 21 additions & 0 deletions tests/CaptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,25 @@ public function testFormatting()
$this->assertEquals($text, $caption->text);
}

public function testToArray()
{
$startTime = "00:00:00,000";
$endTime = "00:00:05,000";
$text = "Caption";

$expectedStart = Time::get($startTime);
$expectedEnd = Time::get($endTime);

$caption = new Caption($startTime, $endTime, $text);
$captionArray = $caption->toArray();
$this->assertTrue(is_array($captionArray));

$expectedArray = [
'start_time' => $expectedStart,
'end_time' => $expectedEnd,
'text' => $text
];
$this->assertEquals($captionArray, $expectedArray);
}

}

0 comments on commit 9c1a11b

Please sign in to comment.