1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
<?php
/**
* BEdita, API-first content management framework
* Copyright 2017 ChannelWeb Srl, Chialab Srl
*
* This file is part of BEdita: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
*/
namespace BEdita\Core\Model\Entity;
use Cake\ORM\Entity;
/**
* DateRange Entity
*
* @property int $id
* @property int $object_id
* @property \DateTimeInterface $start_date
* @property \DateTimeInterface|null $end_date
* @property array $params
*
* @property \BEdita\Core\Model\Entity\ObjectEntity $object
*/
class DateRange extends Entity
{
/**
* @inheritDoc
*/
protected $_accessible = [
'*' => true,
'id' => false,
];
/**
* @inheritDoc
*/
protected $_hidden = [
'id',
'object_id',
];
/**
* Check if this Date Range is before the passed Date Range.
*
* A Date Range is "before" another Date Range if its `end_date` is lower than,
* or equal, to the other Date Range's `start_date`. If `end_date` is `null`,
* for this purpose it assumes the same value as `start_date`.
*
* **Warning**: this method **does not** take `params` into account.
*
* @param \BEdita\Core\Model\Entity\DateRange $dateRange Date Range being compared.
* @return bool
*/
public function isBefore(DateRange $dateRange)
{
static::checkWellFormed($this, $dateRange);
return $this->start_date < $dateRange->start_date && ($this->end_date === null || $this->end_date <= $dateRange->start_date);
}
/**
* Check if this Date Range is after the passed Date Range.
*
* A Date Range is "after" another Date Range if its `start_date` is greater than,
* or equal, to the other Date Range's `end_date`. If `end_date` is `null`,
* for this purpose it assumes the same value as `start_date`.
*
* **Warning**: this method **does not** take `params` into account.
*
* @param \BEdita\Core\Model\Entity\DateRange $dateRange Date Range being compared.
* @return bool
*/
public function isAfter(DateRange $dateRange)
{
static::checkWellFormed($this, $dateRange);
return $this->start_date > $dateRange->start_date && ($dateRange->end_date === null || $this->start_date >= $dateRange->end_date);
}
/**
* Normalize an array of Date Ranges by sorting and joining overlapping Date Ranges.
*
* Normalization sorts Date Ranges in a set by `start_date` in ascending order.
* Also, if two or more Date Ranges do overlap, or are adjacent
* (i.e. `$d1->end_date === $d2->start_date`), they are merged in one Date Range.
* Duplicate Date Ranges are removed.
*
* **Warning**: this method **does not** take `params` into account.
*
* @param \BEdita\Core\Model\Entity\DateRange[] $dateRanges Set of Date Ranges.
* @return \BEdita\Core\Model\Entity\DateRange[]
*/
public static function normalize(array $dateRanges)
{
if (empty($dateRanges)) {
return [];
}
static::checkWellFormed(...$dateRanges);
// Sort items.
usort($dateRanges, function (DateRange $dateRange1, DateRange $dateRange2) {
if ($dateRange1->isBefore($dateRange2)) {
return -1;
}
if ($dateRange1->isAfter($dateRange2)) {
return 1;
}
return 0;
});
// Merge items.
$result = [];
$last = clone array_shift($dateRanges);
while (($current = array_shift($dateRanges)) !== null) {
if ($last->isBefore($current) && $last->end_date < $current->start_date) {
$result[] = $last;
$last = clone $current;
continue;
}
$last->start_date = min($last->start_date, $current->start_date);
if ($last->end_date === null || ($current->end_date !== null && $last->end_date < $current->end_date)) {
$last->end_date = $current->end_date;
}
}
$result[] = $last;
return $result;
}
/**
* Compute union of multiple sets of Date Ranges.
*
* This method computes union of multiple sets of Date Ranges.
* The result is returned in normalized form.
*
* **Warning**: this method **does not** take `params` into account.
*
* @param \BEdita\Core\Model\Entity\DateRange[][] ...$dateRanges Set of Date Ranges.
* @return \BEdita\Core\Model\Entity\DateRange[]
*/
public static function union(...$dateRanges)
{
$dateRanges = array_merge(...$dateRanges);
return static::normalize($dateRanges);
}
/**
* Compute difference between two sets of Date Ranges.
*
* When computing complement of `$array1` with respect to `$array2`:
* - Date Ranges with `end_date = null` are treated as unit sets, all
* other Date Ranges are considered intervals.
* - complement of an interval with respect to another interval results
* in the difference of the two sets.
* - complement of an interval with respect to a unit set results in
* the interval unmodified.
* - complement of a unit sets with respect to an interval results in
* either the unit set unmodified if they are not overlapping, or in
* the empty set otherwise.
* - complement of a unit sets with respect to another unit set results
* in either the unit set unmodified if they are not the same, or in
* the empty set otherwise.
*
* **Warning**: this method does **not** take `params` into account.
*
* ### Example
*
* ```php
* $array1 = [new DateRange(['start_date' => new FrozenTime('2017-01-01 00:00:00'), 'end_date' => new FrozenTime('2017-01-31 12:59:59')])];
* $array2 = [new DateRange(['start_date' => new FrozenTime('2017-01-10 00:00:00'), 'end_date' => new FrozenTime('2017-01-19 12:59:59')])];
*
* $diff = DateRange::diff($array1, $array2);
*
* // $diff will now be equivalent to:
* $diff = [
* new DateRange(['start_date' => new FrozenTime('2017-01-10 00:00:00'), 'end_date' => new FrozenTime('2017-01-10 00:00:00')]),
* new DateRange(['start_date' => new FrozenTime('2017-01-19 12:59:59'), 'end_date' => new FrozenTime('2017-01-19 12:59:59')]),
* ];
* ```
*
* @param \BEdita\Core\Model\Entity\DateRange[] $array1 First set of Date Ranges.
* @param \BEdita\Core\Model\Entity\DateRange[] $array2 Second set of Date Ranges.
* @return \BEdita\Core\Model\Entity\DateRange[]
*/
public static function diff(array $array1, array $array2)
{
// Ensure arrays are normalized.
$array1 = static::normalize($array1);
$array2 = static::normalize($array2);
$result = [];
$dateRange = null;
foreach ($array1 as $dateRange1) {
if ($dateRange !== null) {
$result[] = $dateRange;
}
$dateRange = clone $dateRange1;
while (($dateRange2 = current($array2)) !== false) {
if (
$dateRange->end_date === null
&& $dateRange2->end_date === null
&& $dateRange->start_date->getTimestamp() === $dateRange2->start_date->getTimestamp()
) {
// Unit sets match. Discard range.
$dateRange = null;
next($array2);
break;
}
if ($dateRange2->end_date === null || $dateRange2->isBefore($dateRange)) {
// Does not affect intersection.
next($array2);
continue;
}
if ($dateRange2->isAfter($dateRange)) {
// A step too far.
break;
}
if ($dateRange->start_date < $dateRange2->start_date) {
// Split the range.
$temp = clone $dateRange;
$temp->end_date = $dateRange2->start_date;
$result[] = $temp;
$dateRange->start_date = $dateRange2->start_date;
}
if ($dateRange->end_date < $dateRange2->end_date) {
// Discard range.
$dateRange = null;
break;
}
$dateRange->start_date = $dateRange2->end_date;
next($array2);
}
}
if ($dateRange !== null) {
$result[] = $dateRange;
}
return $result;
}
/**
* Check that all the Date Ranges passed as arguments are actually well formed.
*
* A "well formed" Date Range is an instance of class {@see \BEdita\Core\Model\Entity\DateRange}
* whose field `start_date` is an instance of {@see Cake\I18n\Time} and field `end_date` is
* either `null` or an instance of {@see Cake\I18n\Time}.
*
* @param array ...$dateRanges Date Ranges to check.
* @return void
* @throws \LogicException Throws an exception if a malformed Date Range is encountered.
*/
public static function checkWellFormed(...$dateRanges)
{
$getType = function ($var) {
if (!is_object($var)) {
return gettype($var);
}
return get_class($var);
};
foreach ($dateRanges as $dateRange) {
if (!($dateRange instanceof self)) {
throw new \LogicException(
__d('bedita', 'Invalid Date Range entity class: expected "{0}", got "{1}"', static::class, $getType($dateRange))
);
}
if (!($dateRange->start_date instanceof \DateTimeInterface)) {
throw new \LogicException(
__d('bedita', 'Invalid "{0}": expected "{1}", got "{2}"', 'start_date', \DateTimeInterface::class, $getType($dateRange->start_date))
);
}
if (!($dateRange->end_date instanceof \DateTimeInterface) && $dateRange->end_date !== null) {
throw new \LogicException(
__d('bedita', 'Invalid "{0}": expected "{1}", got "{2}"', 'end_date', \DateTimeInterface::class, $getType($dateRange->end_date))
);
}
}
}
}