Validates plugin settings before persisted in DB.

@param \Cake\Event\Event $event The event that was triggered
@param array $data Information to be validated
@param \ArrayObject $options Options given to pathEntity()
@return void
499582
public function settingsValidate(Event $event, array $data, ArrayObject $options)
    {
        if (!empty($options['entity']) && $options['entity']->has('name')) {
            $validator = new Validator();
            $this->trigger("Plugin.{$options['entity']->name}.settingsValidate", $data, $validator);
            $errors = $validator->errors($data, $options['entity']->isNew());

            if (!empty($errors)) {
                foreach ($errors as $k => $v) {
                    $options['entity']->errors("settings:{$k}", $v);
                }
            }
        }
    }
865322
public function beforeSave($event, $entity, $options)
    {
        if (!empty($entity->new_password)) {
            $entity->password = $entity->new_password; // set for password-changes
        }
    }
130318
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options) {
		$field = $this->getConfig('field');
		$property = $this->getConfig('tagsAssoc.propertyName');
		$options['accessibleFields'][$property] = true;

		if (isset($data[$field])) {
			$data[$property] = $this->normalizeTags($data[$field]);
		} elseif ($field !== $property) {
			if (isset($data[$property]) && !is_array($data[$property])) {
				throw new RuntimeException('Your `' . $property . '` property is malformed (expected array instead of string). You configured to save list of tags in `' . $field . '` field.');
			}
		}

		if (isset($data[$field]) && empty($data[$field])) {
			unset($data[$field]);
		}
	}
1079875
public function validate($data, $mode, array $options = [])
    {
        $errors = [];

        // implements something cleaner later
        if (ValidatorProvider::UPDATE === $mode && !isset($data['id'])) {
            return $errors;
        }

        // validates the resource type exists
        if ($data['meta'] && $data['meta']['type']) {
            $resourceType = $this->om
                ->getRepository('ClarolineCoreBundle:Resource\ResourceType')
                ->findOneBy(['name' => $data['meta']['type']]);

            if (!$resourceType) {
                $errors[] = [
                    'path' => 'meta/type',
                    'message' => sprintf('The type %s does not exist.', $data['meta']['type']),
                ];
            }
        }

        return $errors;
    }
1067762
public function beforeSave($event, $entity, $options)
    {
        $entity->set('cakeadmin', true);

        $newPassword = $entity->get('new_password');

        if (!empty($newPassword)) {
            $entity->set('password', $entity->new_password); // set for password-changes
        }
    }
673552
public function onControllerSetup(Event $event)
    {
        /** @var AppController $controller */
        $controller = $event->getSubject();
        $isAdmin    = ($controller->request->getParam('prefix') === 'admin');

        $plugins = Plugin::loaded();
        foreach ($plugins as $plugin) {
            $path     = Plugin::path($plugin);
            $menuFile = ($isAdmin) ? 'admin_menu' : 'menu';
            $navConf  = $path . 'config/' . $menuFile . '.php';

            if (FS::isFile($navConf)) {
                /** @noinspection PhpIncludeInspection */
                require_once $navConf;
            }
        }
    }
721411
public function getPluginCalendars(Event $event, array $options = []): void
    {
        $content = $result = [];

        /** @var \Qobo\Calendar\Model\Table\CalendarsTable $table */
        $table = TableRegistry::get('Qobo/Calendar.Calendars');

        if (!empty($event->result)) {
            $result = $event->result;
        }

        // locally created calendars don't have source_id (external link).
        $options = array_merge($options, [
            'conditions' => [
                'source LIKE' => 'Plugin__%',
            ]
        ]);

        $calendars = $table->getCalendars($options);

        if (empty($calendars)) {
            return;
        }

        foreach ($calendars as $k => $calendar) {
            unset($calendar->calendar_events);

            $encoded = (string)json_encode($calendar);
            if (json_last_error() !== JSON_ERROR_NONE) {
                throw new \RuntimeException(json_last_error_msg());
            }

            $content[$k]['calendar'] = json_decode($encoded, true);
        }

        if (!empty($content)) {
            $result = array_merge($result, $content);
        }

        $event->result = $result;
    }
683516
public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options) : void
    {
        EventManager::instance()->dispatch(new Event(
            (string)EventName::MODEL_AFTER_SAVE(),
            $this,
            ['entity' => $entity, 'options' => ['current_user' => User::getCurrentUser()]]
        ));
    }
482887
public function validation($data, $files) {
        global $DB;

        $errors = parent::validation($data, $files);
        $eventtype = isset($data['eventtype']) ? $data['eventtype'] : null;
        $coursekey = ($eventtype == 'group') ? 'groupcourseid' : 'courseid';
        $courseid = (!empty($data[$coursekey])) ? $data[$coursekey] : null;
        $eventtypes = calendar_get_allowed_event_types($courseid);

        if (empty($eventtype) || !isset($eventtypes[$eventtype]) || $eventtypes[$eventtype] == false) {
            $errors['eventtype'] = get_string('invalideventtype', 'calendar');
        }

        if ($courseid && $courseid > 0) {
            if ($course = $DB->get_record('course', ['id' => $courseid])) {
                if ($data['timestart'] < $course->startdate) {
                    $errors['timestart'] = get_string('errorbeforecoursestart', 'calendar');
                }
            } else {
                $errors[$coursekey] = get_string('invalidcourse', 'error');
            }
        }

        if ($eventtype == 'course' && empty($courseid)) {
            $errors['courseid'] = get_string('selectacourse');
        }

        if ($eventtype == 'group' && (!empty($courseid) && empty($data['groupid']))) {
            $errors['groupcourseid'] = get_string('nogroups', 'core_group');
        }

        if ($eventtype == 'group' && empty($courseid)) {
            $errors['groupcourseid'] = get_string('selectacourse');
        }

        if ($data['duration'] == 1 && $data['timestart'] > $data['timedurationuntil']) {
            $errors['durationgroup'] = get_string('invalidtimedurationuntil', 'calendar');
        } else if ($data['duration'] == 2 && (trim($data['timedurationminutes']) == '' || $data['timedurationminutes'] < 1)) {
            $errors['durationgroup'] = get_string('invalidtimedurationminutes', 'calendar');
        }

        return $errors;
    }
765249
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)
    {
        parent::beforeSave($event, $entity, $options);

        list($width, $height) = getimagesize($entity->path);
        $entity->size = compact('width', 'height');
    }
1259088
public function beforeSave(Event $event, Content $entity, \ArrayObject $options)
    {
        $entity->language_id = Wasabi::contentLanguage()->id;
        $entity->created_by_user_id = Wasabi::user()->id;
        $entity->modified_by_user_id = Wasabi::user()->id;
    }
933762
public function addValidation($property, $validation, $options = array())
    {
        $validations = $this->getValidations($property);
        $validations[$validation] = $options;

        return $this;
    }
690432
public function afterDelete(Event $event, EntityInterface $entity, ArrayObject $options) {
		$field = $this->getConfig('field');

		$value = $entity->get($field);
		if (!$value) {
			return;
		}

		$conditions = $this->buildConditions($entity);

		$order = $this->getConfig('findOrder');
		if ($order === null) {
			$order = [];
			if ($this->_table->getSchema()->getColumn('modified')) {
				$order['modified'] = 'DESC';
			}
		}
		$entity = $this->_table->find()->where($conditions)->order($order)->first();
		if (!$entity) {
			// This should be caught with a validation rule if at least one "primary" must exist
			return;
		}

		$entity->set($field, true);
		$this->_table->saveOrFail($entity);
	}
1239528
public function valid($options = array())
    {
        $options && $this->setOption($options);

        // Initialize the validation result to be true
        $this->result = true;

        $this->beforeValidate && call_user_func($this->beforeValidate, $this, $this->wei);

        foreach ($this->rules as $field => $rules) {
            $data = $this->getFieldData($field);

            /**
             * Process simple rule
             * FROM
             * 'username' => 'required'
             * TO
             * 'username' => array(
             *     'required' => true
             * )
             */
            if (is_string($rules)) {
                $rules = array($rules => true);
            } elseif ($rules instanceof BaseValidator) {
                $rules = array($rules);
            } elseif (!is_array($rules)) {
                throw new \InvalidArgumentException(sprintf(
                    'Expected argument of type array, string or instance of Wei\Validator\BaseValidator, "%s" given',
                    is_object($rules) ? get_class($rules) : gettype($rules)
                ));
            }

            // Make sure the "required" rule at first
            if (!isset($rules['required'])) {
                $isRequired = true;
            } else {
                $isRequired = (bool) $rules['required'];
                unset($rules['required']);
            }
            $rules = array('required' => $isRequired) + $rules;

            // Start validation
            foreach ($rules as $rule => $params) {
                // Prepare property options for validator
                $props = $this->prepareProps($field, $rule);

                // The current rule validation result
                /* @var $validator Validator\BaseValidator */
                $validator = null;
                $result = $this->validateOne($rule, $data, $params, $validator, $props);

                if (is_object($params)) {
                    $rule = get_class($params);
                }

                // Record the rule validators
                $this->ruleValidators[$field][$rule] = $validator;

                // If any rule is invalid, the result would always be false in the whole validation flow
                if (false === $result) {
                    $this->result = false;
                }

                // Record the valid/invalid rule
                $method = $result ? 'addValidRule' : 'addInvalidRule';
                $this->$method($field, $rule);

                // Trigger the ruleValid/ruleInvalid callback
                $callback = $result ? 'ruleValid' : 'ruleInvalid';
                if ($this->$callback && false === call_user_func($this->$callback, $rule, $field, $this, $this->wei)) {
                    return $this->result;
                }

                if ($result) {
                    // The field data is empty and optional, skip the remaining validation rules
                    /** @var $validator Validator\Required */
                    if ('required' === $rule && $validator->isInvalid($data)) {
                        break;
                    }
                } else {
                    // Break the validation flow when any field's rule is invalid
                    if ('required' === $rule || $this->breakRule || $this->skip) {
                        break;
                    }
                }
            }

            // Trigger the fieldValid/fieldInvalid callback
            $callback = $this->isFieldValid($field) ? 'fieldValid' : 'fieldInvalid';
            if ($this->$callback && false === call_user_func($this->$callback, $field, $this, $this->wei)) {
                return $this->result;
            }

            if (!$this->result && $this->skip) {
                continue;
            }

            // Break the validation flow when any field is invalid
            if (!$this->result && ($this->breakRule || $this->breakField)) {
                break;
            }
        }

        // Trigger the success/failure callback
        $callback = $this->result ? 'success' : 'failure';
        $this->$callback && call_user_func($this->$callback, $this, $this->wei);

        return $this->result;
    }
859835
public function beforeSave(Event $event, Entity $entity, ArrayObject $options)
    {
        $onUpdate = $this->getConfig('onUpdate');
        if (!$entity->isNew() && !$onUpdate) {
            return;
        }

        $onDirty = $this->getConfig('onDirty');
        $field = $this->getConfig('field');
        if (!$onDirty
            && $entity->isDirty($field)
            && (!$entity->isNew() || (!empty($entity->{$field})))
        ) {
            return;
        }

        $separator = $this->getConfig('separator');
        if ($entity->isDirty($field) && !empty($entity->{$field})) {
            $slug = $this->slug($entity, $entity->{$field}, $separator);
            $entity->set($field, $slug);

            return;
        }

        $parts = $this->_getPartsFromEntity($entity);
        if (empty($parts)) {
            return;
        }

        $slug = $this->slug($entity, implode($separator, $parts), $separator);
        $entity->set($field, $slug);
    }
1342384
public function afterSave(Event $event, Setting $entity, ArrayObject $options)
    {
        Cache::delete('settings', 'wasabi/core/longterm');
        $this->eventManager()->dispatch(new Event('Wasabi.Settings.changed'));
    }
850149
public function validateCartCouponRules(CartCouponOnCheckEvent $event)
    {
        $this
            ->cartCouponRuleValidator
            ->validateCartCouponRules(
                $event->getCart(),
                $event->getCoupon()
            );
    }