Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 47 lines (42 sloc) 1.105 kB
d358052 adding JSON database loader
XirisR authored
1 <?php
2 /**
3 * @package MongoUnit
4 * @author Jonathan Moss <jonathan.moss@tangentlabs.co.uk>
5 * @copyright 2010 Tangent Labs
6 * @version SVN: $Id$
7 */
380d4cf converted the whole project to namespaced PHP
Jonathan Moss authored
8 namespace mongoUnit;
d358052 adding JSON database loader
XirisR authored
9 /**
10 * Loads data into a collection
11 *
12 * @package MongoUnit
13 */
380d4cf converted the whole project to namespaced PHP
Jonathan Moss authored
14 class JsonLoader
d358052 adding JSON database loader
XirisR authored
15 {
16
17 private $collection;
18
380d4cf converted the whole project to namespaced PHP
Jonathan Moss authored
19 public function __construct(\MongoCollection $collection)
d358052 adding JSON database loader
XirisR authored
20 {
21 $this->collection = $collection;
22 }
23
24 public function loadFromJsonFile($filePath)
25 {
380d4cf converted the whole project to namespaced PHP
Jonathan Moss authored
26 if (!\file_exists($filePath)) {
d358052 adding JSON database loader
XirisR authored
27 throw new InvalidArgumentException("Could not locate $filePath");
28 }
380d4cf converted the whole project to namespaced PHP
Jonathan Moss authored
29 $json = \file_get_contents($filePath);
d358052 adding JSON database loader
XirisR authored
30 return $this->loadJsonFromString($json);
31 }
32
33 public function loadJsonFromString($json)
34 {
35 if (!$this->isValidJson($json)) {
380d4cf converted the whole project to namespaced PHP
Jonathan Moss authored
36 throw new \InvalidArgumentException("Invalid Json");
d358052 adding JSON database loader
XirisR authored
37 }
380d4cf converted the whole project to namespaced PHP
Jonathan Moss authored
38 $data = \json_decode($json, true);
d358052 adding JSON database loader
XirisR authored
39 $this->collection->drop();
40 return $this->collection->batchInsert($data);
41 }
42
43 private function isValidJson($json)
44 {
380d4cf converted the whole project to namespaced PHP
Jonathan Moss authored
45 return (\json_decode($json) !== null) ? true : false;
d358052 adding JSON database loader
XirisR authored
46 }
47 }
Something went wrong with that request. Please try again.