What happens if someone publishes a paper on your current PhD thesis topic
A lot of it depends on how far along you are, your institution, your career goals, and to some extent whether its your fault or not. That is, you DEFINITELY need to search the literature to see if your topic was already studied. But sometimes, someone might just have the same idea because they are thinking about the same issues and reading the same existing literature as you are.

If someone scoops you, it's likely a lot of your work won't be publishable anymore. In some fields it might be possible to publish as a replication (with low impact) or it may be that if you look carefully there is some areas of non-overlap that you can run with. The issue of publication will matter a lot more if you want a career in academia: you need a strong publication record to move on to the next phase of your career. In that circumstance, it might actually be better to delay your PhD just to get some publications, unless you expect you can get a good post doc regardless.

If you are early in your work, even halfway, it may be possible to switch topics. It's also possible all you need is a minor shift. I got scooped. Twice. Both times it hurt, but both times I also realized that there wasn't anywhere near 100% overlap, and my work was still publishable, it just took some extra time to rework things, reemphasize novelty, etc.

Overall, though, your PhD should be awarded for the work you do, not necessarily whether the work pans out. Your institution shouldn't prevent you from getting a PhD if you have been scooped. Negotiating all these issues should be the role of your thesis committee. The thesis committee should be comprised of at least some relatively unbiased professors who can judge whether or not your work is acceptable. The point of the PhD should be to train to be a researcher. Sometimes being scooped is part of the learning experience.

(note: I am answering this mostly from the perspective of biological sciences in the US - of course there may be differences by field and location)