Unique.php
1 <?php
2 /**
3  * wCMF - wemove Content Management Framework
4  * Copyright (C) 2005-2020 wemove digital solutions GmbH
5  *
6  * Licensed under the terms of the MIT License.
7  *
8  * See the LICENSE file distributed with this work for
9  * additional information.
10  */
11 namespace wcmf\lib\validation\impl;
12 
17 
18 /**
19  * Unique checks if the value is unique regarding the given entity attribute.
20  *
21  * Configuration examples:
22  * @code
23  * // ensure Keyword.name is unique
24  * unique:{"type":"Keyword","value":"name"}
25  *
26  * // or without options when used in entity context
27  * unique
28  * @endcode
29  *
30  * @author ingo herwig <ingo@wemove.com>
31  */
32 class Unique implements ValidateType {
33 
34  /**
35  * @see ValidateType::validate
36  */
37  public function validate($value, $options=null, $context=null) {
38  if (strlen($value) == 0) {
39  return true;
40  }
41 
42  // get type and value from context, if not set
43  if (!isset($options['type']) && isset($context['entity'])) {
44  $options['type'] = $context['entity']->getType();
45  }
46  if (!isset($options['value']) && isset($context['value'])) {
47  $options['value'] = $context['value'];
48  }
49 
50  // validate options
51  if (!isset($options['type'])) {
52  throw new ConfigurationException("No 'type' given in unique options: ".json_encode($options));
53  }
54  if (!isset($options['value'])) {
55  throw new ConfigurationException("No 'value' given in unique options: ".json_encode($options));
56  }
57 
58  $type = $options['type'];
59  $attribute = $options['value'];
60  $query = new ObjectQuery($type);
61  $itemTpl = $query->getObjectTemplate($type);
62  // force set to skip validation
63  $itemTpl->setValue($attribute, Criteria::asValue("=", $value), true);
64  $itemOidList = $query->execute(false);
65  // exclude context entity
66  if (isset($context['entity'])) {
67  $oid = $context['entity']->getOID();
68  $itemOidList = array_filter($itemOidList, function($itemOid) use ($oid) {
69  return $itemOid != $oid;
70  });
71  }
72 
73  // value already exists
74  if (sizeof($itemOidList) > 0) {
75  return false;
76  }
77  return true;
78  }
79 }
80 ?>
ValidateType defines the interface for all validator classes.
static asValue($operator, $value)
Factory method for constructing a Criteria that may be used as value on a PersistentObject's attribut...
Definition: Criteria.php:58
Criteria defines a condition on a PersistentObject's attribute used to select specific instances.
Definition: Criteria.php:21
ConfigurationException signals an exception in the configuration.
Unique checks if the value is unique regarding the given entity attribute.
Definition: Unique.php:32
validate($value, $options=null, $context=null)
Definition: Unique.php:37
ObjectQuery implements a template based object query.