MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / phpCodeOnly

Function phpCodeOnly

src/extraction/languages/php.ts:226–277  ·  view source on GitHub ↗

* A PHP source's code, with inline HTML, comments, string contents and heredoc * bodies turned to spaces (newlines kept), offsets unchanged: what is left * outside `<?php … ?>`, quotes and comments is code.

(source: string)

Source from the content-addressed store, hash-verified

224 * outside `<?php … ?>`, quotes and comments is code.
225 */
226function phpCodeOnly(source: string): string {
227 const out = source.split('');
228 const blank = (from: number, to: number): void => {
229 for (let k = from; k < to && k < out.length; k++) if (out[k] !== '\n' && out[k] !== '\r') out[k] = ' ';
230 };
231 const n = source.length;
232 let i = 0;
233 let inPhp = false;
234 while (i < n) {
235 if (!inPhp) {
236 const open = source.indexOf('<?', i);
237 const end = open < 0 ? n : open;
238 blank(i, end);
239 if (open < 0) break;
240 inPhp = true;
241 i = open + 2;
242 continue;
243 }
244 const c = source[i]!;
245 if (c === '?' && source[i + 1] === '>') {
246 inPhp = false;
247 i += 2;
248 } else if ((c === '/' && source[i + 1] === '/') || (c === '#' && source[i + 1] !== '[')) {
249 let j = i;
250 while (j < n && source[j] !== '\n' && !(source[j] === '?' && source[j + 1] === '>')) j++;
251 blank(i, j);
252 i = j;
253 } else if (c === '/' && source[i + 1] === '*') {
254 const close = source.indexOf('*/', i + 2);
255 const j = close < 0 ? n : close + 2;
256 blank(i, j);
257 i = j;
258 } else if (c === '\'' || c === '"' || c === '`') {
259 let j = i + 1;
260 while (j < n && source[j] !== c) j += source[j] === '\\' ? 2 : 1;
261 blank(i + 1, Math.min(j, n));
262 i = j + 1;
263 } else if (c === '<' && source.startsWith('<<<', i)) {
264 const head = /^<<<[ \t]*(["']?)([A-Za-z_]\w*)\1\r?\n/.exec(source.slice(i, i + 200));
265 if (!head) { i += 3; continue; }
266 const closing = new RegExp(`^[ \\t]*${head[2]}\\b`, 'm');
267 const bodyStart = i + head[0].length;
268 const m = closing.exec(source.slice(bodyStart));
269 const j = m ? bodyStart + m.index + m[0].length : n;
270 blank(i, j);
271 i = j;
272 } else {
273 i++;
274 }
275 }
276 return out.join('');
277}
278
279/**
280 * PHP before 8.0 also wrote a string offset with braces, `$code{0}` or

Callers 1

Calls 3

blankFunction · 0.70
execMethod · 0.65
joinMethod · 0.45

Tested by

no test coverage detected