Completed
Push — master ( 532b06...1ac1c9 )
by Peter
08:53
created

TextExtractor   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 16
c 1
b 0
f 0
lcom 1
cbo 4
dl 0
loc 86
ccs 0
cts 53
cp 0
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C extract() 0 64 16
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: peter
5
 * Date: 20.06.18
6
 * Time: 16:15
7
 */
8
9
namespace Maslosoft\Manganel\Helpers;
10
11
12
use function array_merge;
13
use function in_array;
14
use function is_array;
15
use function is_string;
16
use Maslosoft\Addendum\Interfaces\AnnotatedInterface;
17
use Maslosoft\Addendum\Utilities\ClassChecker;
18
use Maslosoft\Mangan\Helpers\CompositionIterator;
19
use Maslosoft\Manganel\Meta\DocumentPropertyMeta;
20
use Maslosoft\Manganel\Meta\ManganelMeta;
21
use MongoId;
22
use function strpos;
23
24
class TextExtractor
25
{
26
	private static $banFields = [
27
		'_class',
28
		'id',
29
		'_id',
30
		'createDate',
31
		'updateDate',
32
		'createUser',
33
		'createUserId',
34
		'updateUser',
35
		'updateUserId',
36
		'wasSaved'
37
	];
38
39
	/**
40
	 * Extract text values from model with $minBoost for field
41
	 * @param AnnotatedInterface $model
42
	 * @param float              $minBoost
43
	 * @return string[]
44
	 */
45
	public static function extract(AnnotatedInterface $model, $minBoost = 1.0)
46
	{
47
		$texts = [];
48
49
		foreach(ManganelMeta::create($model)->fields() as $metaProperty)
50
		{
51
			/* @var $metaProperty DocumentPropertyMeta */
52
			$name = $metaProperty->name;
53
54
			// Skip system fields
55
			if(in_array($name, self::$banFields))
56
			{
57
				continue;
58
			}
59
60
			if($metaProperty->searchBoost < $minBoost)
61
			{
62
				continue;
63
			}
64
			if(!$metaProperty->searchable)
65
			{
66
				continue;
67
			}
68
69
			$values = $model->$name;
70
			if(!is_array($values) && !is_string($values))
71
			{
72
				continue;
73
			}
74
			if(!is_array($values) && is_string($values))
75
			{
76
				$values = [$values];
77
			}
78
			foreach($values as $value)
79
			{
80
				if (is_string($value))
81
				{
82
					// Skip class names
83
					if(strpos($value, '\\') !== false && ClassChecker::exists($value))
84
					{
85
						continue;
86
					}
87
					if(empty($value))
88
					{
89
						continue;
90
					}
91
92
					// Ignore ID's
93
					if(MongoId::isValid($value))
94
					{
95
						continue;
96
					}
97
					$texts[] = $value;
98
				}
99
			}
100
		}
101
102
		foreach(new CompositionIterator($model) as $subModel)
103
		{
104
			$texts = array_merge($texts, self::extract($subModel, $minBoost));
105
		}
106
107
		return $texts;
108
	}
109
}