1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * Redistributions of files must retain the above copyright notice.
8: *
9: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
10: * @since 3.4.0
11: * @license https://opensource.org/licenses/mit-license.php MIT License
12: */
13: namespace Cake\ORM\Exception;
14:
15: use Cake\Core\Exception\Exception;
16: use Cake\Datasource\EntityInterface;
17: use Cake\Utility\Hash;
18:
19: /**
20: * Used when a strict save or delete fails
21: */
22: class PersistenceFailedException extends Exception
23: {
24: /**
25: * The entity on which the persistence operation failed
26: *
27: * @var \Cake\Datasource\EntityInterface
28: */
29: protected $_entity;
30:
31: /**
32: * {@inheritDoc}
33: */
34: protected $_messageTemplate = 'Entity %s failure.';
35:
36: /**
37: * Constructor.
38: *
39: * @param \Cake\Datasource\EntityInterface $entity The entity on which the persistence operation failed
40: * @param string|array $message Either the string of the error message, or an array of attributes
41: * that are made available in the view, and sprintf()'d into Exception::$_messageTemplate
42: * @param int $code The code of the error, is also the HTTP status code for the error.
43: * @param \Exception|null $previous the previous exception.
44: */
45: public function __construct(EntityInterface $entity, $message, $code = null, $previous = null)
46: {
47: $this->_entity = $entity;
48: if (is_array($message)) {
49: $errors = [];
50: foreach (Hash::flatten($entity->getErrors()) as $field => $error) {
51: $errors[] = $field . ': "' . $error . '"';
52: }
53: if ($errors) {
54: $message[] = implode(', ', $errors);
55: $this->_messageTemplate = 'Entity %s failure. Found the following errors (%s).';
56: }
57: }
58: parent::__construct($message, $code, $previous);
59: }
60:
61: /**
62: * Get the passed in entity
63: *
64: * @return \Cake\Datasource\EntityInterface
65: */
66: public function getEntity()
67: {
68: return $this->_entity;
69: }
70: }
71: