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: /**
26: * The entity on which the persistence operation failed
27: *
28: * @var \Cake\Datasource\EntityInterface
29: */
30: protected $_entity;
31:
32: /**
33: * {@inheritDoc}
34: */
35: protected $_messageTemplate = 'Entity %s failure.';
36:
37: /**
38: * Constructor.
39: *
40: * @param \Cake\Datasource\EntityInterface $entity The entity on which the persistence operation failed
41: * @param string|array $message Either the string of the error message, or an array of attributes
42: * that are made available in the view, and sprintf()'d into Exception::$_messageTemplate
43: * @param int $code The code of the error, is also the HTTP status code for the error.
44: * @param \Exception|null $previous the previous exception.
45: */
46: public function __construct(EntityInterface $entity, $message, $code = null, $previous = null)
47: {
48: $this->_entity = $entity;
49: if (is_array($message)) {
50: $errors = [];
51: foreach (Hash::flatten($entity->getErrors()) as $field => $error) {
52: $errors[] = $field . ': "' . $error . '"';
53: }
54: if ($errors) {
55: $message[] = implode(', ', $errors);
56: $this->_messageTemplate = 'Entity %s failure. Found the following errors (%s).';
57: }
58: }
59: parent::__construct($message, $code, $previous);
60: }
61:
62: /**
63: * Get the passed in entity
64: *
65: * @return \Cake\Datasource\EntityInterface
66: */
67: public function getEntity()
68: {
69: return $this->_entity;
70: }
71: }
72: