Completed
Push — add/legacy-files ( 4cc789...bef25d )
by
unknown
157:43 queued 148:20
created

PersistentList   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 10
c 0
b 0
f 0
wmc 10
lcom 1
cbo 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A get() 0 3 1
A add() 0 6 2
A count() 0 3 1
A output() 0 3 1
A save() 0 16 4
1
<?php
2
3
namespace Automattic\Jetpack\Analyzer;
4
5
use Automattic\Jetpack\Analyzer\PersistentList\Item as PersistentListItem;
6
7
/**
8
 * Handy class for persisting a list of objects that support the to_csv_array method
9
 */
10
class PersistentList {
11
	private $items;
12
13
	function __construct() {
14
		$this->items = array();
15
	}
16
17
	public function get() {
18
		return $this->items;
19
	}
20
21
	public function add( $item ) {
22
		if ( ! is_subclass_of( $item, 'Automattic\Jetpack\Analyzer\PersistentList\Item' ) ) {
23
			throw new \Exception( 'item must extend Automattic\Jetpack\Analyzer\PersistentList\Item' );
24
		}
25
		$this->items[] = $item;
26
	}
27
28
	public function count() {
29
		return count( $this->items );
30
	}
31
32
	public function output() {
33
		echo $this->save( 'php://memory' );
34
	}
35
36
	/**
37
	 * Saves the items to a file and returns the file contents
38
	 */
39
	public function save( $file_path, $allow_empty = true ) {
40
41
		// Not saving empty files if empty files are not allowed to be saved
42
		if ( ! $allow_empty && empty( $this->items ) ) {
43
			return '';
44
		}
45
46
		$handle = fopen( $file_path, 'w+' );
47
		foreach ( $this->items as $item ) {
48
			fputcsv( $handle, $item->to_csv_array() );
49
		}
50
		rewind( $handle );
51
		$contents = stream_get_contents( $handle );
52
		fclose( $handle );
53
		return $contents;
54
	}
55
}
56