gmail-filter-builder/src/Service/Builder.php

91 lines
2.1 KiB
PHP
Raw Normal View History

2017-11-04 00:32:39 +00:00
<?php
namespace Opdavies\GmailFilterBuilder;
class Builder
{
2017-12-30 10:56:07 +00:00
/**
* @var array
*/
2017-11-04 00:32:39 +00:00
private $filters = [];
2017-12-30 10:56:07 +00:00
public function __construct(array $filters)
{
2017-11-04 00:32:39 +00:00
$this->filters = $filters;
}
2017-12-30 13:42:23 +00:00
public function __toString()
{
return $this->build();
}
2017-12-30 10:56:07 +00:00
/**
* Build XML for a set of filters.
*
* @return string
*/
2017-12-30 13:42:23 +00:00
private function build()
2017-11-04 00:32:39 +00:00
{
2018-01-05 00:55:22 +00:00
$prefix = "<?xml version='1.0' encoding='UTF-8'?>" . PHP_EOL . "<feed xmlns='http://www.w3.org/2005/Atom' xmlns:apps='http://schemas.google.com/apps/2006'>";
2017-12-30 10:28:19 +00:00
$suffix = '</feed>';
$xml = collect($this->filters)->map(function ($items) {
return $this->buildEntry($items);
2018-01-04 23:22:23 +00:00
})->implode(PHP_EOL);
2017-12-30 10:28:19 +00:00
2018-01-04 23:22:23 +00:00
return collect([$prefix, $xml, $suffix])->implode(PHP_EOL);
2017-12-30 10:28:19 +00:00
}
/**
2017-12-30 13:42:23 +00:00
* Build XML for an filter.
2017-12-30 10:56:07 +00:00
*
2017-12-30 13:42:23 +00:00
* @param Filter $filter
2017-12-30 10:28:19 +00:00
*
* @return string
*/
2017-12-30 13:42:23 +00:00
private function buildEntry(Filter $filter)
2017-12-30 10:28:19 +00:00
{
2017-12-30 13:42:23 +00:00
$entry = collect($filter->getProperties())->map(function ($value, $key) {
2017-12-30 10:28:19 +00:00
return $this->buildProperty($value, $key);
2018-01-05 00:55:22 +00:00
})->implode(PHP_EOL);
2017-12-30 10:28:19 +00:00
2018-01-05 00:55:22 +00:00
return collect(['<entry>', $entry, '</entry>'])->implode(PHP_EOL);
2017-12-30 10:28:19 +00:00
}
/**
* Build XML for a property.
*
* @param string $value
* @param string $key
*
* @return string
*/
private function buildProperty($value, $key)
{
2017-12-30 18:21:15 +00:00
if (collect(['from', 'to'])->contains($key)) {
$value = $this->implode($value);
2017-12-30 10:28:19 +00:00
}
2017-12-30 18:20:24 +00:00
return vsprintf("<apps:property name='%s' value='%s'/>", [
$key,
2018-01-05 00:31:59 +00:00
htmlentities($this->implode($value)),
2017-12-30 18:20:24 +00:00
]);
2017-11-04 00:32:39 +00:00
}
/**
* Implode values with the appropriate prefix, suffix and separator.
*/
private function implode($value, $separator = '|')
{
2018-01-05 00:31:59 +00:00
if (is_string($value)) {
return $value;
}
if (is_array($value) && count($value) === 1) {
return reset($value);
}
return sprintf('(%s)', collect($value)->implode($separator));
}
2017-11-04 00:32:39 +00:00
}