MediaWiki master
EditConstraintRunner.php
Go to the documentation of this file.
1<?php
8
10use Psr\Log\LoggerInterface;
11use Wikimedia\Assert\Assert;
12
23
24 private LoggerInterface $logger;
25
31 private $constraints = [];
32
38 private $failedConstraint = false;
39
43 public function __construct() {
44 // TODO allow passing an array here as the starting constraints?
45 // TODO consider injecting this?
46 $this->logger = LoggerFactory::getInstance( 'EditConstraintRunner' );
47 }
48
57 public function addConstraint( IEditConstraint $constraint ) {
58 $this->constraints[] = $constraint;
59 }
60
67 public function checkConstraints(): bool {
68 foreach ( $this->constraints as $constraint ) {
69 $result = $constraint->checkConstraint();
70 if ( $result !== IEditConstraint::CONSTRAINT_PASSED ) {
71 // Use `info` instead of `debug` for the one constraint that failed
72 $this->logger->info(
73 'Checked {name}, got result: {result}',
74 [
75 'name' => $this->getConstraintName( $constraint ),
76 'result' => $result
77 ]
78 );
79
80 $this->failedConstraint = $constraint;
81 return false;
82 }
83
84 // Pass, log at `debug` level
85 $this->logger->debug(
86 'Checked {name}, got result: {result}',
87 [
88 'name' => $this->getConstraintName( $constraint ),
89 'result' => $result
90 ]
91 );
92 }
93 return true;
94 }
95
96 private function getConstraintName( IEditConstraint $constraint ): string {
97 // Used for debug logging
98 $fullClassName = explode( '\\', get_class( $constraint ) );
99 $constraintName = end( $fullClassName );
100 if ( $constraint instanceof PageSizeConstraint ) {
101 // TODO "When you need to do this instanceof, it's a code smell"
102 // Convert IEditConstraint to abstract class with a getName method
103 // once the initial migration to edit constraints is complete
104 // PageSizeConstraint is used twice, make sure they can be told apart
105 $constraintName .= ' ' . $constraint->getType();
106 }
107 return $constraintName;
108 }
109
114 Assert::precondition(
115 $this->failedConstraint !== false,
116 'getFailedConstraint called with no failed constraint'
117 );
118 return $this->failedConstraint;
119 }
120
121}
Back end to process the edit constraints.
addConstraint(IEditConstraint $constraint)
Add a constraint to check.
Verify the page isn't larger than the maximum.
Create PSR-3 logger objects.
Interface for all constraints that can prevent edits.